lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | cd7c1a9b0d992078bb4187e5743db22e11a67de8 | 0 | CyclopsMC/IntegratedDynamics | package org.cyclops.integrateddynamics.core.evaluate;
import com.google.common.base.Optional;
import net.minecraft.block.SoundType;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.cyclops.cyclopscore.helper.Helpers;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.operator.IOperator;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNumber;
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
import org.cyclops.integrateddynamics.api.logicprogrammer.IConfigRenderPattern;
import org.cyclops.integrateddynamics.core.evaluate.build.OperatorBuilder;
import org.cyclops.integrateddynamics.core.evaluate.operator.IterativeFunction;
import org.cyclops.integrateddynamics.core.evaluate.operator.OperatorBase;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.core.helper.L10NValues;
import javax.annotation.Nullable;
import java.util.Arrays;
/**
* Collection of operator builders.
* @author rubensworks
*/
public class OperatorBuilders {
// --------------- Logical builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("logical");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_1_PREFIX = LOGICAL.inputTypes(1, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_2 = LOGICAL.inputTypes(2, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Value propagators ---------------
public static final IOperatorValuePropagator<Integer, IValue> PROPAGATOR_INTEGER_VALUE = new IOperatorValuePropagator<Integer, IValue>() {
@Override
public IValue getOutput(Integer input) throws EvaluationException {
return ValueTypeInteger.ValueInteger.of(input);
}
};
public static final IOperatorValuePropagator<Long, IValue> PROPAGATOR_LONG_VALUE = new IOperatorValuePropagator<Long, IValue>() {
@Override
public IValue getOutput(Long input) throws EvaluationException {
return ValueTypeLong.ValueLong.of(input);
}
};
public static final IOperatorValuePropagator<Boolean, IValue> PROPAGATOR_BOOLEAN_VALUE = new IOperatorValuePropagator<Boolean, IValue>() {
@Override
public IValue getOutput(Boolean input) throws EvaluationException {
return ValueTypeBoolean.ValueBoolean.of(input);
}
};
public static final IOperatorValuePropagator<Double, IValue> PROPAGATOR_DOUBLE_VALUE = new IOperatorValuePropagator<Double, IValue>() {
@Override
public IValue getOutput(Double input) throws EvaluationException {
return ValueTypeDouble.ValueDouble.of(input);
}
};
public static final IOperatorValuePropagator<String, IValue> PROPAGATOR_STRING_VALUE = new IOperatorValuePropagator<String, IValue>() {
@Override
public IValue getOutput(String input) throws EvaluationException {
return ValueTypeString.ValueString.of(input);
}
};
public static final IOperatorValuePropagator<NBTTagCompound, IValue> PROPAGATOR_NBT_VALUE = new IOperatorValuePropagator<NBTTagCompound, IValue>() {
@Override
public IValue getOutput(NBTTagCompound input) throws EvaluationException {
return ValueTypeNbt.ValueNbt.of(input);
}
};
public static final IOperatorValuePropagator<ResourceLocation, ValueTypeString.ValueString> PROPAGATOR_RESOURCELOCATION_MODNAME = new IOperatorValuePropagator<ResourceLocation, ValueTypeString.ValueString>() {
@Override
public ValueTypeString.ValueString getOutput(ResourceLocation resourceLocation) throws EvaluationException {
String modName;
try {
String modId = Helpers.getModId(resourceLocation.getResourceDomain());
ModContainer mod = Loader.instance().getIndexedModList().get(modId);
modName = mod == null ? "Minecraft" : mod.getName();
} catch (NullPointerException e) {
modName = "";
}
return ValueTypeString.ValueString.of(modName);
}
};
// --------------- Arithmetic builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC = OperatorBuilder.forType(ValueTypes.CATEGORY_NUMBER).appendKind("arithmetic").conditionalOutputTypeDeriver(new OperatorBuilder.IConditionalOutputTypeDeriver() {
@Override
public IValueType getConditionalOutputType(OperatorBase operator, IVariable[] input) {
IValueType[] original = ValueHelpers.from(input);
IValueTypeNumber[] types = new IValueTypeNumber[original.length];
for(int i = 0; i < original.length; i++) {
if (original[i] == ValueTypes.CATEGORY_ANY) {
// This avoids a class-cast exception in cases where we don't know the exact type.
return ValueTypes.CATEGORY_ANY;
}
types[i] = (IValueTypeNumber) original[i];
}
return ValueTypes.CATEGORY_NUMBER.getLowestType(types);
}
});
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2 = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2_PREFIX = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.PREFIX_2);
// --------------- Integer builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("integer");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_1_SUFFIX = INTEGER.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.SUFFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_2 = INTEGER.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Relational builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("relational");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL_2 = RELATIONAL.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Binary builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("binary");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_1_PREFIX = BINARY.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_2 = BINARY.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- String builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING = OperatorBuilder.forType(ValueTypes.STRING).appendKind("string");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_1_PREFIX = STRING.inputTypes(1, ValueTypes.STRING).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_2 = STRING.inputTypes(2, ValueTypes.STRING).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Double builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE = OperatorBuilder.forType(ValueTypes.DOUBLE).appendKind("double");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE_1_PREFIX = DOUBLE.inputTypes(1, ValueTypes.DOUBLE).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- Nullable builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NULLABLE = OperatorBuilder.forType(ValueTypes.CATEGORY_NULLABLE).appendKind("general");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NULLABLE_1_PREFIX = NULLABLE.inputTypes(1, ValueTypes.CATEGORY_NULLABLE).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- List builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST = OperatorBuilder.forType(ValueTypes.LIST).appendKind("list");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST_1_PREFIX = LIST.inputTypes(1, ValueTypes.LIST).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- Block builders ---------------
public static final OperatorBuilder BLOCK = OperatorBuilder.forType(ValueTypes.OBJECT_BLOCK).appendKind("block");
public static final OperatorBuilder BLOCK_1_SUFFIX_LONG = BLOCK.inputTypes(1, ValueTypes.OBJECT_BLOCK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<SoundType>> BLOCK_SOUND = new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<SoundType>>() {
@SuppressWarnings("deprecation")
@Override
public Optional<SoundType> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeBlock.ValueBlock block = input.getValue(0);
if(block.getRawValue().isPresent()) {
return Optional.of(block.getRawValue().get().getBlock().getSoundType());
}
return Optional.absent();
}
};
// --------------- ItemStack builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_ITEMSTACK).appendKind("itemstack");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_1_SUFFIX_LONG = ITEMSTACK.inputTypes(1, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_2 = ITEMSTACK.inputTypes(2, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_1_INTEGER_1 = ITEMSTACK.inputTypes(new IValueType[]{ValueTypes.OBJECT_ITEMSTACK, ValueTypes.INTEGER}).renderPattern(IConfigRenderPattern.INFIX);
public static final IterativeFunction.PrePostBuilder<ItemStack, IValue> FUNCTION_ITEMSTACK = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, ItemStack>() {
@Override
public ItemStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
return a.getRawValue();
}
});
public static final IterativeFunction.PrePostBuilder<ItemStack, Integer> FUNCTION_ITEMSTACK_TO_INT =
FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<ItemStack, Boolean> FUNCTION_ITEMSTACK_TO_BOOLEAN =
FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, IValue> FUNCTION_ENERGYSTORAGEITEM = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IEnergyStorage>() {
@Override
public IEnergyStorage getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
if(!a.getRawValue().isEmpty() && a.getRawValue().hasCapability(CapabilityEnergy.ENERGY, null)) {
return a.getRawValue().getCapability(CapabilityEnergy.ENERGY, null);
}
return null;
}
});
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, Integer> FUNCTION_CONTAINERITEM_TO_INT =
FUNCTION_ENERGYSTORAGEITEM.appendPost(org.cyclops.integrateddynamics.core.evaluate.OperatorBuilders.PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, Boolean> FUNCTION_CONTAINERITEM_TO_BOOLEAN =
FUNCTION_ENERGYSTORAGEITEM.appendPost(org.cyclops.integrateddynamics.core.evaluate.OperatorBuilders.PROPAGATOR_BOOLEAN_VALUE);
// --------------- Entity builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY = OperatorBuilder.forType(ValueTypes.OBJECT_ENTITY).appendKind("entity");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY_1_SUFFIX_LONG = ENTITY.inputTypes(1, ValueTypes.OBJECT_ENTITY).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final IterativeFunction.PrePostBuilder<Entity, IValue> FUNCTION_ENTITY = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Entity>() {
@Override
public Entity getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeEntity.ValueEntity a = input.getValue(0);
return a.getRawValue().isPresent() ? a.getRawValue().get() : null;
}
});
public static final IterativeFunction.PrePostBuilder<Entity, Double> FUNCTION_ENTITY_TO_DOUBLE =
FUNCTION_ENTITY.appendPost(PROPAGATOR_DOUBLE_VALUE);
public static final IterativeFunction.PrePostBuilder<Entity, Boolean> FUNCTION_ENTITY_TO_BOOLEAN =
FUNCTION_ENTITY.appendPost(PROPAGATOR_BOOLEAN_VALUE);
// --------------- FluidStack builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_FLUIDSTACK).appendKind("fluidstack");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_1_SUFFIX_LONG = FLUIDSTACK.inputTypes(1, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_2 = FLUIDSTACK.inputTypes(2, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.INFIX);
public static final IterativeFunction.PrePostBuilder<FluidStack, IValue> FUNCTION_FLUIDSTACK = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, FluidStack>() {
@Override
public FluidStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeFluidStack.ValueFluidStack a = input.getValue(0);
return a.getRawValue().isPresent() ? a.getRawValue().get() : null;
}
});
public static final IterativeFunction.PrePostBuilder<FluidStack, Integer> FUNCTION_FLUIDSTACK_TO_INT =
FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<FluidStack, Boolean> FUNCTION_FLUIDSTACK_TO_BOOLEAN =
FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE);
// --------------- Operator builders ---------------
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_OPERATOR_TAKE_OPERATOR = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, OperatorBase.SafeVariablesGetter>>() {
@Override
public Pair<IOperator, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input.getValue(0)).getRawValue();
if (innerOperator.getRequiredInputLength() == 1) {
IValue applyingValue = input.getValue(1);
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(new IValueType[]{applyingValue.getType()});
if (error != null) {
throw new EvaluationException(error.localize());
}
} else {
if (!ValueHelpers.correspondsTo(input.getVariables()[1].getType(), innerOperator.getInputTypes()[0])) {
L10NHelpers.UnlocalizedString error = new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_WRONGCURRYINGTYPE,
new L10NHelpers.UnlocalizedString(innerOperator.getUnlocalizedName()),
new L10NHelpers.UnlocalizedString(input.getVariables()[0].getType().getUnlocalizedName()),
0,
new L10NHelpers.UnlocalizedString(innerOperator.getInputTypes()[0].getUnlocalizedName())
);
throw new EvaluationException(error.localize());
}
}
return Pair.<IOperator, OperatorBase.SafeVariablesGetter>of(innerOperator,
new OperatorBase.SafeVariablesGetter.Shifted(1, input.getVariables()));
}
});
public static final IterativeFunction.PrePostBuilder<IOperator, IValue> FUNCTION_ONE_OPERATOR = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IOperator>() {
@Override
public IOperator getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(0), ValueTypes.CATEGORY_ANY);
}
});
public static final IterativeFunction.PrePostBuilder<IOperator, IValue> FUNCTION_ONE_PREDICATE = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IOperator>() {
@Override
public IOperator getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(0));
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, IOperator>, IValue> FUNCTION_TWO_OPERATORS = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, IOperator>>() {
@Override
public Pair<IOperator, IOperator> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator second = getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(1), ValueTypes.CATEGORY_ANY);
IValueType secondInputType = second.getInputTypes()[0];
if (ValueHelpers.correspondsTo(secondInputType, ValueTypes.OPERATOR)) {
secondInputType = ValueTypes.CATEGORY_ANY;
}
IOperator first = getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(0), secondInputType);
return Pair.of(first, second);
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, IOperator>, IValue> FUNCTION_TWO_PREDICATES = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, IOperator>>() {
@Override
public Pair<IOperator, IOperator> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator first = getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(0));
IOperator second = getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(1));
return Pair.of(first, second);
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_OPERATOR_TAKE_OPERATOR_LIST = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, OperatorBase.SafeVariablesGetter>>() {
@Override
public Pair<IOperator, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input.getValue(0)).getRawValue();
IValue applyingValue = input.getValue(1);
if (!(applyingValue instanceof ValueTypeList.ValueList)) {
L10NHelpers.UnlocalizedString error = new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_WRONGTYPE,
"?",
new L10NHelpers.UnlocalizedString(applyingValue.getType().getUnlocalizedName()),
0,
new L10NHelpers.UnlocalizedString(ValueTypes.LIST.getUnlocalizedName())
);
throw new EvaluationException(error.localize());
}
ValueTypeList.ValueList applyingList = (ValueTypeList.ValueList) applyingValue;
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(new IValueType[]{applyingList.getRawValue().getValueType()});
if (error != null) {
throw new EvaluationException(error.localize());
}
return Pair.<IOperator, OperatorBase.SafeVariablesGetter>of(innerOperator,
new OperatorBase.SafeVariablesGetter.Shifted(1, input.getVariables()));
}
});
public static OperatorBuilder.IConditionalOutputTypeDeriver newOperatorConditionalOutputDeriver(final int consumeArguments) {
return new OperatorBuilder.IConditionalOutputTypeDeriver() {
@Override
public IValueType getConditionalOutputType(OperatorBase operator, IVariable[] input) {
try {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input[0].getValue()).getRawValue();
if (innerOperator.getRequiredInputLength() == consumeArguments) {
IVariable[] innerVariables = Arrays.copyOfRange(input, consumeArguments, input.length);
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(ValueHelpers.from(innerVariables));
if (error != null) {
return innerOperator.getOutputType();
}
return innerOperator.getConditionalOutputType(innerVariables);
} else {
return ValueTypes.OPERATOR;
}
} catch (EvaluationException e) {
return ValueTypes.CATEGORY_ANY;
}
}
};
};
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR = OperatorBuilder
.forType(ValueTypes.OPERATOR).appendKind("operator");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR_2_INFIX_LONG = OPERATOR
.inputTypes(new IValueType[]{ValueTypes.OPERATOR, ValueTypes.CATEGORY_ANY})
.renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR_1_PREFIX_LONG = OPERATOR
.inputTypes(new IValueType[]{ValueTypes.OPERATOR})
.renderPattern(IConfigRenderPattern.PREFIX_1_LONG);
// --------------- String builders ---------------
public static final IterativeFunction.PrePostBuilder<Pair<ResourceLocation, Integer>, IValue> FUNCTION_STRING_TO_RESOURCE_LOCATION = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<ResourceLocation, Integer>>() {
@Override
public Pair<ResourceLocation, Integer> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueTypeString.ValueString a = input.getValue(0);
String[] split = a.getRawValue().split(" ");
if (split.length > 2) {
throw new EvaluationException("Invalid name.");
}
ResourceLocation resourceLocation = new ResourceLocation(split[0]);
int meta = 0;
if (split.length > 1) {
try {
meta = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
throw new EvaluationException(e.getMessage());
}
}
return Pair.of(resourceLocation, meta);
}
});
// --------------- Operator helpers ---------------
/**
* Get the operator from a value in a safe manner.
* @param value The operator value.
* @param expectedOutput The expected output value type.
* @return The operator.
* @throws EvaluationException If the operator is not a predicate.
*/
public static IOperator getSafeOperator(ValueTypeOperator.ValueOperator value, IValueType expectedOutput) throws EvaluationException {
IOperator operator = value.getRawValue();
if (!ValueHelpers.correspondsTo(operator.getOutputType(), expectedOutput)) {
L10NHelpers.UnlocalizedString error =
new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_ILLEGALPROPERY,
expectedOutput, operator.getOutputType(), operator.getLocalizedNameFull());
throw new EvaluationException(error.localize());
}
return operator;
}
/**
* Get the predicate from a value in a safe manner.
* It is expected that the operator returns a boolean.
* @param value The operator value.
* @return The operator.
* @throws EvaluationException If the operator is not a predicate.
*/
public static IOperator getSafePredictate(ValueTypeOperator.ValueOperator value) throws EvaluationException {
return getSafeOperator(value, ValueTypes.BOOLEAN);
}
/**
* Create a type validator for operator operator type validators.
* @param expectedSubTypes The expected types that must be present in the operator (not including the first
* operator type itself.
* @return The type validator instance.
*/
public static OperatorBuilder.ITypeValidator createOperatorTypeValidator(final IValueType... expectedSubTypes) {
final int subOperatorLength = expectedSubTypes.length;
final L10NHelpers.UnlocalizedString expected = new L10NHelpers.UnlocalizedString(
org.cyclops.integrateddynamics.core.helper.Helpers.createPatternOfLength(subOperatorLength), ValueHelpers.from(expectedSubTypes));
return new OperatorBuilder.ITypeValidator() {
@Override
public L10NHelpers.UnlocalizedString validateTypes(OperatorBase operator, IValueType[] input) {
if (input.length == 0 || !ValueHelpers.correspondsTo(input[0], ValueTypes.OPERATOR)) {
String givenName = input.length == 0 ? "null" : input[0].getUnlocalizedName();
return new L10NHelpers.UnlocalizedString(L10NValues.VALUETYPE_ERROR_INVALIDOPERATOROPERATOR,
0, givenName);
}
if (input.length != subOperatorLength + 1) {
IValueType[] operatorInputs = Arrays.copyOfRange(input, 1, input.length);
L10NHelpers.UnlocalizedString given = new L10NHelpers.UnlocalizedString(
org.cyclops.integrateddynamics.core.helper.Helpers.createPatternOfLength(operatorInputs.length), ValueHelpers.from(operatorInputs));
return new L10NHelpers.UnlocalizedString(L10NValues.VALUETYPE_ERROR_INVALIDOPERATORSIGNATURE,
expected, given);
}
return null;
}
};
}
// --------------- NBT builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT = OperatorBuilder.forType(ValueTypes.NBT).appendKind("nbt");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_1_SUFFIX_LONG = NBT.inputTypes(ValueTypes.NBT).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_2 = NBT.inputTypes(ValueTypes.NBT, ValueTypes.STRING).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_3 = NBT.inputTypes(ValueTypes.NBT, ValueTypes.STRING, ValueTypes.STRING).output(ValueTypes.NBT).renderPattern(IConfigRenderPattern.INFIX_2);
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, IValue> FUNCTION_NBT = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, NBTTagCompound>() {
@Override
public NBTTagCompound getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return ((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue();
}
});
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, IValue> FUNCTION_NBT_ENTRY = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<NBTBase>>() {
@Override
public Optional<NBTBase> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return Optional.fromNullable(((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue()
.getTag(((ValueTypeString.ValueString) input.getValue(1)).getRawValue()));
}
});
public static final IterativeFunction.PrePostBuilder<Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_NBT_COPY_FOR_VALUE = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>>() {
@Override
public Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return Triple.of(((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue().copy(),
((ValueTypeString.ValueString) input.getValue(1)).getRawValue(),
new OperatorBase.SafeVariablesGetter.Shifted(2, input.getVariables()));
}
});
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, Integer> FUNCTION_NBT_TO_INT =
FUNCTION_NBT.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, Boolean> FUNCTION_NBT_TO_BOOLEAN =
FUNCTION_NBT.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Integer> FUNCTION_NBT_ENTRY_TO_INT =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Long> FUNCTION_NBT_ENTRY_TO_LONG =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_LONG_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Double> FUNCTION_NBT_ENTRY_TO_DOUBLE =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_DOUBLE_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Boolean> FUNCTION_NBT_ENTRY_TO_BOOLEAN =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, String> FUNCTION_NBT_ENTRY_TO_STRING =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_STRING_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, NBTTagCompound> FUNCTION_NBT_ENTRY_TO_NBT =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_NBT_VALUE);
public static final IterativeFunction.PrePostBuilder<Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>, NBTTagCompound>
FUNCTION_NBT_COPY_FOR_VALUE_TO_NBT = FUNCTION_NBT_COPY_FOR_VALUE.appendPost(PROPAGATOR_NBT_VALUE);
// --------------- Capability helpers ---------------
/**
* Helper function to create an operator function builder for deriving capabilities from an itemstack.
* @param capabilityReference The capability instance reference.
* @param <T> The capability type.
* @return The builder.
*/
public static <T> IterativeFunction.PrePostBuilder<T, IValue> getItemCapability(@Nullable final ICapabilityReference<T> capabilityReference) {
return IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, T>() {
@Override
public T getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
if(!a.getRawValue().isEmpty() && a.getRawValue().hasCapability(capabilityReference.getReference(), null)) {
return a.getRawValue().getCapability(capabilityReference.getReference(), null);
}
return null;
}
});
}
public static interface ICapabilityReference<T> {
public Capability<T> getReference();
}
}
| src/main/java/org/cyclops/integrateddynamics/core/evaluate/OperatorBuilders.java | package org.cyclops.integrateddynamics.core.evaluate;
import com.google.common.base.Optional;
import net.minecraft.block.SoundType;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.cyclops.cyclopscore.helper.Helpers;
import org.cyclops.cyclopscore.helper.L10NHelpers;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.operator.IOperator;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNumber;
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
import org.cyclops.integrateddynamics.api.logicprogrammer.IConfigRenderPattern;
import org.cyclops.integrateddynamics.core.evaluate.build.OperatorBuilder;
import org.cyclops.integrateddynamics.core.evaluate.operator.IterativeFunction;
import org.cyclops.integrateddynamics.core.evaluate.operator.OperatorBase;
import org.cyclops.integrateddynamics.core.evaluate.variable.*;
import org.cyclops.integrateddynamics.core.helper.L10NValues;
import javax.annotation.Nullable;
import java.util.Arrays;
/**
* Collection of operator builders.
* @author rubensworks
*/
public class OperatorBuilders {
// --------------- Logical builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("logical");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_1_PREFIX = LOGICAL.inputTypes(1, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_2 = LOGICAL.inputTypes(2, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Value propagators ---------------
public static final IOperatorValuePropagator<Integer, IValue> PROPAGATOR_INTEGER_VALUE = new IOperatorValuePropagator<Integer, IValue>() {
@Override
public IValue getOutput(Integer input) throws EvaluationException {
return ValueTypeInteger.ValueInteger.of(input);
}
};
public static final IOperatorValuePropagator<Long, IValue> PROPAGATOR_LONG_VALUE = new IOperatorValuePropagator<Long, IValue>() {
@Override
public IValue getOutput(Long input) throws EvaluationException {
return ValueTypeLong.ValueLong.of(input);
}
};
public static final IOperatorValuePropagator<Boolean, IValue> PROPAGATOR_BOOLEAN_VALUE = new IOperatorValuePropagator<Boolean, IValue>() {
@Override
public IValue getOutput(Boolean input) throws EvaluationException {
return ValueTypeBoolean.ValueBoolean.of(input);
}
};
public static final IOperatorValuePropagator<Double, IValue> PROPAGATOR_DOUBLE_VALUE = new IOperatorValuePropagator<Double, IValue>() {
@Override
public IValue getOutput(Double input) throws EvaluationException {
return ValueTypeDouble.ValueDouble.of(input);
}
};
public static final IOperatorValuePropagator<String, IValue> PROPAGATOR_STRING_VALUE = new IOperatorValuePropagator<String, IValue>() {
@Override
public IValue getOutput(String input) throws EvaluationException {
return ValueTypeString.ValueString.of(input);
}
};
public static final IOperatorValuePropagator<NBTTagCompound, IValue> PROPAGATOR_NBT_VALUE = new IOperatorValuePropagator<NBTTagCompound, IValue>() {
@Override
public IValue getOutput(NBTTagCompound input) throws EvaluationException {
return ValueTypeNbt.ValueNbt.of(input);
}
};
public static final IOperatorValuePropagator<ResourceLocation, ValueTypeString.ValueString> PROPAGATOR_RESOURCELOCATION_MODNAME = new IOperatorValuePropagator<ResourceLocation, ValueTypeString.ValueString>() {
@Override
public ValueTypeString.ValueString getOutput(ResourceLocation resourceLocation) throws EvaluationException {
String modName;
try {
String modId = Helpers.getModId(resourceLocation.getResourceDomain());
ModContainer mod = Loader.instance().getIndexedModList().get(modId);
modName = mod == null ? "Minecraft" : mod.getName();
} catch (NullPointerException e) {
modName = "";
}
return ValueTypeString.ValueString.of(modName);
}
};
// --------------- Arithmetic builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC = OperatorBuilder.forType(ValueTypes.CATEGORY_NUMBER).appendKind("arithmetic").conditionalOutputTypeDeriver(new OperatorBuilder.IConditionalOutputTypeDeriver() {
@Override
public IValueType getConditionalOutputType(OperatorBase operator, IVariable[] input) {
IValueType[] original = ValueHelpers.from(input);
IValueTypeNumber[] types = new IValueTypeNumber[original.length];
for(int i = 0; i < original.length; i++) {
types[i] = (IValueTypeNumber) original[i];
}
return ValueTypes.CATEGORY_NUMBER.getLowestType(types);
}
});
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2 = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2_PREFIX = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.PREFIX_2);
// --------------- Integer builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("integer");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_1_SUFFIX = INTEGER.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.SUFFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_2 = INTEGER.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Relational builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("relational");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL_2 = RELATIONAL.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Binary builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("binary");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_1_PREFIX = BINARY.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_2 = BINARY.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX);
// --------------- String builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING = OperatorBuilder.forType(ValueTypes.STRING).appendKind("string");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_1_PREFIX = STRING.inputTypes(1, ValueTypes.STRING).renderPattern(IConfigRenderPattern.PREFIX_1);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_2 = STRING.inputTypes(2, ValueTypes.STRING).renderPattern(IConfigRenderPattern.INFIX);
// --------------- Double builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE = OperatorBuilder.forType(ValueTypes.DOUBLE).appendKind("double");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE_1_PREFIX = DOUBLE.inputTypes(1, ValueTypes.DOUBLE).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- Nullable builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NULLABLE = OperatorBuilder.forType(ValueTypes.CATEGORY_NULLABLE).appendKind("general");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NULLABLE_1_PREFIX = NULLABLE.inputTypes(1, ValueTypes.CATEGORY_NULLABLE).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- List builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST = OperatorBuilder.forType(ValueTypes.LIST).appendKind("list");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST_1_PREFIX = LIST.inputTypes(1, ValueTypes.LIST).renderPattern(IConfigRenderPattern.PREFIX_1);
// --------------- Block builders ---------------
public static final OperatorBuilder BLOCK = OperatorBuilder.forType(ValueTypes.OBJECT_BLOCK).appendKind("block");
public static final OperatorBuilder BLOCK_1_SUFFIX_LONG = BLOCK.inputTypes(1, ValueTypes.OBJECT_BLOCK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<SoundType>> BLOCK_SOUND = new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<SoundType>>() {
@SuppressWarnings("deprecation")
@Override
public Optional<SoundType> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeBlock.ValueBlock block = input.getValue(0);
if(block.getRawValue().isPresent()) {
return Optional.of(block.getRawValue().get().getBlock().getSoundType());
}
return Optional.absent();
}
};
// --------------- ItemStack builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_ITEMSTACK).appendKind("itemstack");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_1_SUFFIX_LONG = ITEMSTACK.inputTypes(1, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_2 = ITEMSTACK.inputTypes(2, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_1_INTEGER_1 = ITEMSTACK.inputTypes(new IValueType[]{ValueTypes.OBJECT_ITEMSTACK, ValueTypes.INTEGER}).renderPattern(IConfigRenderPattern.INFIX);
public static final IterativeFunction.PrePostBuilder<ItemStack, IValue> FUNCTION_ITEMSTACK = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, ItemStack>() {
@Override
public ItemStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
return a.getRawValue();
}
});
public static final IterativeFunction.PrePostBuilder<ItemStack, Integer> FUNCTION_ITEMSTACK_TO_INT =
FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<ItemStack, Boolean> FUNCTION_ITEMSTACK_TO_BOOLEAN =
FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, IValue> FUNCTION_ENERGYSTORAGEITEM = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IEnergyStorage>() {
@Override
public IEnergyStorage getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
if(!a.getRawValue().isEmpty() && a.getRawValue().hasCapability(CapabilityEnergy.ENERGY, null)) {
return a.getRawValue().getCapability(CapabilityEnergy.ENERGY, null);
}
return null;
}
});
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, Integer> FUNCTION_CONTAINERITEM_TO_INT =
FUNCTION_ENERGYSTORAGEITEM.appendPost(org.cyclops.integrateddynamics.core.evaluate.OperatorBuilders.PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<IEnergyStorage, Boolean> FUNCTION_CONTAINERITEM_TO_BOOLEAN =
FUNCTION_ENERGYSTORAGEITEM.appendPost(org.cyclops.integrateddynamics.core.evaluate.OperatorBuilders.PROPAGATOR_BOOLEAN_VALUE);
// --------------- Entity builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY = OperatorBuilder.forType(ValueTypes.OBJECT_ENTITY).appendKind("entity");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY_1_SUFFIX_LONG = ENTITY.inputTypes(1, ValueTypes.OBJECT_ENTITY).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final IterativeFunction.PrePostBuilder<Entity, IValue> FUNCTION_ENTITY = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Entity>() {
@Override
public Entity getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeEntity.ValueEntity a = input.getValue(0);
return a.getRawValue().isPresent() ? a.getRawValue().get() : null;
}
});
public static final IterativeFunction.PrePostBuilder<Entity, Double> FUNCTION_ENTITY_TO_DOUBLE =
FUNCTION_ENTITY.appendPost(PROPAGATOR_DOUBLE_VALUE);
public static final IterativeFunction.PrePostBuilder<Entity, Boolean> FUNCTION_ENTITY_TO_BOOLEAN =
FUNCTION_ENTITY.appendPost(PROPAGATOR_BOOLEAN_VALUE);
// --------------- FluidStack builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_FLUIDSTACK).appendKind("fluidstack");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_1_SUFFIX_LONG = FLUIDSTACK.inputTypes(1, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_2 = FLUIDSTACK.inputTypes(2, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.INFIX);
public static final IterativeFunction.PrePostBuilder<FluidStack, IValue> FUNCTION_FLUIDSTACK = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, FluidStack>() {
@Override
public FluidStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeFluidStack.ValueFluidStack a = input.getValue(0);
return a.getRawValue().isPresent() ? a.getRawValue().get() : null;
}
});
public static final IterativeFunction.PrePostBuilder<FluidStack, Integer> FUNCTION_FLUIDSTACK_TO_INT =
FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<FluidStack, Boolean> FUNCTION_FLUIDSTACK_TO_BOOLEAN =
FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE);
// --------------- Operator builders ---------------
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_OPERATOR_TAKE_OPERATOR = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, OperatorBase.SafeVariablesGetter>>() {
@Override
public Pair<IOperator, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input.getValue(0)).getRawValue();
if (innerOperator.getRequiredInputLength() == 1) {
IValue applyingValue = input.getValue(1);
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(new IValueType[]{applyingValue.getType()});
if (error != null) {
throw new EvaluationException(error.localize());
}
} else {
if (!ValueHelpers.correspondsTo(input.getVariables()[1].getType(), innerOperator.getInputTypes()[0])) {
L10NHelpers.UnlocalizedString error = new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_WRONGCURRYINGTYPE,
new L10NHelpers.UnlocalizedString(innerOperator.getUnlocalizedName()),
new L10NHelpers.UnlocalizedString(input.getVariables()[0].getType().getUnlocalizedName()),
0,
new L10NHelpers.UnlocalizedString(innerOperator.getInputTypes()[0].getUnlocalizedName())
);
throw new EvaluationException(error.localize());
}
}
return Pair.<IOperator, OperatorBase.SafeVariablesGetter>of(innerOperator,
new OperatorBase.SafeVariablesGetter.Shifted(1, input.getVariables()));
}
});
public static final IterativeFunction.PrePostBuilder<IOperator, IValue> FUNCTION_ONE_OPERATOR = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IOperator>() {
@Override
public IOperator getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(0), ValueTypes.CATEGORY_ANY);
}
});
public static final IterativeFunction.PrePostBuilder<IOperator, IValue> FUNCTION_ONE_PREDICATE = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, IOperator>() {
@Override
public IOperator getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(0));
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, IOperator>, IValue> FUNCTION_TWO_OPERATORS = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, IOperator>>() {
@Override
public Pair<IOperator, IOperator> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator second = getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(1), ValueTypes.CATEGORY_ANY);
IValueType secondInputType = second.getInputTypes()[0];
if (ValueHelpers.correspondsTo(secondInputType, ValueTypes.OPERATOR)) {
secondInputType = ValueTypes.CATEGORY_ANY;
}
IOperator first = getSafeOperator((ValueTypeOperator.ValueOperator) input.getValue(0), secondInputType);
return Pair.of(first, second);
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, IOperator>, IValue> FUNCTION_TWO_PREDICATES = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, IOperator>>() {
@Override
public Pair<IOperator, IOperator> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator first = getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(0));
IOperator second = getSafePredictate((ValueTypeOperator.ValueOperator) input.getValue(1));
return Pair.of(first, second);
}
});
public static final IterativeFunction.PrePostBuilder<Pair<IOperator, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_OPERATOR_TAKE_OPERATOR_LIST = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<IOperator, OperatorBase.SafeVariablesGetter>>() {
@Override
public Pair<IOperator, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input.getValue(0)).getRawValue();
IValue applyingValue = input.getValue(1);
if (!(applyingValue instanceof ValueTypeList.ValueList)) {
L10NHelpers.UnlocalizedString error = new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_WRONGTYPE,
"?",
new L10NHelpers.UnlocalizedString(applyingValue.getType().getUnlocalizedName()),
0,
new L10NHelpers.UnlocalizedString(ValueTypes.LIST.getUnlocalizedName())
);
throw new EvaluationException(error.localize());
}
ValueTypeList.ValueList applyingList = (ValueTypeList.ValueList) applyingValue;
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(new IValueType[]{applyingList.getRawValue().getValueType()});
if (error != null) {
throw new EvaluationException(error.localize());
}
return Pair.<IOperator, OperatorBase.SafeVariablesGetter>of(innerOperator,
new OperatorBase.SafeVariablesGetter.Shifted(1, input.getVariables()));
}
});
public static OperatorBuilder.IConditionalOutputTypeDeriver newOperatorConditionalOutputDeriver(final int consumeArguments) {
return new OperatorBuilder.IConditionalOutputTypeDeriver() {
@Override
public IValueType getConditionalOutputType(OperatorBase operator, IVariable[] input) {
try {
IOperator innerOperator = ((ValueTypeOperator.ValueOperator) input[0].getValue()).getRawValue();
if (innerOperator.getRequiredInputLength() == consumeArguments) {
IVariable[] innerVariables = Arrays.copyOfRange(input, consumeArguments, input.length);
L10NHelpers.UnlocalizedString error = innerOperator.validateTypes(ValueHelpers.from(innerVariables));
if (error != null) {
return innerOperator.getOutputType();
}
return innerOperator.getConditionalOutputType(innerVariables);
} else {
return ValueTypes.OPERATOR;
}
} catch (EvaluationException e) {
return ValueTypes.CATEGORY_ANY;
}
}
};
};
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR = OperatorBuilder
.forType(ValueTypes.OPERATOR).appendKind("operator");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR_2_INFIX_LONG = OPERATOR
.inputTypes(new IValueType[]{ValueTypes.OPERATOR, ValueTypes.CATEGORY_ANY})
.renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> OPERATOR_1_PREFIX_LONG = OPERATOR
.inputTypes(new IValueType[]{ValueTypes.OPERATOR})
.renderPattern(IConfigRenderPattern.PREFIX_1_LONG);
// --------------- String builders ---------------
public static final IterativeFunction.PrePostBuilder<Pair<ResourceLocation, Integer>, IValue> FUNCTION_STRING_TO_RESOURCE_LOCATION = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Pair<ResourceLocation, Integer>>() {
@Override
public Pair<ResourceLocation, Integer> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueTypeString.ValueString a = input.getValue(0);
String[] split = a.getRawValue().split(" ");
if (split.length > 2) {
throw new EvaluationException("Invalid name.");
}
ResourceLocation resourceLocation = new ResourceLocation(split[0]);
int meta = 0;
if (split.length > 1) {
try {
meta = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
throw new EvaluationException(e.getMessage());
}
}
return Pair.of(resourceLocation, meta);
}
});
// --------------- Operator helpers ---------------
/**
* Get the operator from a value in a safe manner.
* @param value The operator value.
* @param expectedOutput The expected output value type.
* @return The operator.
* @throws EvaluationException If the operator is not a predicate.
*/
public static IOperator getSafeOperator(ValueTypeOperator.ValueOperator value, IValueType expectedOutput) throws EvaluationException {
IOperator operator = value.getRawValue();
if (!ValueHelpers.correspondsTo(operator.getOutputType(), expectedOutput)) {
L10NHelpers.UnlocalizedString error =
new L10NHelpers.UnlocalizedString(L10NValues.OPERATOR_ERROR_ILLEGALPROPERY,
expectedOutput, operator.getOutputType(), operator.getLocalizedNameFull());
throw new EvaluationException(error.localize());
}
return operator;
}
/**
* Get the predicate from a value in a safe manner.
* It is expected that the operator returns a boolean.
* @param value The operator value.
* @return The operator.
* @throws EvaluationException If the operator is not a predicate.
*/
public static IOperator getSafePredictate(ValueTypeOperator.ValueOperator value) throws EvaluationException {
return getSafeOperator(value, ValueTypes.BOOLEAN);
}
/**
* Create a type validator for operator operator type validators.
* @param expectedSubTypes The expected types that must be present in the operator (not including the first
* operator type itself.
* @return The type validator instance.
*/
public static OperatorBuilder.ITypeValidator createOperatorTypeValidator(final IValueType... expectedSubTypes) {
final int subOperatorLength = expectedSubTypes.length;
final L10NHelpers.UnlocalizedString expected = new L10NHelpers.UnlocalizedString(
org.cyclops.integrateddynamics.core.helper.Helpers.createPatternOfLength(subOperatorLength), ValueHelpers.from(expectedSubTypes));
return new OperatorBuilder.ITypeValidator() {
@Override
public L10NHelpers.UnlocalizedString validateTypes(OperatorBase operator, IValueType[] input) {
if (input.length == 0 || !ValueHelpers.correspondsTo(input[0], ValueTypes.OPERATOR)) {
String givenName = input.length == 0 ? "null" : input[0].getUnlocalizedName();
return new L10NHelpers.UnlocalizedString(L10NValues.VALUETYPE_ERROR_INVALIDOPERATOROPERATOR,
0, givenName);
}
if (input.length != subOperatorLength + 1) {
IValueType[] operatorInputs = Arrays.copyOfRange(input, 1, input.length);
L10NHelpers.UnlocalizedString given = new L10NHelpers.UnlocalizedString(
org.cyclops.integrateddynamics.core.helper.Helpers.createPatternOfLength(operatorInputs.length), ValueHelpers.from(operatorInputs));
return new L10NHelpers.UnlocalizedString(L10NValues.VALUETYPE_ERROR_INVALIDOPERATORSIGNATURE,
expected, given);
}
return null;
}
};
}
// --------------- NBT builders ---------------
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT = OperatorBuilder.forType(ValueTypes.NBT).appendKind("nbt");
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_1_SUFFIX_LONG = NBT.inputTypes(ValueTypes.NBT).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_2 = NBT.inputTypes(ValueTypes.NBT, ValueTypes.STRING).renderPattern(IConfigRenderPattern.INFIX);
public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> NBT_3 = NBT.inputTypes(ValueTypes.NBT, ValueTypes.STRING, ValueTypes.STRING).output(ValueTypes.NBT).renderPattern(IConfigRenderPattern.INFIX_2);
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, IValue> FUNCTION_NBT = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, NBTTagCompound>() {
@Override
public NBTTagCompound getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return ((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue();
}
});
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, IValue> FUNCTION_NBT_ENTRY = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Optional<NBTBase>>() {
@Override
public Optional<NBTBase> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return Optional.fromNullable(((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue()
.getTag(((ValueTypeString.ValueString) input.getValue(1)).getRawValue()));
}
});
public static final IterativeFunction.PrePostBuilder<Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>, IValue> FUNCTION_NBT_COPY_FOR_VALUE = IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>>() {
@Override
public Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter> getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
return Triple.of(((ValueTypeNbt.ValueNbt) input.getValue(0)).getRawValue().copy(),
((ValueTypeString.ValueString) input.getValue(1)).getRawValue(),
new OperatorBase.SafeVariablesGetter.Shifted(2, input.getVariables()));
}
});
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, Integer> FUNCTION_NBT_TO_INT =
FUNCTION_NBT.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<NBTTagCompound, Boolean> FUNCTION_NBT_TO_BOOLEAN =
FUNCTION_NBT.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Integer> FUNCTION_NBT_ENTRY_TO_INT =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_INTEGER_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Long> FUNCTION_NBT_ENTRY_TO_LONG =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_LONG_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Double> FUNCTION_NBT_ENTRY_TO_DOUBLE =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_DOUBLE_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, Boolean> FUNCTION_NBT_ENTRY_TO_BOOLEAN =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_BOOLEAN_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, String> FUNCTION_NBT_ENTRY_TO_STRING =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_STRING_VALUE);
public static final IterativeFunction.PrePostBuilder<Optional<NBTBase>, NBTTagCompound> FUNCTION_NBT_ENTRY_TO_NBT =
FUNCTION_NBT_ENTRY.appendPost(PROPAGATOR_NBT_VALUE);
public static final IterativeFunction.PrePostBuilder<Triple<NBTTagCompound, String, OperatorBase.SafeVariablesGetter>, NBTTagCompound>
FUNCTION_NBT_COPY_FOR_VALUE_TO_NBT = FUNCTION_NBT_COPY_FOR_VALUE.appendPost(PROPAGATOR_NBT_VALUE);
// --------------- Capability helpers ---------------
/**
* Helper function to create an operator function builder for deriving capabilities from an itemstack.
* @param capabilityReference The capability instance reference.
* @param <T> The capability type.
* @return The builder.
*/
public static <T> IterativeFunction.PrePostBuilder<T, IValue> getItemCapability(@Nullable final ICapabilityReference<T> capabilityReference) {
return IterativeFunction.PrePostBuilder.begin()
.appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, T>() {
@Override
public T getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0);
if(!a.getRawValue().isEmpty() && a.getRawValue().hasCapability(capabilityReference.getReference(), null)) {
return a.getRawValue().getCapability(capabilityReference.getReference(), null);
}
return null;
}
});
}
public static interface ICapabilityReference<T> {
public Capability<T> getReference();
}
}
| Fix crash due to casting ANY to NUMBER
| src/main/java/org/cyclops/integrateddynamics/core/evaluate/OperatorBuilders.java | Fix crash due to casting ANY to NUMBER | <ide><path>rc/main/java/org/cyclops/integrateddynamics/core/evaluate/OperatorBuilders.java
<ide> IValueType[] original = ValueHelpers.from(input);
<ide> IValueTypeNumber[] types = new IValueTypeNumber[original.length];
<ide> for(int i = 0; i < original.length; i++) {
<add> if (original[i] == ValueTypes.CATEGORY_ANY) {
<add> // This avoids a class-cast exception in cases where we don't know the exact type.
<add> return ValueTypes.CATEGORY_ANY;
<add> }
<ide> types[i] = (IValueTypeNumber) original[i];
<ide> }
<ide> return ValueTypes.CATEGORY_NUMBER.getLowestType(types); |
|
Java | agpl-3.0 | 3623a914b3fb6a678c755306e4c0a1ed7c502965 | 0 | wolffcm/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,kumarrus/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,VoltDB/voltdb,ingted/voltdb,kumarrus/voltdb,VoltDB/voltdb,creative-quant/voltdb,zuowang/voltdb,paulmartel/voltdb,deerwalk/voltdb,flybird119/voltdb,ingted/voltdb,wolffcm/voltdb,zuowang/voltdb,ingted/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,zuowang/voltdb,kumarrus/voltdb,VoltDB/voltdb,paulmartel/voltdb,ingted/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,flybird119/voltdb,paulmartel/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,zuowang/voltdb,flybird119/voltdb,deerwalk/voltdb,flybird119/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,wolffcm/voltdb,ingted/voltdb,creative-quant/voltdb,wolffcm/voltdb,VoltDB/voltdb,flybird119/voltdb,creative-quant/voltdb,VoltDB/voltdb,zuowang/voltdb,flybird119/voltdb,ingted/voltdb,creative-quant/voltdb,wolffcm/voltdb,deerwalk/voltdb,flybird119/voltdb,migue/voltdb,zuowang/voltdb,migue/voltdb,migue/voltdb,VoltDB/voltdb,ingted/voltdb,zuowang/voltdb,migue/voltdb,wolffcm/voltdb,kumarrus/voltdb,migue/voltdb,flybird119/voltdb,migue/voltdb,creative-quant/voltdb,ingted/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,zuowang/voltdb,migue/voltdb,kumarrus/voltdb,creative-quant/voltdb,paulmartel/voltdb,paulmartel/voltdb,migue/voltdb,kumarrus/voltdb,paulmartel/voltdb,deerwalk/voltdb,wolffcm/voltdb,paulmartel/voltdb,deerwalk/voltdb | /* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.iv2;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltcore.zk.BabySitter;
import org.voltcore.zk.LeaderElector;
import org.voltcore.zk.ZKUtil;
import org.voltdb.Promotable;
import org.voltdb.SnapshotFormat;
import org.voltdb.TheHashinator;
import org.voltdb.VoltDB;
import org.voltdb.VoltZK;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.sysprocs.saverestore.SnapshotUtil.SnapshotResponseHandler;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.collect.ImmutableSortedMap;
import com.google_voltpatches.common.util.concurrent.SettableFuture;
/**
* LeaderAppointer handles centralized appointment of partition leaders across
* the partition. This is primarily so that the leaders can be evenly
* distributed throughout the cluster, reducing bottlenecks (at least at
* startup). As a side-effect, this service also controls the initial startup
* of the cluster, blocking operation until each partition has a k-safe set of
* replicas, each partition has a leader, and the MPI has started.
*/
public class LeaderAppointer implements Promotable
{
private static final VoltLogger tmLog = new VoltLogger("TM");
private enum AppointerState {
INIT, // Initial start state, used to inhibit ZK callback actions
CLUSTER_START, // indicates that we're doing the initial cluster startup
DONE // indicates normal running conditions, including repair
}
private final HostMessenger m_hostMessenger;
private final ZooKeeper m_zk;
// This should only be accessed through getInitialPartitionCount() on cluster startup.
private final int m_initialPartitionCount;
private final Map<Integer, BabySitter> m_partitionWatchers;
private final LeaderCache m_iv2appointees;
private final LeaderCache m_iv2masters;
private final Map<Integer, PartitionCallback> m_callbacks;
private final int m_kfactor;
private final JSONObject m_topo;
private final MpInitiator m_MPI;
private final AtomicReference<AppointerState> m_state =
new AtomicReference<AppointerState>(AppointerState.INIT);
private SettableFuture<Object> m_startupLatch = null;
private final boolean m_partitionDetectionEnabled;
private boolean m_partitionDetected = false;
private boolean m_usingCommandLog = false;
private final AtomicBoolean m_replayComplete = new AtomicBoolean(false);
private final KSafetyStats m_stats;
/*
* Track partitions that are cleaned up during election/promotion etc.
* This eliminates the race where the cleanup occurs while constructing babysitters
* for partitions that end up being removed.
*/
private HashSet<Integer> m_removedPartitionsAtPromotionTime = null;
// Provide a single single-threaded executor service to all the BabySitters for each partition.
// This will guarantee that the ordering of events generated by ZooKeeper is preserved in the
// handling of callbacks in LeaderAppointer.
private final ExecutorService m_es =
CoreUtils.getCachedSingleThreadExecutor("LeaderAppointer-Babysitters", 15000);
private final SnapshotSchedule m_partSnapshotSchedule;
private final SnapshotResponseHandler m_snapshotHandler =
new SnapshotResponseHandler() {
@Override
public void handleResponse(ClientResponse resp)
{
if (resp == null) {
VoltDB.crashLocalVoltDB("Received a null response to a snapshot initiation request. " +
"This should be impossible.", true, null);
}
else if (resp.getStatus() != ClientResponse.SUCCESS) {
tmLog.info("Failed to complete partition detection snapshot, status: " + resp.getStatus() +
", reason: " + resp.getStatusString());
tmLog.info("Retrying partition detection snapshot...");
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
else if (!SnapshotUtil.didSnapshotRequestSucceed(resp.getResults())) {
VoltDB.crashGlobalVoltDB("Unable to complete partition detection snapshot: " +
resp.getResults()[0], false, null);
}
else {
VoltDB.crashGlobalVoltDB("Partition detection snapshot completed. Shutting down.",
false, null);
}
}
};
private class PartitionCallback extends BabySitter.Callback
{
final int m_partitionId;
final Set<Long> m_replicas;
long m_currentLeader;
/** Constructor used when we know (or think we know) who the leader for this partition is */
PartitionCallback(int partitionId, long currentLeader)
{
this(partitionId);
// Try to be clever for repair. Create ourselves with the current leader set to
// whatever is in the LeaderCache, and claim that replica exists, then let the
// first run() call fix the world.
m_currentLeader = currentLeader;
m_replicas.add(currentLeader);
}
/** Constructor used at startup when there is no leader */
PartitionCallback(int partitionId)
{
m_partitionId = partitionId;
// A bit of a hack, but we should never end up with an HSID as Long.MAX_VALUE
m_currentLeader = Long.MAX_VALUE;
m_replicas = new HashSet<Long>();
}
@Override
public void run(List<String> children)
{
List<Long> updatedHSIds = VoltZK.childrenToReplicaHSIds(children);
// compute previously unseen HSId set in the callback list
Set<Long> newHSIds = new HashSet<Long>(updatedHSIds);
newHSIds.removeAll(m_replicas);
tmLog.debug("Newly seen replicas: " + CoreUtils.hsIdCollectionToString(newHSIds));
// compute previously seen but now vanished from the callback list HSId set
Set<Long> missingHSIds = new HashSet<Long>(m_replicas);
missingHSIds.removeAll(updatedHSIds);
tmLog.debug("Newly dead replicas: " + CoreUtils.hsIdCollectionToString(missingHSIds));
tmLog.debug("Handling babysitter callback for partition " + m_partitionId + ": children: " +
CoreUtils.hsIdCollectionToString(updatedHSIds));
if (m_state.get() == AppointerState.CLUSTER_START) {
// We can't yet tolerate a host failure during startup. Crash it all
if (missingHSIds.size() > 0) {
VoltDB.crashGlobalVoltDB("Node failure detected during startup.", false, null);
}
// ENG-3166: Eventually we would like to get rid of the extra replicas beyond k_factor,
// but for now we just look to see how many replicas of this partition we actually expect
// and gate leader assignment on that many copies showing up.
int replicaCount = m_kfactor + 1;
JSONArray parts;
try {
parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == m_partitionId) {
replicaCount = aPartition.getJSONArray("replicas").length();
}
}
} catch (JSONException e) {
// Ignore and just assume the normal number of replicas
}
if (children.size() == replicaCount) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
else {
tmLog.info("Waiting on " + ((m_kfactor + 1) - children.size()) + " more nodes " +
"for k-safety before startup");
}
}
else {
Set<Integer> hostsOnRing = new HashSet<Integer>();
// Check for k-safety
if (!isClusterKSafe(hostsOnRing)) {
VoltDB.crashGlobalVoltDB("Some partitions have no replicas. Cluster has become unviable.",
false, null);
}
// Check if replay has completed
if (m_replayComplete.get() == false) {
VoltDB.crashGlobalVoltDB("Detected node failure during command log replay. Cluster will shut down.",
false, null);
}
// Check to see if there's been a possible network partition and we're not already handling it
if (m_partitionDetectionEnabled && !m_partitionDetected) {
doPartitionDetectionActivities(hostsOnRing);
}
// If we survived the above gauntlet of fail, appoint a new leader for this partition.
if (missingHSIds.contains(m_currentLeader)) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
// If this partition doesn't have a leader yet, and we have new replicas added,
// elect a leader.
if (m_currentLeader == Long.MAX_VALUE && !updatedHSIds.isEmpty()) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
}
m_replicas.clear();
m_replicas.addAll(updatedHSIds);
}
}
/* We'll use this callback purely for startup so we can discover when all
* the leaders we have appointed have completed their promotions and
* published themselves to Zookeeper */
LeaderCache.Callback m_masterCallback = new LeaderCache.Callback()
{
@Override
public void run(ImmutableMap<Integer, Long> cache) {
Set<Long> currentLeaders = new HashSet<Long>(cache.values());
tmLog.debug("Updated leaders: " + currentLeaders);
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
if (currentLeaders.size() == getInitialPartitionCount()) {
tmLog.debug("Leader appointment complete, promoting MPI and unblocking.");
m_state.set(AppointerState.DONE);
m_MPI.acceptPromotion();
m_startupLatch.set(null);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
}
};
Watcher m_partitionCallback = new Watcher() {
@Override
public void process(WatchedEvent event)
{
m_es.submit(new Runnable() {
@Override
public void run()
{
try {
List<String> children = m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
tmLog.info("Noticed partition change " + children + ", " +
"currenctly watching " + m_partitionWatchers.keySet());
for (String child : children) {
int pid = LeaderElector.getPartitionFromElectionDir(child);
if (!m_partitionWatchers.containsKey(pid) && pid != MpInitiator.MP_INIT_PID) {
watchPartition(pid, m_es, false);
}
}
tmLog.info("Done " + m_partitionWatchers.keySet());
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Cannot read leader initiator directory", false, e);
}
}
});
}
};
public LeaderAppointer(HostMessenger hm, int numberOfPartitions,
int kfactor, boolean partitionDetectionEnabled,
SnapshotSchedule partitionSnapshotSchedule,
boolean usingCommandLog,
JSONObject topology, MpInitiator mpi,
KSafetyStats stats)
{
m_hostMessenger = hm;
m_zk = hm.getZK();
m_kfactor = kfactor;
m_topo = topology;
m_MPI = mpi;
m_initialPartitionCount = numberOfPartitions;
m_callbacks = new HashMap<Integer, PartitionCallback>();
m_partitionWatchers = new HashMap<Integer, BabySitter>();
m_iv2appointees = new LeaderCache(m_zk, VoltZK.iv2appointees);
m_iv2masters = new LeaderCache(m_zk, VoltZK.iv2masters, m_masterCallback);
m_partitionDetectionEnabled = partitionDetectionEnabled;
m_partSnapshotSchedule = partitionSnapshotSchedule;
m_usingCommandLog = usingCommandLog;
m_stats = stats;
}
@Override
public void acceptPromotion() throws InterruptedException, ExecutionException
{
final SettableFuture<Object> blocker = SettableFuture.create();
try {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
acceptPromotionImpl(blocker);
} catch (Throwable t) {
blocker.setException(t);
}
}
});
blocker.get();
} catch (RejectedExecutionException e) {
if (m_es.isShutdown()) return;
throw new RejectedExecutionException(e);
}
}
private void acceptPromotionImpl(final SettableFuture<Object> blocker) throws InterruptedException, ExecutionException, KeeperException {
// Crank up the leader caches. Use blocking startup so that we'll have valid point-in-time caches later.
m_iv2appointees.start(true);
m_iv2masters.start(true);
ImmutableMap<Integer, Long> appointees = m_iv2appointees.pointInTimeCache();
// Figure out what conditions we assumed leadership under.
if (appointees.size() == 0)
{
tmLog.debug("LeaderAppointer in startup");
m_state.set(AppointerState.CLUSTER_START);
}
//INIT is the default before promotion at runtime. Don't do this startup check
//Let the rest of the promotion run and determine k-safety which is the else block.
else if (m_state.get() == AppointerState.INIT && !VoltDB.instance().isRunning()) {
ImmutableMap<Integer, Long> masters = m_iv2masters.pointInTimeCache();
try {
if ((appointees.size() < getInitialPartitionCount()) ||
(masters.size() < getInitialPartitionCount()) ||
(appointees.size() != masters.size())) {
// If we are promoted and the appointees or masters set is partial, the previous appointer failed
// during startup (at least for now, until we add remove a partition on the fly).
VoltDB.crashGlobalVoltDB("Detected failure during startup, unable to start", false, null);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
else {
tmLog.debug("LeaderAppointer in repair");
m_state.set(AppointerState.DONE);
}
if (m_state.get() == AppointerState.CLUSTER_START) {
// Need to block the return of acceptPromotion until after the MPI is promoted. Wait for this latch
// to countdown after appointing all the partition leaders. The
// LeaderCache callback will count it down once it has seen all the
// appointed leaders publish themselves as the actual leaders.
m_startupLatch = SettableFuture.create();
writeKnownLiveNodes(new HashSet<Integer>(m_hostMessenger.getLiveHostIds()));
// Theoretically, the whole try/catch block below can be removed because the leader
// appointer now watches the parent dir for any new partitions. It doesn't have to
// create the partition dirs all at once, it can pick them up one by one as they are
// created. But I'm too afraid to remove this block just before the release,
// so leaving it here till later. - ning
try {
final int initialPartitionCount = getInitialPartitionCount();
for (int i = 0; i < initialPartitionCount; i++) {
LeaderElector.createRootIfNotExist(m_zk,
LeaderElector.electionDirForPartition(i));
watchPartition(i, m_es, true);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count on startup", true, e);
}
//Asynchronously wait for this to finish otherwise it deadlocks
//on task that need to run on this thread
m_startupLatch.addListener(new Runnable() {
@Override
public void run() {
try {
m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
blocker.set(null);
} catch (Throwable t) {
blocker.setException(t);
}
}
},
m_es);
}
else {
// If we're taking over for a failed LeaderAppointer, we know when
// we get here that every partition had a leader at some point in
// time. We'll seed each of the PartitionCallbacks for each
// partition with the HSID of the last published leader. The
// blocking startup of the BabySitter watching that partition will
// call our callback, get the current full set of replicas, and
// appoint a new leader if the seeded one has actually failed
Map<Integer, Long> masters = m_iv2masters.pointInTimeCache();
tmLog.info("LeaderAppointer repairing with master set: " + CoreUtils.hsIdValueMapToString(masters));
//Setting the map to non-null causes the babysitters to populate it when cleaning up partitions
//We are only racing with ourselves in that the creation of a babysitter can trigger callbacks
//that result in partitions being cleaned up. We don't have to worry about some other leader appointer.
//The iteration order of the partitions doesn't matter
m_removedPartitionsAtPromotionTime = new HashSet<Integer>();
for (Entry<Integer, Long> master : masters.entrySet()) {
//Skip processing the partition if it was cleaned up by a babysitter that was previously
//instantiated
if (m_removedPartitionsAtPromotionTime.contains(master.getKey())) {
tmLog.info("During promotion partition " + master.getKey() + " was cleaned up. Skipping.");
continue;
}
int partId = master.getKey();
String dir = LeaderElector.electionDirForPartition(partId);
m_callbacks.put(partId, new PartitionCallback(partId, master.getValue()));
Pair<BabySitter, List<String>> sitterstuff =
BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(partId), m_es);
//We could get this far and then find out that creating this particular
//babysitter triggered cleanup so we need to bail out here as well
if (!m_removedPartitionsAtPromotionTime.contains(master.getKey())) {
m_partitionWatchers.put(partId, sitterstuff.getFirst());
}
}
m_removedPartitionsAtPromotionTime = null;
// just go ahead and promote our MPI
m_MPI.acceptPromotion();
// set up a watcher on the partitions dir so that new partitions will be picked up
m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
blocker.set(null);
}
}
/**
* Watch the partition ZK dir in the leader appointer.
*
* This should be called on the elected leader appointer only. m_callbacks and
* m_partitionWatchers are only accessed on initialization, promotion,
* or elastic add node.
*
* @param pid The partition ID
* @param es The executor service to use to construct the baby sitter
* @param shouldBlock Whether or not to wait for the initial read of children
* @throws KeeperException
* @throws InterruptedException
* @throws ExecutionException
*/
void watchPartition(int pid, ExecutorService es, boolean shouldBlock)
throws InterruptedException, ExecutionException
{
String dir = LeaderElector.electionDirForPartition(pid);
m_callbacks.put(pid, new PartitionCallback(pid));
BabySitter babySitter;
if (shouldBlock) {
babySitter = BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(pid), es).getFirst();
} else {
babySitter = BabySitter.nonblockingFactory(m_zk, dir, m_callbacks.get(pid), es);
}
m_partitionWatchers.put(pid, babySitter);
}
private long assignLeader(int partitionId, List<Long> children)
{
// We used masterHostId = -1 as a way to force the leader choice to be
// the first replica in the list, if we don't have some other mechanism
// which has successfully overridden it.
int masterHostId = -1;
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
// find master in topo
JSONArray parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == partitionId) {
masterHostId = aPartition.getInt("master");
}
}
}
catch (JSONException jse) {
tmLog.error("Failed to find master for partition " + partitionId + ", defaulting to 0");
jse.printStackTrace();
masterHostId = -1; // stupid default
}
}
else {
// For now, if we're appointing a new leader as a result of a
// failure, just pick the first replica in the children list.
// Could eventually do something more complex here to try to keep a
// semi-balance, but it's unclear that this has much utility until
// we add rebalancing on rejoin as well.
masterHostId = -1;
}
long masterHSId = children.get(0);
for (Long child : children) {
if (CoreUtils.getHostIdFromHSId(child) == masterHostId) {
masterHSId = child;
break;
}
}
tmLog.info("Appointing HSId " + CoreUtils.hsIdToString(masterHSId) + " as leader for partition " +
partitionId);
try {
m_iv2appointees.put(partitionId, masterHSId);
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to appoint new master for partition " + partitionId, true, e);
}
return masterHSId;
}
private void writeKnownLiveNodes(Set<Integer> liveNodes)
{
try {
if (m_zk.exists(VoltZK.lastKnownLiveNodes, null) == null)
{
// VoltZK.createPersistentZKNodes should have done this
m_zk.create(VoltZK.lastKnownLiveNodes, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("liveNodes").array();
for (Integer node : liveNodes) {
stringer.value(node);
}
stringer.endArray();
stringer.endObject();
JSONObject obj = new JSONObject(stringer.toString());
tmLog.debug("Writing live nodes to ZK: " + obj.toString(4));
m_zk.setData(VoltZK.lastKnownLiveNodes, obj.toString(4).getBytes("UTF-8"), -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to update known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
}
private Set<Integer> readPriorKnownLiveNodes()
{
Set<Integer> nodes = new HashSet<Integer>();
try {
byte[] data = m_zk.getData(VoltZK.lastKnownLiveNodes, false, null);
String jsonString = new String(data, "UTF-8");
tmLog.debug("Read prior known live nodes: " + jsonString);
JSONObject jsObj = new JSONObject(jsonString);
JSONArray jsonNodes = jsObj.getJSONArray("liveNodes");
for (int ii = 0; ii < jsonNodes.length(); ii++) {
nodes.add(jsonNodes.getInt(ii));
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read prior known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
return nodes;
}
/**
* Given a set of the known host IDs before a fault, and the known host IDs in the
* post-fault cluster, determine whether or not we think a network partition may have happened.
* NOTE: this assumes that we have already done the k-safety validation for every partition and already failed
* if we weren't a viable cluster.
* ALSO NOTE: not private so it may be unit-tested.
*/
static boolean makePPDDecision(Set<Integer> previousHosts, Set<Integer> currentHosts)
{
// Real partition detection stuff would go here
// find the lowest hostId between the still-alive hosts and the
// failed hosts. Which set contains the lowest hostId?
int blessedHostId = Integer.MAX_VALUE;
boolean blessedHostIdInFailedSet = true;
// This should be all the pre-partition hosts IDs. Any new host IDs
// (say, if this was triggered by rejoin), will be greater than any surviving
// host ID, so don't worry about including it in this search.
for (Integer hostId : previousHosts) {
if (hostId < blessedHostId) {
blessedHostId = hostId;
}
}
for (Integer hostId : currentHosts) {
if (hostId.equals(blessedHostId)) {
blessedHostId = hostId;
blessedHostIdInFailedSet = false;
}
}
// Evaluate PPD triggers.
boolean partitionDetectionTriggered = false;
// Exact 50-50 splits. The set with the lowest survivor host doesn't trigger PPD
// If the blessed host is in the failure set, this set is not blessed.
if (currentHosts.size() * 2 == previousHosts.size()) {
if (blessedHostIdInFailedSet) {
tmLog.info("Partition detection triggered for 50/50 cluster failure. " +
"This survivor set is shutting down.");
partitionDetectionTriggered = true;
}
else {
tmLog.info("Partition detected for 50/50 failure. " +
"This survivor set is continuing execution.");
}
}
// A strict, viable minority is always a partition.
if (currentHosts.size() * 2 < previousHosts.size()) {
tmLog.info("Partition detection triggered. " +
"This minority survivor set is shutting down.");
partitionDetectionTriggered = true;
}
return partitionDetectionTriggered;
}
private void doPartitionDetectionActivities(Set<Integer> currentNodes)
{
// We should never re-enter here once we've decided we're partitioned and doomed
assert(!m_partitionDetected);
Set<Integer> currentHosts = new HashSet<Integer>(currentNodes);
Set<Integer> previousHosts = readPriorKnownLiveNodes();
boolean partitionDetectionTriggered = makePPDDecision(previousHosts, currentHosts);
if (partitionDetectionTriggered) {
m_partitionDetected = true;
if (m_usingCommandLog) {
// Just shut down immediately
VoltDB.crashGlobalVoltDB("Use of command logging detected, no additional database snapshot will " +
"be generated. Please use the 'recover' action to restore the database if necessary.",
false, null);
}
else {
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
}
// If the cluster host set has changed, then write the new set to ZK
// NOTE: we don't want to update the known live nodes if we've decided that our subcluster is
// dying, otherwise a poorly timed subsequent failure might reverse this decision. Any future promoted
// LeaderAppointer should make their partition detection decision based on the pre-partition cluster state.
else if (!currentHosts.equals(previousHosts)) {
writeKnownLiveNodes(currentNodes);
}
}
private boolean isClusterKSafe(Set<Integer> hostsOnRing)
{
boolean retval = true;
List<String> partitionDirs = null;
ImmutableSortedMap.Builder<Integer,Integer> lackingReplication =
ImmutableSortedMap.naturalOrder();
try {
partitionDirs = m_zk.getChildren(VoltZK.leaders_initiators, null);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read partitions from ZK", true, e);
}
//Don't fetch the values serially do it asynchronously
Queue<ZKUtil.ByteArrayCallback> dataCallbacks = new ArrayDeque<ZKUtil.ByteArrayCallback>();
Queue<ZKUtil.ChildrenCallback> childrenCallbacks = new ArrayDeque<ZKUtil.ChildrenCallback>();
for (String partitionDir : partitionDirs) {
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
ZKUtil.ByteArrayCallback callback = new ZKUtil.ByteArrayCallback();
m_zk.getData(dir, false, callback, null);
dataCallbacks.offer(callback);
ZKUtil.ChildrenCallback childrenCallback = new ZKUtil.ChildrenCallback();
m_zk.getChildren(dir, false, childrenCallback, null);
childrenCallbacks.offer(childrenCallback);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
for (String partitionDir : partitionDirs) {
int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
// The data of the partition dir indicates whether the partition has finished
// initializing or not. If not, the replicas may still be in the process of
// adding themselves to the dir. So don't check for k-safety if that's the case.
byte[] partitionState = dataCallbacks.poll().getData();
boolean isInitializing = false;
if (partitionState != null && partitionState.length == 1) {
isInitializing = partitionState[0] == LeaderElector.INITIALIZING;
}
List<String> replicas = childrenCallbacks.poll().getChildren();
if (pid == MpInitiator.MP_INIT_PID) continue;
final boolean partitionNotOnHashRing = partitionNotOnHashRing(pid);
if (!isInitializing && replicas.isEmpty()) {
//These partitions can fail, just cleanup and remove the partition from the system
if (partitionNotOnHashRing) {
removeAndCleanupPartition(pid);
continue;
}
tmLog.fatal("K-Safety violation: No replicas found for partition: " + pid);
retval = false;
} else if (!partitionNotOnHashRing) {
//Record host ids for all partitions that are on the ring
//so they are considered for partition detection
for (String replica : replicas) {
final String split[] = replica.split("/");
final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
final int hostId = CoreUtils.getHostIdFromHSId(hsId);
hostsOnRing.add(hostId);
}
}
if (!isInitializing && replicas.size() <= m_kfactor && !partitionNotOnHashRing) {
lackingReplication.put(pid, m_kfactor + 1 - replicas.size());
}
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
m_stats.setSafetyMap(lackingReplication.build());
return retval;
}
private void removeAndCleanupPartition(int pid) {
tmLog.info("Removing and cleanup up partition info for partition " + pid);
if (m_removedPartitionsAtPromotionTime != null) {
m_removedPartitionsAtPromotionTime.add(pid);
tmLog.info("Partition " + pid + " was cleaned up during LeaderAppointer promotion and should be skipped");
}
BabySitter sitter = m_partitionWatchers.remove(pid);
if (sitter != null) {
sitter.shutdown();
}
m_callbacks.remove(pid);
try {
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2masters, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2appointees, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.leaders_initiators, "partition_" + String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
} catch (Exception e) {
tmLog.error("Error removing partition info", e);
}
}
private static boolean partitionNotOnHashRing(int pid) {
if (TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY) return false;
return TheHashinator.getRanges(pid).isEmpty();
}
/**
* Gets the initial cluster partition count on startup. This can only be called during
* initialization. Calling this after initialization throws, because the partition count may
* not reflect the actual partition count in the cluster.
*
* @return
*/
private int getInitialPartitionCount() throws IllegalAccessException
{
AppointerState currentState = m_state.get();
if (currentState != AppointerState.INIT && currentState != AppointerState.CLUSTER_START) {
throw new IllegalAccessException("Getting cached partition count after cluster " +
"startup");
}
return m_initialPartitionCount;
}
public void onReplayCompletion()
{
m_replayComplete.set(true);
}
public void shutdown()
{
try {
m_es.execute(new Runnable() {
@Override
public void run() {
try {
m_iv2appointees.shutdown();
m_iv2masters.shutdown();
for (BabySitter watcher : m_partitionWatchers.values()) {
watcher.shutdown();
}
} catch (Exception e) {
// don't care, we're going down
}
}
});
m_es.shutdown();
m_es.awaitTermination(356, TimeUnit.DAYS);
}
catch (InterruptedException e) {
tmLog.warn("Unexpected interrupted exception", e);
}
}
}
| src/frontend/org/voltdb/iv2/LeaderAppointer.java | /* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.iv2;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltcore.zk.BabySitter;
import org.voltcore.zk.LeaderElector;
import org.voltcore.zk.ZKUtil;
import org.voltdb.Promotable;
import org.voltdb.SnapshotFormat;
import org.voltdb.TheHashinator;
import org.voltdb.VoltDB;
import org.voltdb.VoltZK;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.sysprocs.saverestore.SnapshotUtil.SnapshotResponseHandler;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.collect.ImmutableSortedMap;
import com.google_voltpatches.common.util.concurrent.SettableFuture;
/**
* LeaderAppointer handles centralized appointment of partition leaders across
* the partition. This is primarily so that the leaders can be evenly
* distributed throughout the cluster, reducing bottlenecks (at least at
* startup). As a side-effect, this service also controls the initial startup
* of the cluster, blocking operation until each partition has a k-safe set of
* replicas, each partition has a leader, and the MPI has started.
*/
public class LeaderAppointer implements Promotable
{
private static final VoltLogger tmLog = new VoltLogger("TM");
private enum AppointerState {
INIT, // Initial start state, used to inhibit ZK callback actions
CLUSTER_START, // indicates that we're doing the initial cluster startup
DONE // indicates normal running conditions, including repair
}
private final HostMessenger m_hostMessenger;
private final ZooKeeper m_zk;
// This should only be accessed through getInitialPartitionCount() on cluster startup.
private final int m_initialPartitionCount;
private final Map<Integer, BabySitter> m_partitionWatchers;
private final LeaderCache m_iv2appointees;
private final LeaderCache m_iv2masters;
private final Map<Integer, PartitionCallback> m_callbacks;
private final int m_kfactor;
private final JSONObject m_topo;
private final MpInitiator m_MPI;
private final AtomicReference<AppointerState> m_state =
new AtomicReference<AppointerState>(AppointerState.INIT);
private SettableFuture<Object> m_startupLatch = null;
private final boolean m_partitionDetectionEnabled;
private boolean m_partitionDetected = false;
private boolean m_usingCommandLog = false;
private final AtomicBoolean m_replayComplete = new AtomicBoolean(false);
private final KSafetyStats m_stats;
/*
* Track partitions that are cleaned up during election/promotion etc.
* This eliminates the race where the cleanup occurs while constructing babysitters
* for partitions that end up being removed.
*/
private HashSet<Integer> m_removedPartitionsAtPromotionTime = null;
// Provide a single single-threaded executor service to all the BabySitters for each partition.
// This will guarantee that the ordering of events generated by ZooKeeper is preserved in the
// handling of callbacks in LeaderAppointer.
private final ExecutorService m_es =
CoreUtils.getCachedSingleThreadExecutor("LeaderAppointer-Babysitters", 15000);
private final SnapshotSchedule m_partSnapshotSchedule;
private final SnapshotResponseHandler m_snapshotHandler =
new SnapshotResponseHandler() {
@Override
public void handleResponse(ClientResponse resp)
{
if (resp == null) {
VoltDB.crashLocalVoltDB("Received a null response to a snapshot initiation request. " +
"This should be impossible.", true, null);
}
else if (resp.getStatus() != ClientResponse.SUCCESS) {
tmLog.info("Failed to complete partition detection snapshot, status: " + resp.getStatus() +
", reason: " + resp.getStatusString());
tmLog.info("Retrying partition detection snapshot...");
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
else if (!SnapshotUtil.didSnapshotRequestSucceed(resp.getResults())) {
VoltDB.crashGlobalVoltDB("Unable to complete partition detection snapshot: " +
resp.getResults()[0], false, null);
}
else {
VoltDB.crashGlobalVoltDB("Partition detection snapshot completed. Shutting down.",
false, null);
}
}
};
private class PartitionCallback extends BabySitter.Callback
{
final int m_partitionId;
final Set<Long> m_replicas;
long m_currentLeader;
/** Constructor used when we know (or think we know) who the leader for this partition is */
PartitionCallback(int partitionId, long currentLeader)
{
this(partitionId);
// Try to be clever for repair. Create ourselves with the current leader set to
// whatever is in the LeaderCache, and claim that replica exists, then let the
// first run() call fix the world.
m_currentLeader = currentLeader;
m_replicas.add(currentLeader);
}
/** Constructor used at startup when there is no leader */
PartitionCallback(int partitionId)
{
m_partitionId = partitionId;
// A bit of a hack, but we should never end up with an HSID as Long.MAX_VALUE
m_currentLeader = Long.MAX_VALUE;
m_replicas = new HashSet<Long>();
}
@Override
public void run(List<String> children)
{
List<Long> updatedHSIds = VoltZK.childrenToReplicaHSIds(children);
// compute previously unseen HSId set in the callback list
Set<Long> newHSIds = new HashSet<Long>(updatedHSIds);
newHSIds.removeAll(m_replicas);
tmLog.debug("Newly seen replicas: " + CoreUtils.hsIdCollectionToString(newHSIds));
// compute previously seen but now vanished from the callback list HSId set
Set<Long> missingHSIds = new HashSet<Long>(m_replicas);
missingHSIds.removeAll(updatedHSIds);
tmLog.debug("Newly dead replicas: " + CoreUtils.hsIdCollectionToString(missingHSIds));
tmLog.debug("Handling babysitter callback for partition " + m_partitionId + ": children: " +
CoreUtils.hsIdCollectionToString(updatedHSIds));
if (m_state.get() == AppointerState.CLUSTER_START) {
// We can't yet tolerate a host failure during startup. Crash it all
if (missingHSIds.size() > 0) {
VoltDB.crashGlobalVoltDB("Node failure detected during startup.", false, null);
}
// ENG-3166: Eventually we would like to get rid of the extra replicas beyond k_factor,
// but for now we just look to see how many replicas of this partition we actually expect
// and gate leader assignment on that many copies showing up.
int replicaCount = m_kfactor + 1;
JSONArray parts;
try {
parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == m_partitionId) {
replicaCount = aPartition.getJSONArray("replicas").length();
}
}
} catch (JSONException e) {
// Ignore and just assume the normal number of replicas
}
if (children.size() == replicaCount) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
else {
tmLog.info("Waiting on " + ((m_kfactor + 1) - children.size()) + " more nodes " +
"for k-safety before startup");
}
}
else {
Set<Integer> hostsOnRing = new HashSet<Integer>();
// Check for k-safety
if (!isClusterKSafe(hostsOnRing)) {
VoltDB.crashGlobalVoltDB("Some partitions have no replicas. Cluster has become unviable.",
false, null);
}
// Check if replay has completed
if (m_replayComplete.get() == false) {
VoltDB.crashGlobalVoltDB("Detected node failure during command log replay. Cluster will shut down.",
false, null);
}
// Check to see if there's been a possible network partition and we're not already handling it
if (m_partitionDetectionEnabled && !m_partitionDetected) {
doPartitionDetectionActivities(hostsOnRing);
}
// If we survived the above gauntlet of fail, appoint a new leader for this partition.
if (missingHSIds.contains(m_currentLeader)) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
// If this partition doesn't have a leader yet, and we have new replicas added,
// elect a leader.
if (m_currentLeader == Long.MAX_VALUE && !updatedHSIds.isEmpty()) {
m_currentLeader = assignLeader(m_partitionId, updatedHSIds);
}
}
m_replicas.clear();
m_replicas.addAll(updatedHSIds);
}
}
/* We'll use this callback purely for startup so we can discover when all
* the leaders we have appointed have completed their promotions and
* published themselves to Zookeeper */
LeaderCache.Callback m_masterCallback = new LeaderCache.Callback()
{
@Override
public void run(ImmutableMap<Integer, Long> cache) {
Set<Long> currentLeaders = new HashSet<Long>(cache.values());
tmLog.debug("Updated leaders: " + currentLeaders);
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
if (currentLeaders.size() == getInitialPartitionCount()) {
tmLog.debug("Leader appointment complete, promoting MPI and unblocking.");
m_state.set(AppointerState.DONE);
m_MPI.acceptPromotion();
m_startupLatch.set(null);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
}
};
Watcher m_partitionCallback = new Watcher() {
@Override
public void process(WatchedEvent event)
{
m_es.submit(new Runnable() {
@Override
public void run()
{
try {
List<String> children = m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
tmLog.info("Noticed partition change " + children + ", " +
"currenctly watching " + m_partitionWatchers.keySet());
for (String child : children) {
int pid = LeaderElector.getPartitionFromElectionDir(child);
if (!m_partitionWatchers.containsKey(pid) && pid != MpInitiator.MP_INIT_PID) {
watchPartition(pid, m_es, false);
}
}
tmLog.info("Done " + m_partitionWatchers.keySet());
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Cannot read leader initiator directory", false, e);
}
}
});
}
};
public LeaderAppointer(HostMessenger hm, int numberOfPartitions,
int kfactor, boolean partitionDetectionEnabled,
SnapshotSchedule partitionSnapshotSchedule,
boolean usingCommandLog,
JSONObject topology, MpInitiator mpi,
KSafetyStats stats)
{
m_hostMessenger = hm;
m_zk = hm.getZK();
m_kfactor = kfactor;
m_topo = topology;
m_MPI = mpi;
m_initialPartitionCount = numberOfPartitions;
m_callbacks = new HashMap<Integer, PartitionCallback>();
m_partitionWatchers = new HashMap<Integer, BabySitter>();
m_iv2appointees = new LeaderCache(m_zk, VoltZK.iv2appointees);
m_iv2masters = new LeaderCache(m_zk, VoltZK.iv2masters, m_masterCallback);
m_partitionDetectionEnabled = partitionDetectionEnabled;
m_partSnapshotSchedule = partitionSnapshotSchedule;
m_usingCommandLog = usingCommandLog;
m_stats = stats;
}
@Override
public void acceptPromotion() throws InterruptedException, ExecutionException
{
final SettableFuture<Object> blocker = SettableFuture.create();
try {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
acceptPromotionImpl(blocker);
} catch (Throwable t) {
blocker.setException(t);
}
}
});
blocker.get();
} catch (RejectedExecutionException e) {
if (m_es.isShutdown()) return;
throw new RejectedExecutionException(e);
}
}
private void acceptPromotionImpl(final SettableFuture<Object> blocker) throws InterruptedException, ExecutionException, KeeperException {
// Crank up the leader caches. Use blocking startup so that we'll have valid point-in-time caches later.
m_iv2appointees.start(true);
m_iv2masters.start(true);
ImmutableMap<Integer, Long> appointees = m_iv2appointees.pointInTimeCache();
// Figure out what conditions we assumed leadership under.
if (appointees.size() == 0)
{
tmLog.debug("LeaderAppointer in startup");
m_state.set(AppointerState.CLUSTER_START);
}
else if (m_state.get() == AppointerState.INIT) {
ImmutableMap<Integer, Long> masters = m_iv2masters.pointInTimeCache();
try {
if ((appointees.size() < getInitialPartitionCount()) ||
(masters.size() < getInitialPartitionCount()) ||
(appointees.size() != masters.size())) {
// If we are promoted and the appointees or masters set is partial, the previous appointer failed
// during startup (at least for now, until we add remove a partition on the fly).
VoltDB.crashGlobalVoltDB("Detected failure during startup, unable to start", false, null);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count", true, e);
}
}
else {
tmLog.debug("LeaderAppointer in repair");
m_state.set(AppointerState.DONE);
}
if (m_state.get() == AppointerState.CLUSTER_START) {
// Need to block the return of acceptPromotion until after the MPI is promoted. Wait for this latch
// to countdown after appointing all the partition leaders. The
// LeaderCache callback will count it down once it has seen all the
// appointed leaders publish themselves as the actual leaders.
m_startupLatch = SettableFuture.create();
writeKnownLiveNodes(new HashSet<Integer>(m_hostMessenger.getLiveHostIds()));
// Theoretically, the whole try/catch block below can be removed because the leader
// appointer now watches the parent dir for any new partitions. It doesn't have to
// create the partition dirs all at once, it can pick them up one by one as they are
// created. But I'm too afraid to remove this block just before the release,
// so leaving it here till later. - ning
try {
final int initialPartitionCount = getInitialPartitionCount();
for (int i = 0; i < initialPartitionCount; i++) {
LeaderElector.createRootIfNotExist(m_zk,
LeaderElector.electionDirForPartition(i));
watchPartition(i, m_es, true);
}
} catch (IllegalAccessException e) {
// This should never happen
VoltDB.crashLocalVoltDB("Failed to get partition count on startup", true, e);
}
//Asynchronously wait for this to finish otherwise it deadlocks
//on task that need to run on this thread
m_startupLatch.addListener(new Runnable() {
@Override
public void run() {
try {
m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
blocker.set(null);
} catch (Throwable t) {
blocker.setException(t);
}
}
},
m_es);
}
else {
// If we're taking over for a failed LeaderAppointer, we know when
// we get here that every partition had a leader at some point in
// time. We'll seed each of the PartitionCallbacks for each
// partition with the HSID of the last published leader. The
// blocking startup of the BabySitter watching that partition will
// call our callback, get the current full set of replicas, and
// appoint a new leader if the seeded one has actually failed
Map<Integer, Long> masters = m_iv2masters.pointInTimeCache();
tmLog.info("LeaderAppointer repairing with master set: " + CoreUtils.hsIdValueMapToString(masters));
//Setting the map to non-null causes the babysitters to populate it when cleaning up partitions
//We are only racing with ourselves in that the creation of a babysitter can trigger callbacks
//that result in partitions being cleaned up. We don't have to worry about some other leader appointer.
//The iteration order of the partitions doesn't matter
m_removedPartitionsAtPromotionTime = new HashSet<Integer>();
for (Entry<Integer, Long> master : masters.entrySet()) {
//Skip processing the partition if it was cleaned up by a babysitter that was previously
//instantiated
if (m_removedPartitionsAtPromotionTime.contains(master.getKey())) {
tmLog.info("During promotion partition " + master.getKey() + " was cleaned up. Skipping.");
continue;
}
int partId = master.getKey();
String dir = LeaderElector.electionDirForPartition(partId);
m_callbacks.put(partId, new PartitionCallback(partId, master.getValue()));
Pair<BabySitter, List<String>> sitterstuff =
BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(partId), m_es);
//We could get this far and then find out that creating this particular
//babysitter triggered cleanup so we need to bail out here as well
if (!m_removedPartitionsAtPromotionTime.contains(master.getKey())) {
m_partitionWatchers.put(partId, sitterstuff.getFirst());
}
}
m_removedPartitionsAtPromotionTime = null;
// just go ahead and promote our MPI
m_MPI.acceptPromotion();
// set up a watcher on the partitions dir so that new partitions will be picked up
m_zk.getChildren(VoltZK.leaders_initiators, m_partitionCallback);
blocker.set(null);
}
}
/**
* Watch the partition ZK dir in the leader appointer.
*
* This should be called on the elected leader appointer only. m_callbacks and
* m_partitionWatchers are only accessed on initialization, promotion,
* or elastic add node.
*
* @param pid The partition ID
* @param es The executor service to use to construct the baby sitter
* @param shouldBlock Whether or not to wait for the initial read of children
* @throws KeeperException
* @throws InterruptedException
* @throws ExecutionException
*/
void watchPartition(int pid, ExecutorService es, boolean shouldBlock)
throws InterruptedException, ExecutionException
{
String dir = LeaderElector.electionDirForPartition(pid);
m_callbacks.put(pid, new PartitionCallback(pid));
BabySitter babySitter;
if (shouldBlock) {
babySitter = BabySitter.blockingFactory(m_zk, dir, m_callbacks.get(pid), es).getFirst();
} else {
babySitter = BabySitter.nonblockingFactory(m_zk, dir, m_callbacks.get(pid), es);
}
m_partitionWatchers.put(pid, babySitter);
}
private long assignLeader(int partitionId, List<Long> children)
{
// We used masterHostId = -1 as a way to force the leader choice to be
// the first replica in the list, if we don't have some other mechanism
// which has successfully overridden it.
int masterHostId = -1;
if (m_state.get() == AppointerState.CLUSTER_START) {
try {
// find master in topo
JSONArray parts = m_topo.getJSONArray("partitions");
for (int p = 0; p < parts.length(); p++) {
JSONObject aPartition = parts.getJSONObject(p);
int pid = aPartition.getInt("partition_id");
if (pid == partitionId) {
masterHostId = aPartition.getInt("master");
}
}
}
catch (JSONException jse) {
tmLog.error("Failed to find master for partition " + partitionId + ", defaulting to 0");
jse.printStackTrace();
masterHostId = -1; // stupid default
}
}
else {
// For now, if we're appointing a new leader as a result of a
// failure, just pick the first replica in the children list.
// Could eventually do something more complex here to try to keep a
// semi-balance, but it's unclear that this has much utility until
// we add rebalancing on rejoin as well.
masterHostId = -1;
}
long masterHSId = children.get(0);
for (Long child : children) {
if (CoreUtils.getHostIdFromHSId(child) == masterHostId) {
masterHSId = child;
break;
}
}
tmLog.info("Appointing HSId " + CoreUtils.hsIdToString(masterHSId) + " as leader for partition " +
partitionId);
try {
m_iv2appointees.put(partitionId, masterHSId);
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to appoint new master for partition " + partitionId, true, e);
}
return masterHSId;
}
private void writeKnownLiveNodes(Set<Integer> liveNodes)
{
try {
if (m_zk.exists(VoltZK.lastKnownLiveNodes, null) == null)
{
// VoltZK.createPersistentZKNodes should have done this
m_zk.create(VoltZK.lastKnownLiveNodes, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("liveNodes").array();
for (Integer node : liveNodes) {
stringer.value(node);
}
stringer.endArray();
stringer.endObject();
JSONObject obj = new JSONObject(stringer.toString());
tmLog.debug("Writing live nodes to ZK: " + obj.toString(4));
m_zk.setData(VoltZK.lastKnownLiveNodes, obj.toString(4).getBytes("UTF-8"), -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to update known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
}
private Set<Integer> readPriorKnownLiveNodes()
{
Set<Integer> nodes = new HashSet<Integer>();
try {
byte[] data = m_zk.getData(VoltZK.lastKnownLiveNodes, false, null);
String jsonString = new String(data, "UTF-8");
tmLog.debug("Read prior known live nodes: " + jsonString);
JSONObject jsObj = new JSONObject(jsonString);
JSONArray jsonNodes = jsObj.getJSONArray("liveNodes");
for (int ii = 0; ii < jsonNodes.length(); ii++) {
nodes.add(jsonNodes.getInt(ii));
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read prior known live nodes at ZK path: " +
VoltZK.lastKnownLiveNodes, true, e);
}
return nodes;
}
/**
* Given a set of the known host IDs before a fault, and the known host IDs in the
* post-fault cluster, determine whether or not we think a network partition may have happened.
* NOTE: this assumes that we have already done the k-safety validation for every partition and already failed
* if we weren't a viable cluster.
* ALSO NOTE: not private so it may be unit-tested.
*/
static boolean makePPDDecision(Set<Integer> previousHosts, Set<Integer> currentHosts)
{
// Real partition detection stuff would go here
// find the lowest hostId between the still-alive hosts and the
// failed hosts. Which set contains the lowest hostId?
int blessedHostId = Integer.MAX_VALUE;
boolean blessedHostIdInFailedSet = true;
// This should be all the pre-partition hosts IDs. Any new host IDs
// (say, if this was triggered by rejoin), will be greater than any surviving
// host ID, so don't worry about including it in this search.
for (Integer hostId : previousHosts) {
if (hostId < blessedHostId) {
blessedHostId = hostId;
}
}
for (Integer hostId : currentHosts) {
if (hostId.equals(blessedHostId)) {
blessedHostId = hostId;
blessedHostIdInFailedSet = false;
}
}
// Evaluate PPD triggers.
boolean partitionDetectionTriggered = false;
// Exact 50-50 splits. The set with the lowest survivor host doesn't trigger PPD
// If the blessed host is in the failure set, this set is not blessed.
if (currentHosts.size() * 2 == previousHosts.size()) {
if (blessedHostIdInFailedSet) {
tmLog.info("Partition detection triggered for 50/50 cluster failure. " +
"This survivor set is shutting down.");
partitionDetectionTriggered = true;
}
else {
tmLog.info("Partition detected for 50/50 failure. " +
"This survivor set is continuing execution.");
}
}
// A strict, viable minority is always a partition.
if (currentHosts.size() * 2 < previousHosts.size()) {
tmLog.info("Partition detection triggered. " +
"This minority survivor set is shutting down.");
partitionDetectionTriggered = true;
}
return partitionDetectionTriggered;
}
private void doPartitionDetectionActivities(Set<Integer> currentNodes)
{
// We should never re-enter here once we've decided we're partitioned and doomed
assert(!m_partitionDetected);
Set<Integer> currentHosts = new HashSet<Integer>(currentNodes);
Set<Integer> previousHosts = readPriorKnownLiveNodes();
boolean partitionDetectionTriggered = makePPDDecision(previousHosts, currentHosts);
if (partitionDetectionTriggered) {
m_partitionDetected = true;
if (m_usingCommandLog) {
// Just shut down immediately
VoltDB.crashGlobalVoltDB("Use of command logging detected, no additional database snapshot will " +
"be generated. Please use the 'recover' action to restore the database if necessary.",
false, null);
}
else {
SnapshotUtil.requestSnapshot(0L,
m_partSnapshotSchedule.getPath(),
m_partSnapshotSchedule.getPrefix() + System.currentTimeMillis(),
true, SnapshotFormat.NATIVE, null, m_snapshotHandler,
true);
}
}
// If the cluster host set has changed, then write the new set to ZK
// NOTE: we don't want to update the known live nodes if we've decided that our subcluster is
// dying, otherwise a poorly timed subsequent failure might reverse this decision. Any future promoted
// LeaderAppointer should make their partition detection decision based on the pre-partition cluster state.
else if (!currentHosts.equals(previousHosts)) {
writeKnownLiveNodes(currentNodes);
}
}
private boolean isClusterKSafe(Set<Integer> hostsOnRing)
{
boolean retval = true;
List<String> partitionDirs = null;
ImmutableSortedMap.Builder<Integer,Integer> lackingReplication =
ImmutableSortedMap.naturalOrder();
try {
partitionDirs = m_zk.getChildren(VoltZK.leaders_initiators, null);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read partitions from ZK", true, e);
}
//Don't fetch the values serially do it asynchronously
Queue<ZKUtil.ByteArrayCallback> dataCallbacks = new ArrayDeque<ZKUtil.ByteArrayCallback>();
Queue<ZKUtil.ChildrenCallback> childrenCallbacks = new ArrayDeque<ZKUtil.ChildrenCallback>();
for (String partitionDir : partitionDirs) {
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
ZKUtil.ByteArrayCallback callback = new ZKUtil.ByteArrayCallback();
m_zk.getData(dir, false, callback, null);
dataCallbacks.offer(callback);
ZKUtil.ChildrenCallback childrenCallback = new ZKUtil.ChildrenCallback();
m_zk.getChildren(dir, false, childrenCallback, null);
childrenCallbacks.offer(childrenCallback);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
for (String partitionDir : partitionDirs) {
int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);
String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
try {
// The data of the partition dir indicates whether the partition has finished
// initializing or not. If not, the replicas may still be in the process of
// adding themselves to the dir. So don't check for k-safety if that's the case.
byte[] partitionState = dataCallbacks.poll().getData();
boolean isInitializing = false;
if (partitionState != null && partitionState.length == 1) {
isInitializing = partitionState[0] == LeaderElector.INITIALIZING;
}
List<String> replicas = childrenCallbacks.poll().getChildren();
if (pid == MpInitiator.MP_INIT_PID) continue;
final boolean partitionNotOnHashRing = partitionNotOnHashRing(pid);
if (!isInitializing && replicas.isEmpty()) {
//These partitions can fail, just cleanup and remove the partition from the system
if (partitionNotOnHashRing) {
removeAndCleanupPartition(pid);
continue;
}
tmLog.fatal("K-Safety violation: No replicas found for partition: " + pid);
retval = false;
} else if (!partitionNotOnHashRing) {
//Record host ids for all partitions that are on the ring
//so they are considered for partition detection
for (String replica : replicas) {
final String split[] = replica.split("/");
final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
final int hostId = CoreUtils.getHostIdFromHSId(hsId);
hostsOnRing.add(hostId);
}
}
if (!isInitializing && replicas.size() <= m_kfactor && !partitionNotOnHashRing) {
lackingReplication.put(pid, m_kfactor + 1 - replicas.size());
}
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
}
}
m_stats.setSafetyMap(lackingReplication.build());
return retval;
}
private void removeAndCleanupPartition(int pid) {
tmLog.info("Removing and cleanup up partition info for partition " + pid);
if (m_removedPartitionsAtPromotionTime != null) {
m_removedPartitionsAtPromotionTime.add(pid);
tmLog.info("Partition " + pid + " was cleaned up during LeaderAppointer promotion and should be skipped");
}
BabySitter sitter = m_partitionWatchers.remove(pid);
if (sitter != null) {
sitter.shutdown();
}
m_callbacks.remove(pid);
try {
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2masters, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.iv2appointees, String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
try {
m_zk.delete(ZKUtil.joinZKPath(VoltZK.leaders_initiators, "partition_" + String.valueOf(pid)), -1);
} catch (KeeperException.NoNodeException e) {}
} catch (Exception e) {
tmLog.error("Error removing partition info", e);
}
}
private static boolean partitionNotOnHashRing(int pid) {
if (TheHashinator.getConfiguredHashinatorType() == TheHashinator.HashinatorType.LEGACY) return false;
return TheHashinator.getRanges(pid).isEmpty();
}
/**
* Gets the initial cluster partition count on startup. This can only be called during
* initialization. Calling this after initialization throws, because the partition count may
* not reflect the actual partition count in the cluster.
*
* @return
*/
private int getInitialPartitionCount() throws IllegalAccessException
{
AppointerState currentState = m_state.get();
if (currentState != AppointerState.INIT && currentState != AppointerState.CLUSTER_START) {
throw new IllegalAccessException("Getting cached partition count after cluster " +
"startup");
}
return m_initialPartitionCount;
}
public void onReplayCompletion()
{
m_replayComplete.set(true);
}
public void shutdown()
{
try {
m_es.execute(new Runnable() {
@Override
public void run() {
try {
m_iv2appointees.shutdown();
m_iv2masters.shutdown();
for (BabySitter watcher : m_partitionWatchers.values()) {
watcher.shutdown();
}
} catch (Exception e) {
// don't care, we're going down
}
}
});
m_es.shutdown();
m_es.awaitTermination(356, TimeUnit.DAYS);
}
catch (InterruptedException e) {
tmLog.warn("Unexpected interrupted exception", e);
}
}
}
| For ENG-5588, take a stab at removing the check that is only supposed to run at startup
| src/frontend/org/voltdb/iv2/LeaderAppointer.java | For ENG-5588, take a stab at removing the check that is only supposed to run at startup | <ide><path>rc/frontend/org/voltdb/iv2/LeaderAppointer.java
<ide> tmLog.debug("LeaderAppointer in startup");
<ide> m_state.set(AppointerState.CLUSTER_START);
<ide> }
<del> else if (m_state.get() == AppointerState.INIT) {
<add> //INIT is the default before promotion at runtime. Don't do this startup check
<add> //Let the rest of the promotion run and determine k-safety which is the else block.
<add> else if (m_state.get() == AppointerState.INIT && !VoltDB.instance().isRunning()) {
<ide> ImmutableMap<Integer, Long> masters = m_iv2masters.pointInTimeCache();
<ide> try {
<ide> if ((appointees.size() < getInitialPartitionCount()) || |
|
Java | apache-2.0 | 7f256c32cbc4884a6e7d3d128fa5595b67c84637 | 0 | driftx/cassandra,nutbunnies/cassandra,michaelsembwever/cassandra,cooldoger/cassandra,scylladb/scylla-tools-java,pofallon/cassandra,belliottsmith/cassandra,yhnishi/cassandra,Instagram/cassandra,pcmanus/cassandra,iamaleksey/cassandra,rdio/cassandra,spodkowinski/cassandra,project-zerus/cassandra,beobal/cassandra,Stratio/cassandra,yukim/cassandra,regispl/cassandra,dkua/cassandra,stef1927/cassandra,segfault/apache_cassandra,hhorii/cassandra,kangkot/stratio-cassandra,Bj0rnen/cassandra,chbatey/cassandra-1,vaibhi9/cassandra,gdusbabek/cassandra,phact/cassandra,aboudreault/cassandra,DavidHerzogTU-Berlin/cassandraToRun,pcmanus/cassandra,hengxin/cassandra,codefollower/Cassandra-Research,Jaumo/cassandra,sivikt/cassandra,blambov/cassandra,newrelic-forks/cassandra,scaledata/cassandra,Jaumo/cassandra,weipinghe/cassandra,tongjixianing/projects,pbailis/cassandra-pbs,szhou1234/cassandra,sayanh/ViewMaintenanceSupport,hhorii/cassandra,codefollower/Cassandra-Research,RyanMagnusson/cassandra,blambov/cassandra,taigetco/cassandra_read,aweisberg/cassandra,fengshao0907/cassandra-1,RyanMagnusson/cassandra,GabrielNicolasAvellaneda/cassandra,guanxi55nba/db-improvement,bdeggleston/cassandra,jrwest/cassandra,ifesdjeen/cassandra,jasonstack/cassandra,likaiwalkman/cassandra,AtwooTM/cassandra,instaclustr/cassandra,strapdata/cassandra,nlalevee/cassandra,guanxi55nba/key-value-store,ben-manes/cassandra,tommystendahl/cassandra,hengxin/cassandra,ollie314/cassandra,jkni/cassandra,Jollyplum/cassandra,vramaswamy456/cassandra,bcoverston/cassandra,chaordic/cassandra,jasonwee/cassandra,yanbit/cassandra,yonglehou/cassandra,weideng1/cassandra,pallavi510/cassandra,krummas/cassandra,GabrielNicolasAvellaneda/cassandra,fengshao0907/Cassandra-Research,clohfink/cassandra,weipinghe/cassandra,mariusae/cassandra,szhou1234/cassandra,boneill42/cassandra,qinjin/mdtc-cassandra,rogerchina/cassandra,mambocab/cassandra,gdusbabek/cassandra,jsanda/cassandra,xiongzheng/Cassandra-Research,bcoverston/apache-hosted-cassandra,bdeggleston/cassandra,a-buck/cassandra,guard163/cassandra,juiceblender/cassandra,miguel0afd/cassandra-cqlMod,sedulam/CASSANDRA-12201,guanxi55nba/key-value-store,driftx/cassandra,bdeggleston/cassandra,nitsanw/cassandra,WorksApplications/cassandra,darach/cassandra,ptuckey/cassandra,snazy/cassandra,dkua/cassandra,rmarchei/cassandra,JeremiahDJordan/cassandra,guard163/cassandra,sayanh/ViewMaintenanceSupport,carlyeks/cassandra,ifesdjeen/cassandra,matthewtt/cassandra_read,stef1927/cassandra,emolsson/cassandra,pthomaid/cassandra,ibmsoe/cassandra,scaledata/cassandra,RyanMagnusson/cassandra,DICL/cassandra,sayanh/ViewMaintenanceCassandra,stuhood/cassandra-old,tjake/cassandra,michaelsembwever/cassandra,Stratio/stratio-cassandra,yonglehou/cassandra,joesiewert/cassandra,macintoshio/cassandra,driftx/cassandra,guanxi55nba/db-improvement,thobbs/cassandra,lalithsuresh/cassandra-c3,sluk3r/cassandra,pofallon/cassandra,asias/cassandra,mike-tr-adamson/cassandra,josh-mckenzie/cassandra,kgreav/cassandra,exoscale/cassandra,stuhood/cassandra-old,mheffner/cassandra-1,iamaleksey/cassandra,szhou1234/cassandra,michaelmior/cassandra,Bj0rnen/cassandra,iburmistrov/Cassandra,xiongzheng/Cassandra-Research,szhou1234/cassandra,kangkot/stratio-cassandra,Bj0rnen/cassandra,mklew/mmp,jeffjirsa/cassandra,scaledata/cassandra,belliottsmith/cassandra,macintoshio/cassandra,adelapena/cassandra,mgmuscari/cassandra-cdh4,jasonstack/cassandra,jkni/cassandra,sharvanath/cassandra,mariusae/cassandra,vramaswamy456/cassandra,mambocab/cassandra,mshuler/cassandra,weipinghe/cassandra,taigetco/cassandra_read,swps/cassandra,HidemotoNakada/cassandra-udf,swps/cassandra,apache/cassandra,project-zerus/cassandra,belliottsmith/cassandra,ifesdjeen/cassandra,instaclustr/cassandra,LatencyUtils/cassandra-stress2,yukim/cassandra,nvoron23/cassandra,yangzhe1991/cassandra,Imran-C/cassandra,chaordic/cassandra,jeromatron/cassandra,scylladb/scylla-tools-java,beobal/cassandra,clohfink/cassandra,sriki77/cassandra,sedulam/CASSANDRA-12201,pkdevbox/cassandra,pkdevbox/cassandra,aboudreault/cassandra,dprguiuc/Cassandra-Wasef,nakomis/cassandra,ollie314/cassandra,shawnkumar/cstargraph,mkjellman/cassandra,adelapena/cassandra,project-zerus/cassandra,shookari/cassandra,ejankan/cassandra,sivikt/cassandra,rackerlabs/cloudmetrics-cassandra,bcoverston/cassandra,miguel0afd/cassandra-cqlMod,bcoverston/cassandra,knifewine/cassandra,strapdata/cassandra,MasahikoSawada/cassandra,blerer/cassandra,strapdata/cassandra,bcoverston/cassandra,iburmistrov/Cassandra,whitepages/cassandra,apache/cassandra,DikangGu/cassandra,jeffjirsa/cassandra,heiko-braun/cassandra,jasonstack/cassandra,pauloricardomg/cassandra,sedulam/CASSANDRA-12201,macintoshio/cassandra,LatencyUtils/cassandra-stress2,mklew/mmp,mkjellman/cassandra,michaelmior/cassandra,Jollyplum/cassandra,mashuai/Cassandra-Research,mashuai/Cassandra-Research,modempachev4/kassandra,dkua/cassandra,nvoron23/cassandra,matthewtt/cassandra_read,yhnishi/cassandra,Stratio/stratio-cassandra,DavidHerzogTU-Berlin/cassandra,ifesdjeen/cassandra,ibmsoe/cassandra,bdeggleston/cassandra,shawnkumar/cstargraph,shawnkumar/cstargraph,mheffner/cassandra-1,sammyyu/Cassandra,exoscale/cassandra,Jaumo/cassandra,darach/cassandra,helena/cassandra,lalithsuresh/cassandra-c3,weideng1/cassandra,chbatey/cassandra-1,jrwest/cassandra,bcoverston/apache-hosted-cassandra,mt0803/cassandra,juiceblender/cassandra,mshuler/cassandra,Jollyplum/cassandra,likaiwalkman/cassandra,sayanh/ViewMaintenanceCassandra,aarushi12002/cassandra,heiko-braun/cassandra,iamaleksey/cassandra,mt0803/cassandra,thelastpickle/cassandra,caidongyun/cassandra,iamaleksey/cassandra,mike-tr-adamson/cassandra,mheffner/cassandra-1,michaelsembwever/cassandra,EnigmaCurry/cassandra,shookari/cassandra,guanxi55nba/db-improvement,krummas/cassandra,jsanda/cassandra,aureagle/cassandra,fengshao0907/Cassandra-Research,ben-manes/cassandra,pcn/cassandra-1,michaelsembwever/cassandra,helena/cassandra,rmarchei/cassandra,rogerchina/cassandra,mariusae/cassandra,HidemotoNakada/cassandra-udf,aboudreault/cassandra,WorksApplications/cassandra,apache/cassandra,ejankan/cassandra,sammyyu/Cassandra,DavidHerzogTU-Berlin/cassandra,nlalevee/cassandra,aureagle/cassandra,asias/cassandra,yangzhe1991/cassandra,dongjiaqiang/cassandra,JeremiahDJordan/cassandra,clohfink/cassandra,aweisberg/cassandra,thelastpickle/cassandra,DikangGu/cassandra,spodkowinski/cassandra,AtwooTM/cassandra,Stratio/stratio-cassandra,kangkot/stratio-cassandra,matthewtt/cassandra_read,rmarchei/cassandra,yanbit/cassandra,pbailis/cassandra-pbs,DICL/cassandra,nvoron23/cassandra,dongjiaqiang/cassandra,josh-mckenzie/cassandra,bcoverston/apache-hosted-cassandra,pallavi510/cassandra,leomrocha/cassandra,sriki77/cassandra,ptnapoleon/cassandra,tongjixianing/projects,iburmistrov/Cassandra,krummas/cassandra,WorksApplications/cassandra,MasahikoSawada/cassandra,emolsson/cassandra,helena/cassandra,guanxi55nba/key-value-store,Stratio/cassandra,kgreav/cassandra,ben-manes/cassandra,bmel/cassandra,ptnapoleon/cassandra,Stratio/stratio-cassandra,aureagle/cassandra,spodkowinski/cassandra,jeffjirsa/cassandra,strapdata/cassandra,christian-esken/cassandra,jbellis/cassandra,hengxin/cassandra,exoscale/cassandra,asias/cassandra,Imran-C/cassandra,tjake/cassandra,tongjixianing/projects,tommystendahl/cassandra,tjake/cassandra,ollie314/cassandra,knifewine/cassandra,dprguiuc/Cassandra-Wasef,boneill42/cassandra,pcn/cassandra-1,mkjellman/cassandra,jasobrown/cassandra,stef1927/cassandra,beobal/cassandra,mambocab/cassandra,Instagram/cassandra,whitepages/cassandra,nitsanw/cassandra,jasonwee/cassandra,phact/cassandra,vaibhi9/cassandra,snazy/cassandra,rackerlabs/cloudmetrics-cassandra,pthomaid/cassandra,jrwest/cassandra,bmel/cassandra,Instagram/cassandra,pkdevbox/cassandra,tommystendahl/cassandra,jbellis/cassandra,blerer/cassandra,nitsanw/cassandra,ptuckey/cassandra,pauloricardomg/cassandra,apache/cassandra,dongjiaqiang/cassandra,nutbunnies/cassandra,stuhood/cassandra-old,adejanovski/cassandra,kgreav/cassandra,tommystendahl/cassandra,sammyyu/Cassandra,thobbs/cassandra,christian-esken/cassandra,adejanovski/cassandra,emolsson/cassandra,miguel0afd/cassandra-cqlMod,sbtourist/cassandra,leomrocha/cassandra,instaclustr/cassandra,nlalevee/cassandra,carlyeks/cassandra,qinjin/mdtc-cassandra,krummas/cassandra,aarushi12002/cassandra,LatencyUtils/cassandra-stress2,WorksApplications/cassandra,yukim/cassandra,josh-mckenzie/cassandra,jeromatron/cassandra,mklew/mmp,b/project-cassandra,mshuler/cassandra,darach/cassandra,caidongyun/cassandra,bmel/cassandra,ibmsoe/cassandra,blerer/cassandra,mike-tr-adamson/cassandra,jsanda/cassandra,newrelic-forks/cassandra,HidemotoNakada/cassandra-udf,thelastpickle/cassandra,adelapena/cassandra,joesiewert/cassandra,newrelic-forks/cassandra,qinjin/mdtc-cassandra,modempachev4/kassandra,fengshao0907/cassandra-1,ptnapoleon/cassandra,sharvanath/cassandra,thelastpickle/cassandra,vaibhi9/cassandra,fengshao0907/Cassandra-Research,shookari/cassandra,mike-tr-adamson/cassandra,chaordic/cassandra,mshuler/cassandra,DavidHerzogTU-Berlin/cassandraToRun,jeromatron/cassandra,kangkot/stratio-cassandra,beobal/cassandra,kgreav/cassandra,pcn/cassandra-1,sayanh/ViewMaintenanceCassandra,pcmanus/cassandra,adejanovski/cassandra,jasonwee/cassandra,nutbunnies/cassandra,MasahikoSawada/cassandra,juiceblender/cassandra,cooldoger/cassandra,jasobrown/cassandra,yukim/cassandra,rdio/cassandra,josh-mckenzie/cassandra,EnigmaCurry/cassandra,Instagram/cassandra,sivikt/cassandra,xiongzheng/Cassandra-Research,nakomis/cassandra,dprguiuc/Cassandra-Wasef,jeffjirsa/cassandra,segfault/apache_cassandra,a-buck/cassandra,yhnishi/cassandra,chbatey/cassandra-1,knifewine/cassandra,rdio/cassandra,pauloricardomg/cassandra,sluk3r/cassandra,tjake/cassandra,sriki77/cassandra,wreda/cassandra,yanbit/cassandra,rogerchina/cassandra,Stratio/cassandra,stef1927/cassandra,wreda/cassandra,joesiewert/cassandra,Imran-C/cassandra,weideng1/cassandra,thobbs/cassandra,swps/cassandra,sbtourist/cassandra,jasobrown/cassandra,sbtourist/cassandra,cooldoger/cassandra,bpupadhyaya/cassandra,bpupadhyaya/cassandra,mgmuscari/cassandra-cdh4,caidongyun/cassandra,taigetco/cassandra_read,blambov/cassandra,instaclustr/cassandra,aweisberg/cassandra,phact/cassandra,snazy/cassandra,segfault/apache_cassandra,pthomaid/cassandra,ejankan/cassandra,regispl/cassandra,stuhood/cassandra-old,aweisberg/cassandra,juiceblender/cassandra,b/project-cassandra,heiko-braun/cassandra,Stratio/stratio-cassandra,pallavi510/cassandra,b/project-cassandra,boneill42/cassandra,jkni/cassandra,yonglehou/cassandra,blambov/cassandra,codefollower/Cassandra-Research,jasobrown/cassandra,mkjellman/cassandra,sharvanath/cassandra,DikangGu/cassandra,bpupadhyaya/cassandra,snazy/cassandra,sluk3r/cassandra,mariusae/cassandra,DavidHerzogTU-Berlin/cassandraToRun,leomrocha/cassandra,jbellis/cassandra,rackerlabs/cloudmetrics-cassandra,mt0803/cassandra,yangzhe1991/cassandra,wreda/cassandra,aarushi12002/cassandra,gdusbabek/cassandra,clohfink/cassandra,ptuckey/cassandra,pbailis/cassandra-pbs,scylladb/scylla-tools-java,fengshao0907/cassandra-1,adelapena/cassandra,AtwooTM/cassandra,DavidHerzogTU-Berlin/cassandra,blerer/cassandra,likaiwalkman/cassandra,christian-esken/cassandra,JeremiahDJordan/cassandra,whitepages/cassandra,GabrielNicolasAvellaneda/cassandra,guard163/cassandra,nakomis/cassandra,michaelmior/cassandra,belliottsmith/cassandra,pauloricardomg/cassandra,EnigmaCurry/cassandra,cooldoger/cassandra,a-buck/cassandra,DICL/cassandra,mariusae/cassandra,mgmuscari/cassandra-cdh4,scylladb/scylla-tools-java,hhorii/cassandra,pofallon/cassandra,jrwest/cassandra,b/project-cassandra,mashuai/Cassandra-Research,vramaswamy456/cassandra,lalithsuresh/cassandra-c3,kangkot/stratio-cassandra,regispl/cassandra,driftx/cassandra,modempachev4/kassandra,carlyeks/cassandra,spodkowinski/cassandra | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.utils;
import java.math.*;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.io.*;
import java.security.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.zip.*;
import javax.xml.bind.annotation.XmlElement;
import org.apache.cassandra.io.DataInputBuffer;
import org.apache.cassandra.io.DataOutputBuffer;
import org.apache.cassandra.io.ICompactSerializer;
import org.apache.cassandra.io.SSTable;
/**
* Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] )
*/
public class BloomFilter implements Serializable
{
private static List<ISimpleHash> hashLibrary_ = new ArrayList<ISimpleHash>();
private static ICompactSerializer<BloomFilter> serializer_;
static
{
serializer_ = new BloomFilterSerializer();
hashLibrary_.add(new RSHash());
hashLibrary_.add(new JSHash());
hashLibrary_.add(new PJWHash());
hashLibrary_.add(new ELFHash());
hashLibrary_.add(new BKDRHash());
hashLibrary_.add(new SDBMHash());
hashLibrary_.add(new DJBHash());
hashLibrary_.add(new DEKHash());
hashLibrary_.add(new BPHash());
hashLibrary_.add(new FNVHash());
hashLibrary_.add(new APHash());
}
public static ICompactSerializer<BloomFilter> serializer()
{
return serializer_;
}
private BitSet filter_;
private int count_;
private int size_;
private int hashes_;
private Random random_ = new Random(System.currentTimeMillis());
public BloomFilter(int numElements, int bitsPerElement)
{
// TODO -- think about the trivial cases more.
// Note that it should indeed be possible to send a bloom filter that
// encodes the empty set.
if (numElements < 0 || bitsPerElement < 1)
throw new IllegalArgumentException("Number of elements and bits "
+ "must be non-negative.");
// Adding a small random number of bits so that even if the set
// of elements hasn't changed, we'll get different false positives.
count_ = numElements;
size_ = numElements * bitsPerElement + 20 + random_.nextInt(64);
filter_ = new BitSet(size_);
//hashes_ = BloomCalculations.computeBestK(bitsPerElement);
hashes_ = 8;
}
/*
* This version is only used by the deserializer.
*/
BloomFilter(int count, int hashes, int size, BitSet filter)
{
count_ = count;
hashes_ = hashes;
size_ = size;
filter_ = filter;
}
int count()
{
return count_;
}
int size()
{
return size_;
}
int hashes()
{
return hashes_;
}
BitSet filter()
{
return filter_;
}
public boolean isPresent(String key)
{
boolean bVal = true;
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
if (!filter_.get(index))
{
bVal = false;
break;
}
}
return bVal;
}
/*
param@ key -- value whose hash is used to fill
the filter_.
This is a general purpose API.
*/
public void fill(String key)
{
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
filter_.set(index);
}
}
public String toString()
{
return filter_.toString();
}
}
class BloomFilterSerializer implements ICompactSerializer<BloomFilter>
{
/*
* The following methods are used for compact representation
* of BloomFilter. This is essential, since we want to determine
* the size of the serialized Bloom Filter blob before it is
* populated armed with the knowledge of how many elements are
* going to reside in it.
*/
public void serialize(BloomFilter bf, DataOutputStream dos) throws IOException
{
/* write out the count of the BloomFilter */
dos.writeInt(bf.count());
/* write the number of hash functions used */
dos.writeInt(bf.hashes());
/* write the size of the BloomFilter */
dos.writeInt(bf.size());
BitSet.serializer().serialize(bf.filter(), dos);
}
public BloomFilter deserialize(DataInputStream dis) throws IOException
{
/* read the count of the BloomFilter */
int count = dis.readInt();
/* read the number of hash functions */
int hashes = dis.readInt();
/* read the size of the bloom filter */
int size = dis.readInt();
BitSet bs = BitSet.serializer().deserialize(dis);
return new BloomFilter(count, hashes, size, bs);
}
}
interface ISimpleHash
{
public int hash(String str);
}
class RSHash implements ISimpleHash
{
public int hash(String str)
{
int b = 378551;
int a = 63689;
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = hash * a + str.charAt(i);
a = a * b;
}
return hash;
}
}
class JSHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 1315423911;
for (int i = 0; i < str.length(); i++)
{
hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2));
}
return hash;
}
}
class PJWHash implements ISimpleHash
{
public int hash(String str)
{
int bitsInUnsignedInt = (4 * 8);
int threeQuarters = (bitsInUnsignedInt * 3) / 4;
int oneEighth = bitsInUnsignedInt / 8;
int highBits = (0xFFFFFFFF) << (bitsInUnsignedInt - oneEighth);
int hash = 0;
int test = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash << oneEighth) + str.charAt(i);
if ((test = hash & highBits) != 0)
{
hash = ((hash ^ (test >> threeQuarters)) & (~highBits));
}
}
return hash;
}
}
class ELFHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
int x = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash << 4) + str.charAt(i);
if ((x = hash & 0xF0000000) != 0)
{
hash ^= (x >> 24);
}
hash &= ~x;
}
return hash;
}
}
class BKDRHash implements ISimpleHash
{
public int hash(String str)
{
int seed = 131; // 31 131 1313 13131 131313 etc..
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash * seed) + str.charAt(i);
}
return hash;
}
}
class SDBMHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
}
class DJBHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 5381;
for (int i = 0; i < str.length(); i++)
{
hash = ((hash << 5) + hash) + str.charAt(i);
}
return hash;
}
}
class DEKHash implements ISimpleHash
{
public int hash(String str)
{
int hash = str.length();
for (int i = 0; i < str.length(); i++)
{
hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);
}
return hash;
}
}
class BPHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = hash << 7 ^ str.charAt(i);
}
return hash;
}
}
class FNVHash implements ISimpleHash
{
public int hash(String str)
{
int fnv_prime = 0x811C9DC5;
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash *= fnv_prime;
hash ^= str.charAt(i);
}
return hash;
}
}
class APHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0xAAAAAAAA;
for (int i = 0; i < str.length(); i++)
{
if ((i & 1) == 0)
{
hash ^= ((hash << 7) ^ str.charAt(i) ^ (hash >> 3));
}
else
{
hash ^= (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5)));
}
}
return hash;
}
}
| src/org/apache/cassandra/utils/BloomFilter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.utils;
import java.math.*;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.io.*;
import java.security.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.zip.*;
import javax.xml.bind.annotation.XmlElement;
import org.apache.cassandra.io.DataInputBuffer;
import org.apache.cassandra.io.DataOutputBuffer;
import org.apache.cassandra.io.ICompactSerializer;
import org.apache.cassandra.io.SSTable;
/**
* Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] )
*/
public class BloomFilter implements Serializable
{
public static class CountingBloomFilter implements Serializable
{
private static ICompactSerializer<CountingBloomFilter> serializer_;
static
{
serializer_ = new CountingBloomFilterSerializer();
}
public static ICompactSerializer<CountingBloomFilter> serializer()
{
return serializer_;
}
@XmlElement(name="Filter")
private byte[] filter_ = new byte[0];
@XmlElement(name="Size")
private int size_;
@XmlElement(name="Hashes")
private int hashes_;
/* Keeps count of number of keys added to CBF */
private transient int count_ = 0;
private transient Random random_ = new Random(System.currentTimeMillis());
/*
* This is just for JAXB.
*/
private CountingBloomFilter()
{
}
public CountingBloomFilter(int numElements, int bitsPerElement)
{
// TODO -- think about the trivial cases more.
// Note that it should indeed be possible to send a bloom filter that
// encodes the empty set.
if (numElements < 0 || bitsPerElement < 1)
throw new IllegalArgumentException("Number of elements and bits "
+ "must be non-negative.");
// Adding a small random number of bits so that even if the set
// of elements hasn't changed, we'll get different false positives.
size_ = numElements * bitsPerElement + 20 + random_.nextInt(64);
filter_ = new byte[size_];
hashes_ = BloomCalculations.computeBestK(bitsPerElement);
}
CountingBloomFilter(int size, int hashes, byte[] filter)
{
size_ = size;
hashes_ = hashes;
filter_ = filter;
}
public CountingBloomFilter cloneMe()
{
byte[] filter = new byte[filter_.length];
System.arraycopy(filter_, 0, filter, 0, filter_.length);
return new BloomFilter.CountingBloomFilter(size_, hashes_, filter);
}
int size()
{
return size_;
}
int hashes()
{
return hashes_;
}
byte[] filter()
{
return filter_;
}
public BloomFilter.CountingBloomFilter merge(BloomFilter.CountingBloomFilter cbf)
{
if ( cbf == null )
return this;
if ( size_ >= cbf.size_ )
{
for ( int i = 0; i < cbf.filter_.length; ++i )
{
filter_[i] |= cbf.filter_[i];
}
return this;
}
else
{
for ( int i = 0; i < filter_.length; ++i )
{
cbf.filter_[i] |= filter_[i];
}
return cbf;
}
}
public boolean isPresent(String key)
{
boolean bVal = true;
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
if (filter_[index] == 0)
{
bVal = false;
break;
}
}
return bVal;
}
/*
param@ key -- value whose hash is used to fill
the filter_.
This is a general purpose API.
*/
public void add(String key)
{
if ( !isPresent(key) )
++count_;
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
byte value = (filter_[index] == 0xFF) ? filter_[index] : (byte)( (++filter_[index]) & 0xFF );
filter_[index] = value;
}
}
public boolean delete(String key)
{
boolean bVal = isPresent(key);
if ( !bVal )
{
--count_;
return bVal;
}
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
byte value = (filter_[index] == 0) ? filter_[index] : (byte)( (--filter_[index]) & 0xFF );
filter_[index] = value;
}
return bVal;
}
public int count()
{
return count_;
}
}
private static List<ISimpleHash> hashLibrary_ = new ArrayList<ISimpleHash>();
private static ICompactSerializer<BloomFilter> serializer_;
static
{
serializer_ = new BloomFilterSerializer();
hashLibrary_.add(new RSHash());
hashLibrary_.add(new JSHash());
hashLibrary_.add(new PJWHash());
hashLibrary_.add(new ELFHash());
hashLibrary_.add(new BKDRHash());
hashLibrary_.add(new SDBMHash());
hashLibrary_.add(new DJBHash());
hashLibrary_.add(new DEKHash());
hashLibrary_.add(new BPHash());
hashLibrary_.add(new FNVHash());
hashLibrary_.add(new APHash());
}
public static ICompactSerializer<BloomFilter> serializer()
{
return serializer_;
}
private BitSet filter_;
private int count_;
private int size_;
private int hashes_;
private Random random_ = new Random(System.currentTimeMillis());
public BloomFilter(int bitsPerElement)
{
if (bitsPerElement < 1)
throw new IllegalArgumentException("Number of bitsPerElement "
+ "must be non-negative.");
// Adding a small random number of bits so that even if the set
// of elements hasn't changed, we'll get different false positives.
size_ = 20 + random_.nextInt(64);
filter_ = new BitSet(size_);
hashes_ = BloomCalculations.computeBestK(bitsPerElement);
}
public BloomFilter(int numElements, int bitsPerElement)
{
// TODO -- think about the trivial cases more.
// Note that it should indeed be possible to send a bloom filter that
// encodes the empty set.
if (numElements < 0 || bitsPerElement < 1)
throw new IllegalArgumentException("Number of elements and bits "
+ "must be non-negative.");
// Adding a small random number of bits so that even if the set
// of elements hasn't changed, we'll get different false positives.
count_ = numElements;
size_ = numElements * bitsPerElement + 20 + random_.nextInt(64);
filter_ = new BitSet(size_);
//hashes_ = BloomCalculations.computeBestK(bitsPerElement);
hashes_ = 8;
}
public BloomFilter(int numElements, double maxFalsePosProbability)
{
if (numElements < 0)
throw new IllegalArgumentException("Number of elements must be "
+ "non-negative.");
BloomCalculations.BloomSpecification spec = BloomCalculations
.computeBitsAndK(maxFalsePosProbability);
// Add a small random number of bits so that even if the set
// of elements hasn't changed, we'll get different false positives.
count_ = numElements;
size_ = numElements * spec.bitsPerElement + 20 + random_.nextInt(64);
filter_ = new BitSet(size_);
hashes_ = spec.K;
}
/*
* This version is only used by the deserializer.
*/
BloomFilter(int count, int hashes, int size, BitSet filter)
{
count_ = count;
hashes_ = hashes;
size_ = size;
filter_ = filter;
}
int count()
{
return count_;
}
int size()
{
return size_;
}
int hashes()
{
return hashes_;
}
BitSet filter()
{
return filter_;
}
public BloomFilter merge(BloomFilter bf)
{
BloomFilter mergedBf = null;
if ( filter_.size() >= bf.filter_.size() )
{
filter_.or(bf.filter_);
mergedBf = this;
}
else
{
bf.filter_.or(filter_);
mergedBf = bf;
}
return mergedBf;
}
public boolean isPresent(String key)
{
boolean bVal = true;
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
if (!filter_.get(index))
{
bVal = false;
break;
}
}
return bVal;
}
/*
param@ key -- value whose hash is used to fill
the filter_.
This is a general purpose API.
*/
public void fill(String key)
{
for (int i = 0; i < hashes_; ++i)
{
ISimpleHash hash = hashLibrary_.get(i);
int hashValue = hash.hash(key);
int index = Math.abs(hashValue % size_);
filter_.set(index);
}
}
public String toString()
{
return filter_.toString();
}
public static void main(String[] args) throws Throwable
{
BloomFilter bf = new BloomFilter(64*1024*1024, 15);
for ( int i = 0; i < 64*1024*1024; ++i )
{
bf.fill(Integer.toString(i));
}
System.out.println("Done filling ...");
for ( int i = 0; i < 64*1024*1024; ++i )
{
if ( !bf.isPresent(Integer.toString(i)) )
System.out.println("Oops");
}
}
}
class BloomFilterSerializer implements ICompactSerializer<BloomFilter>
{
/*
* The following methods are used for compact representation
* of BloomFilter. This is essential, since we want to determine
* the size of the serialized Bloom Filter blob before it is
* populated armed with the knowledge of how many elements are
* going to reside in it.
*/
public void serialize(BloomFilter bf, DataOutputStream dos) throws IOException
{
/* write out the count of the BloomFilter */
dos.writeInt(bf.count());
/* write the number of hash functions used */
dos.writeInt(bf.hashes());
/* write the size of the BloomFilter */
dos.writeInt(bf.size());
BitSet.serializer().serialize(bf.filter(), dos);
}
public BloomFilter deserialize(DataInputStream dis) throws IOException
{
/* read the count of the BloomFilter */
int count = dis.readInt();
/* read the number of hash functions */
int hashes = dis.readInt();
/* read the size of the bloom filter */
int size = dis.readInt();
BitSet bs = BitSet.serializer().deserialize(dis);
return new BloomFilter(count, hashes, size, bs);
}
}
class CountingBloomFilterSerializer implements ICompactSerializer<BloomFilter.CountingBloomFilter>
{
/*
* The following methods are used for compact representation
* of BloomFilter. This is essential, since we want to determine
* the size of the serialized Bloom Filter blob before it is
* populated armed with the knowledge of how many elements are
* going to reside in it.
*/
public void serialize(BloomFilter.CountingBloomFilter cbf, DataOutputStream dos)
throws IOException
{
/* write the size of the BloomFilter */
dos.writeInt(cbf.size());
/* write the number of hash functions used */
dos.writeInt(cbf.hashes());
byte[] filter = cbf.filter();
/* write length of the filter */
dos.writeInt(filter.length);
dos.write(filter);
}
public BloomFilter.CountingBloomFilter deserialize(DataInputStream dis) throws IOException
{
/* read the size of the bloom filter */
int size = dis.readInt();
/* read the number of hash functions */
int hashes = dis.readInt();
/* read the length of the filter */
int length = dis.readInt();
byte[] filter = new byte[length];
dis.readFully(filter);
return new BloomFilter.CountingBloomFilter(size, hashes, filter);
}
}
interface ISimpleHash
{
public int hash(String str);
}
class RSHash implements ISimpleHash
{
public int hash(String str)
{
int b = 378551;
int a = 63689;
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = hash * a + str.charAt(i);
a = a * b;
}
return hash;
}
}
class JSHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 1315423911;
for (int i = 0; i < str.length(); i++)
{
hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2));
}
return hash;
}
}
class PJWHash implements ISimpleHash
{
public int hash(String str)
{
int bitsInUnsignedInt = (4 * 8);
int threeQuarters = (bitsInUnsignedInt * 3) / 4;
int oneEighth = bitsInUnsignedInt / 8;
int highBits = (0xFFFFFFFF) << (bitsInUnsignedInt - oneEighth);
int hash = 0;
int test = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash << oneEighth) + str.charAt(i);
if ((test = hash & highBits) != 0)
{
hash = ((hash ^ (test >> threeQuarters)) & (~highBits));
}
}
return hash;
}
}
class ELFHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
int x = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash << 4) + str.charAt(i);
if ((x = hash & 0xF0000000) != 0)
{
hash ^= (x >> 24);
}
hash &= ~x;
}
return hash;
}
}
class BKDRHash implements ISimpleHash
{
public int hash(String str)
{
int seed = 131; // 31 131 1313 13131 131313 etc..
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = (hash * seed) + str.charAt(i);
}
return hash;
}
}
class SDBMHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
}
class DJBHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 5381;
for (int i = 0; i < str.length(); i++)
{
hash = ((hash << 5) + hash) + str.charAt(i);
}
return hash;
}
}
class DEKHash implements ISimpleHash
{
public int hash(String str)
{
int hash = str.length();
for (int i = 0; i < str.length(); i++)
{
hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);
}
return hash;
}
}
class BPHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash = hash << 7 ^ str.charAt(i);
}
return hash;
}
}
class FNVHash implements ISimpleHash
{
public int hash(String str)
{
int fnv_prime = 0x811C9DC5;
int hash = 0;
for (int i = 0; i < str.length(); i++)
{
hash *= fnv_prime;
hash ^= str.charAt(i);
}
return hash;
}
}
class APHash implements ISimpleHash
{
public int hash(String str)
{
int hash = 0xAAAAAAAA;
for (int i = 0; i < str.length(); i++)
{
if ((i & 1) == 0)
{
hash ^= ((hash << 7) ^ str.charAt(i) ^ (hash >> 3));
}
else
{
hash ^= (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5)));
}
}
return hash;
}
}
| r/m unused code, including entire CountingBloomFilter
git-svn-id: 1e8683751772dd0ef52a45d586103b4a82d616ff@766137 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/cassandra/utils/BloomFilter.java | r/m unused code, including entire CountingBloomFilter | <ide><path>rc/org/apache/cassandra/utils/BloomFilter.java
<ide> */
<ide>
<ide> public class BloomFilter implements Serializable
<del>{
<del> public static class CountingBloomFilter implements Serializable
<del> {
<del> private static ICompactSerializer<CountingBloomFilter> serializer_;
<del> static
<del> {
<del> serializer_ = new CountingBloomFilterSerializer();
<del> }
<del>
<del> public static ICompactSerializer<CountingBloomFilter> serializer()
<del> {
<del> return serializer_;
<del> }
<del>
<del> @XmlElement(name="Filter")
<del> private byte[] filter_ = new byte[0];
<del>
<del> @XmlElement(name="Size")
<del> private int size_;
<del>
<del> @XmlElement(name="Hashes")
<del> private int hashes_;
<del>
<del> /* Keeps count of number of keys added to CBF */
<del> private transient int count_ = 0;
<del> private transient Random random_ = new Random(System.currentTimeMillis());
<del>
<del> /*
<del> * This is just for JAXB.
<del> */
<del> private CountingBloomFilter()
<del> {
<del> }
<del>
<del> public CountingBloomFilter(int numElements, int bitsPerElement)
<del> {
<del> // TODO -- think about the trivial cases more.
<del> // Note that it should indeed be possible to send a bloom filter that
<del> // encodes the empty set.
<del> if (numElements < 0 || bitsPerElement < 1)
<del> throw new IllegalArgumentException("Number of elements and bits "
<del> + "must be non-negative.");
<del> // Adding a small random number of bits so that even if the set
<del> // of elements hasn't changed, we'll get different false positives.
<del> size_ = numElements * bitsPerElement + 20 + random_.nextInt(64);
<del> filter_ = new byte[size_];
<del> hashes_ = BloomCalculations.computeBestK(bitsPerElement);
<del> }
<del>
<del> CountingBloomFilter(int size, int hashes, byte[] filter)
<del> {
<del> size_ = size;
<del> hashes_ = hashes;
<del> filter_ = filter;
<del> }
<del>
<del> public CountingBloomFilter cloneMe()
<del> {
<del> byte[] filter = new byte[filter_.length];
<del> System.arraycopy(filter_, 0, filter, 0, filter_.length);
<del> return new BloomFilter.CountingBloomFilter(size_, hashes_, filter);
<del> }
<del>
<del> int size()
<del> {
<del> return size_;
<del> }
<del>
<del> int hashes()
<del> {
<del> return hashes_;
<del> }
<del>
<del> byte[] filter()
<del> {
<del> return filter_;
<del> }
<del>
<del> public BloomFilter.CountingBloomFilter merge(BloomFilter.CountingBloomFilter cbf)
<del> {
<del> if ( cbf == null )
<del> return this;
<del>
<del> if ( size_ >= cbf.size_ )
<del> {
<del> for ( int i = 0; i < cbf.filter_.length; ++i )
<del> {
<del> filter_[i] |= cbf.filter_[i];
<del> }
<del> return this;
<del> }
<del> else
<del> {
<del> for ( int i = 0; i < filter_.length; ++i )
<del> {
<del> cbf.filter_[i] |= filter_[i];
<del> }
<del> return cbf;
<del> }
<del> }
<del>
<del> public boolean isPresent(String key)
<del> {
<del> boolean bVal = true;
<del> for (int i = 0; i < hashes_; ++i)
<del> {
<del> ISimpleHash hash = hashLibrary_.get(i);
<del> int hashValue = hash.hash(key);
<del> int index = Math.abs(hashValue % size_);
<del> if (filter_[index] == 0)
<del> {
<del> bVal = false;
<del> break;
<del> }
<del> }
<del> return bVal;
<del> }
<del>
<del> /*
<del> param@ key -- value whose hash is used to fill
<del> the filter_.
<del> This is a general purpose API.
<del> */
<del> public void add(String key)
<del> {
<del> if ( !isPresent(key) )
<del> ++count_;
<del> for (int i = 0; i < hashes_; ++i)
<del> {
<del> ISimpleHash hash = hashLibrary_.get(i);
<del> int hashValue = hash.hash(key);
<del> int index = Math.abs(hashValue % size_);
<del> byte value = (filter_[index] == 0xFF) ? filter_[index] : (byte)( (++filter_[index]) & 0xFF );
<del> filter_[index] = value;
<del> }
<del> }
<del>
<del> public boolean delete(String key)
<del> {
<del> boolean bVal = isPresent(key);
<del> if ( !bVal )
<del> {
<del> --count_;
<del> return bVal;
<del> }
<del>
<del> for (int i = 0; i < hashes_; ++i)
<del> {
<del> ISimpleHash hash = hashLibrary_.get(i);
<del> int hashValue = hash.hash(key);
<del> int index = Math.abs(hashValue % size_);
<del> byte value = (filter_[index] == 0) ? filter_[index] : (byte)( (--filter_[index]) & 0xFF );
<del> filter_[index] = value;
<del> }
<del>
<del> return bVal;
<del> }
<del>
<del> public int count()
<del> {
<del> return count_;
<del> }
<del> }
<del>
<add>{
<ide> private static List<ISimpleHash> hashLibrary_ = new ArrayList<ISimpleHash>();
<ide> private static ICompactSerializer<BloomFilter> serializer_;
<ide>
<ide> private int size_;
<ide> private int hashes_;
<ide> private Random random_ = new Random(System.currentTimeMillis());
<del>
<del> public BloomFilter(int bitsPerElement)
<del> {
<del> if (bitsPerElement < 1)
<del> throw new IllegalArgumentException("Number of bitsPerElement "
<del> + "must be non-negative.");
<del> // Adding a small random number of bits so that even if the set
<del> // of elements hasn't changed, we'll get different false positives.
<del> size_ = 20 + random_.nextInt(64);
<del> filter_ = new BitSet(size_);
<del> hashes_ = BloomCalculations.computeBestK(bitsPerElement);
<del> }
<ide>
<ide> public BloomFilter(int numElements, int bitsPerElement)
<ide> {
<ide> hashes_ = 8;
<ide> }
<ide>
<del> public BloomFilter(int numElements, double maxFalsePosProbability)
<del> {
<del> if (numElements < 0)
<del> throw new IllegalArgumentException("Number of elements must be "
<del> + "non-negative.");
<del> BloomCalculations.BloomSpecification spec = BloomCalculations
<del> .computeBitsAndK(maxFalsePosProbability);
<del> // Add a small random number of bits so that even if the set
<del> // of elements hasn't changed, we'll get different false positives.
<del> count_ = numElements;
<del> size_ = numElements * spec.bitsPerElement + 20 + random_.nextInt(64);
<del> filter_ = new BitSet(size_);
<del> hashes_ = spec.K;
<del> }
<del>
<ide> /*
<ide> * This version is only used by the deserializer.
<ide> */
<ide> BitSet filter()
<ide> {
<ide> return filter_;
<del> }
<del>
<del> public BloomFilter merge(BloomFilter bf)
<del> {
<del> BloomFilter mergedBf = null;
<del> if ( filter_.size() >= bf.filter_.size() )
<del> {
<del> filter_.or(bf.filter_);
<del> mergedBf = this;
<del> }
<del> else
<del> {
<del> bf.filter_.or(filter_);
<del> mergedBf = bf;
<del> }
<del> return mergedBf;
<ide> }
<ide>
<ide> public boolean isPresent(String key)
<ide> public String toString()
<ide> {
<ide> return filter_.toString();
<del> }
<del>
<del> public static void main(String[] args) throws Throwable
<del> {
<del> BloomFilter bf = new BloomFilter(64*1024*1024, 15);
<del> for ( int i = 0; i < 64*1024*1024; ++i )
<del> {
<del> bf.fill(Integer.toString(i));
<del> }
<del> System.out.println("Done filling ...");
<del> for ( int i = 0; i < 64*1024*1024; ++i )
<del> {
<del> if ( !bf.isPresent(Integer.toString(i)) )
<del> System.out.println("Oops");
<del> }
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del>class CountingBloomFilterSerializer implements ICompactSerializer<BloomFilter.CountingBloomFilter>
<del>{
<del> /*
<del> * The following methods are used for compact representation
<del> * of BloomFilter. This is essential, since we want to determine
<del> * the size of the serialized Bloom Filter blob before it is
<del> * populated armed with the knowledge of how many elements are
<del> * going to reside in it.
<del> */
<del>
<del> public void serialize(BloomFilter.CountingBloomFilter cbf, DataOutputStream dos)
<del> throws IOException
<del> {
<del> /* write the size of the BloomFilter */
<del> dos.writeInt(cbf.size());
<del> /* write the number of hash functions used */
<del> dos.writeInt(cbf.hashes());
<del>
<del> byte[] filter = cbf.filter();
<del> /* write length of the filter */
<del> dos.writeInt(filter.length);
<del> dos.write(filter);
<del> }
<del>
<del> public BloomFilter.CountingBloomFilter deserialize(DataInputStream dis) throws IOException
<del> {
<del> /* read the size of the bloom filter */
<del> int size = dis.readInt();
<del> /* read the number of hash functions */
<del> int hashes = dis.readInt();
<del> /* read the length of the filter */
<del> int length = dis.readInt();
<del> byte[] filter = new byte[length];
<del> dis.readFully(filter);
<del> return new BloomFilter.CountingBloomFilter(size, hashes, filter);
<del> }
<del>}
<del>
<ide> interface ISimpleHash
<ide> {
<ide> public int hash(String str); |
|
Java | apache-2.0 | 27235bb3076c869cc300986b27a20d2dae27542e | 0 | criccomini/ezdb | package ezdb.rocksdb;
import java.io.File;
import java.io.IOException;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import ezdb.rocksdb.util.FileUtils;
public class EzRocksDbJniFactory implements EzRocksDbFactory {
@Override
public RocksDB open(File path, Options options) throws IOException {
try {
return RocksDB.open(options, path.getAbsolutePath());
} catch (RocksDBException e) {
throw new IOException(e);
}
}
@Override
public void destroy(File path, Options options) throws IOException {
// implementation taken from java port of leveldb
FileUtils.deleteRecursively(path);
}
}
| ezdb-rocksdb-jni/src/main/java/ezdb/rocksdb/EzRocksDbJniFactory.java | package ezdb.rocksdb;
import java.io.File;
import java.io.IOException;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import ezdb.rocksdb.util.FileUtils;
public class EzRocksDbJniFactory implements EzRocksDbFactory {
@Override
public RocksDB open(File path, Options options) throws IOException {
try {
return RocksDB.open(options, path.getAbsolutePath());
} catch (RocksDBException e) {
throw new IOException(e);
}
}
@Override
public void destroy(File path, Options options) throws IOException {
//implementation taken from java port of leveldb
try {
RocksDB.destroyDB(path.getAbsolutePath(), options);
} catch (RocksDBException e) {
throw new IOException(e);
}
}
}
| revert destroy impl | ezdb-rocksdb-jni/src/main/java/ezdb/rocksdb/EzRocksDbJniFactory.java | revert destroy impl | <ide><path>zdb-rocksdb-jni/src/main/java/ezdb/rocksdb/EzRocksDbJniFactory.java
<ide>
<ide> @Override
<ide> public void destroy(File path, Options options) throws IOException {
<del> //implementation taken from java port of leveldb
<del> try {
<del> RocksDB.destroyDB(path.getAbsolutePath(), options);
<del> } catch (RocksDBException e) {
<del> throw new IOException(e);
<del> }
<add> // implementation taken from java port of leveldb
<add> FileUtils.deleteRecursively(path);
<ide> }
<ide> } |
|
Java | epl-1.0 | e72bc0b9cabb4302bf97920122b8e15442b9d5ad | 0 | alastrina123/debrief,debrief/debrief,debrief/debrief,pecko/debrief,pecko/debrief,pecko/debrief,alastrina123/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,alastrina123/debrief,debrief/debrief,pecko/debrief,alastrina123/debrief,alastrina123/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,pecko/debrief,debrief/debrief,theanuradha/debrief,pecko/debrief,pecko/debrief,alastrina123/debrief,theanuradha/debrief,alastrina123/debrief,theanuradha/debrief | package org.mwc.debrief.satc_interface.actions;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.CMAPOperation;
import org.mwc.cmap.core.property_support.RightClickSupport.RightClickContextItemGenerator;
import org.mwc.debrief.satc_interface.SATC_Interface_Activator;
import org.mwc.debrief.satc_interface.data.SATC_Solution;
import org.mwc.debrief.satc_interface.data.wrappers.ContributionWrapper;
import org.mwc.debrief.satc_interface.utilities.conversions;
import org.mwc.debrief.satc_interface.wizards.NewStraightLegWizard;
import Debrief.Wrappers.SensorContactWrapper;
import Debrief.Wrappers.SensorWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.TimePeriod.BaseTimePeriod;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
import com.planetmayo.debrief.satc.model.GeoPoint;
import com.planetmayo.debrief.satc.model.contributions.BaseContribution;
import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution;
import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution.BMeasurement;
import com.planetmayo.debrief.satc.model.contributions.CourseAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.CourseForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.LocationAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.RangeForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.RangeForecastContribution.ROrigin;
import com.planetmayo.debrief.satc.model.contributions.SpeedAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.SpeedForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.StraightLegForecastContribution;
import com.planetmayo.debrief.satc.model.generator.IContributions;
import com.planetmayo.debrief.satc.model.generator.ISolver;
import com.planetmayo.debrief.satc.model.manager.ISolversManager;
import com.planetmayo.debrief.satc_rcp.SATC_Activator;
public class CreateSolutionFromSensorData implements
RightClickContextItemGenerator
{
@Override
public void generate(IMenuManager parent, final Layers theLayers,
Layer[] parentLayers, Editable[] subjects)
{
ArrayList<SensorContactWrapper> validCuts = null;
IMenuManager thisMenu = new MenuManager("SemiAuto TMA");
parent.add(thisMenu);
for (int i = 0; i < subjects.length; i++)
{
Editable thisItem = subjects[i];
if (thisItem instanceof SensorContactWrapper)
{
SensorContactWrapper scw = (SensorContactWrapper) thisItem;
if (scw.getVisible())
{
if (validCuts == null)
validCuts = new ArrayList<SensorContactWrapper>();
// SPECIAL PROCESSING: if the user has accidentally selected both the
// sensor and a block of cuts, they will get added twice.
// so - double-check we haven't already loaded this cut
if (!validCuts.contains(scw))
validCuts.add(scw);
}
}
else if (thisItem instanceof SensorWrapper)
{
SensorWrapper sw = (SensorWrapper) thisItem;
Enumeration<Editable> cuts = sw.elements();
while (cuts.hasMoreElements())
{
SensorContactWrapper thisCut = (SensorContactWrapper) cuts
.nextElement();
if (thisCut.getVisible())
{
if (validCuts == null)
validCuts = new ArrayList<SensorContactWrapper>();
// SPECIAL PROCESSING: see above for duplicate cuts
if (!validCuts.contains(thisCut))
validCuts.add(thisCut);
}
}
}
else if ((thisItem instanceof ContributionWrapper)
|| (thisItem instanceof SATC_Solution))
{
if (subjects.length == 1)
{
BaseTimePeriod period = null;
if (thisItem instanceof ContributionWrapper)
{
ContributionWrapper cw = (ContributionWrapper) thisItem;
BaseContribution theCont = cw.getContribution();
period = new TimePeriod.BaseTimePeriod(new HiResDate(
theCont.getStartDate()), new HiResDate(theCont.getFinishDate()));
}
else
{
SATC_Solution solution = (SATC_Solution) thisItem;
if (solution.getSolver().getProblemSpace().getStartDate() != null)
period = new TimePeriod.BaseTimePeriod(solution.getStartDTG(),
solution.getEndDTG());
}
// did it work?
if (period != null)
{
parent.add(new Separator());
SATC_Solution solution = (SATC_Solution) parentLayers[0];
String actionTitle = "Add new contribution";
parent.add(new DoIt("Add Speed Forecast for period covered by ["
+ thisItem.getName() + "]",
new SpeedForecastContributionFromCuts(solution, actionTitle,
theLayers, period), "icons/speed.png"));
parent.add(new DoIt("Add Course Forecast for period covered by ["
+ thisItem.getName() + "]",
new CourseForecastContributionFromCuts(solution, actionTitle,
theLayers, period), "icons/direction.png"));
parent.add(new DoIt("Add Straight Leg for period covered by ["
+ thisItem.getName() + "]",
new StraightLegForecastContributionFromCuts(solution,
actionTitle, theLayers, period), "icons/leg.png"));
}
}
}
}
// ok, is it worth going for?
if (validCuts != null)
{
final String title;
if (validCuts.size() > 1)
title = "sensor cuts";
else
title = "sensor cut";
// right,stick in a separator
thisMenu.add(new Separator());
// see if there's an existing solution in there.
SATC_Solution[] existingSolutions = findExistingSolutionsIn(theLayers);
if ((existingSolutions != null) && (existingSolutions.length > 0))
{
for (int i = 0; i < existingSolutions.length; i++)
{
final SATC_Solution layer = existingSolutions[i];
// create a top level menu item
MenuManager thisD = new MenuManager("Add to " + layer.getName());
thisMenu.add(thisD);
// add the child items
addItemsTo(layer, thisD, validCuts, title, null, "");
}
}
DoIt wizardItem = new DoIt("Create new scenario from these cuts",
new BearingMeasurementContributionFromCuts(null, title, theLayers,
validCuts)
{
@Override
public String getContributionName()
{
return "Bearing data";
}
}, "icons/calculator.gif");
thisMenu.add(wizardItem);
}
}
protected void addItemsTo(final SATC_Solution solution,
final MenuManager parent,
final ArrayList<SensorContactWrapper> validItems, final String title,
Layers layers, String verb1)
{
String actionTitle = "Add new contribution";
DoIt wizardItem = new DoIt(
"Open Straight Leg Wizard for period covered by [" + title + "]",
new StraightLegWizardFromCuts(solution, actionTitle, layers, validItems),
"icons/wizard.png");
parent.add(wizardItem);
parent.add(new Separator());
parent.add(new DoIt(verb1 + "Bearing Measurement from " + title,
new BearingMeasurementContributionFromCuts(solution, actionTitle,
layers, validItems), "icons/bearings.gif"));
parent.add(new DoIt(verb1 + "Speed Forecast for period covered by ["
+ title + "]", new SpeedForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/speed.png"));
parent.add(new DoIt(verb1 + "Range Forecast for period covered by ["
+ title + "]", new RangeForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/range.png"));
parent.add(new DoIt(verb1 + "Course Forecast for period covered by ["
+ title + "]", new CourseForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/direction.png"));
parent.add(new DoIt(verb1 + "Straight Leg for period covered by [" + title
+ "]", new StraightLegForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/leg.png"));
}
protected static class DoIt extends Action
{
private final IUndoableOperation _myOperation;
DoIt(String title, IUndoableOperation operation, String path)
{
super(title);
_myOperation = operation;
this.setImageDescriptor(SATC_Interface_Activator.getImageDescriptor(path));
}
@Override
public void run()
{
CorePlugin.run(_myOperation);
}
}
/**
* put the operation firer onto the undo history. We've refactored this into a
* separate method so testing classes don't have to simulate the CorePlugin
*
* @param operation
*/
protected void runIt(IUndoableOperation operation)
{
CorePlugin.run(operation);
}
private SATC_Solution[] findExistingSolutionsIn(Layers theLayers)
{
ArrayList<SATC_Solution> res = null;
Enumeration<Editable> iter = theLayers.elements();
while (iter.hasMoreElements())
{
Editable thisL = iter.nextElement();
if (thisL instanceof SATC_Solution)
{
if (res == null)
res = new ArrayList<SATC_Solution>();
res.add((SATC_Solution) thisL);
}
}
SATC_Solution[] list = null;
if (res != null)
list = res.toArray(new SATC_Solution[]
{});
return list;
}
private class BearingMeasurementContributionFromCuts extends
CoreSolutionFromCuts
{
private ArrayList<SensorContactWrapper> _validCuts;
public BearingMeasurementContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, new TimePeriod.BaseTimePeriod(
new HiResDate(validCuts.get(0).getDTG().getDate()), new HiResDate(
validCuts.get(validCuts.size() - 1).getDTG())));
_validCuts = validCuts;
}
protected BearingMeasurementContribution createContribution(String contName)
{
// ok, now collate the contriubtion
final BearingMeasurementContribution bmc = new BearingMeasurementContribution();
bmc.setName(contName);
bmc.setBearingError(Math.toRadians(3.0));
bmc.setAutoDetect(false);
// add the bearing data
Iterator<SensorContactWrapper> iter = _validCuts.iterator();
while (iter.hasNext())
{
final SensorContactWrapper scw = (SensorContactWrapper) iter.next();
WorldLocation theOrigin = scw.getOrigin();
GeoPoint loc;
if (theOrigin == null)
theOrigin = scw.getCalculatedOrigin(scw.getSensor().getHost());
loc = conversions.toPoint(theOrigin);
double brg = Math.toRadians(scw.getBearing());
Date date = scw.getDTG().getDate();
Double theRange = null;
if (scw.getRange() != null)
theRange = scw.getRange().getValueIn(WorldDistance.METRES);
final BMeasurement thisM = new BMeasurement(loc, brg, date, theRange);
// give it the respective color
thisM.setColor(scw.getColor());
// ok, store it.
bmc.addMeasurement(thisM);
}
return bmc;
}
}
private class SpeedForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public SpeedForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public SpeedForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new SpeedForecastContribution();
}
}
private class CourseForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public CourseForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public CourseForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new CourseForecastContribution();
}
}
private class RangeForecastContributionFromCuts extends
ForecastContributionFromCuts
{
private ArrayList<SensorContactWrapper> _validCuts;
public RangeForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
_validCuts = validCuts;
}
@Override
protected BaseContribution getContribution()
{
RangeForecastContribution rfc = new RangeForecastContribution();
// now set the range origins
// add the bearing data
Iterator<SensorContactWrapper> iter = _validCuts.iterator();
while (iter.hasNext())
{
final SensorContactWrapper scw = (SensorContactWrapper) iter.next();
WorldLocation theOrigin = scw.getOrigin();
GeoPoint loc;
if (theOrigin == null)
theOrigin = scw.getCalculatedOrigin(scw.getSensor().getHost());
loc = conversions.toPoint(theOrigin);
RangeForecastContribution.ROrigin newR = new ROrigin(loc, scw.getDTG()
.getDate());
rfc.addThis(newR);
}
return rfc;
}
}
private class StraightLegWizardFromCuts extends ForecastContributionFromCuts
{
private NewStraightLegWizard _wizard;
public StraightLegWizardFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
// sort out the straight leg component
super(existingSolution, title, theLayers, validCuts);
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
{
// find out the period
TimePeriod period = super.getPeriod();
initSolver();
// ok, sort out the wizard
_wizard = new NewStraightLegWizard(period);
WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(),
_wizard);
wd.setTitle("New Straight Leg Forecast");
wd.open();
if (wd.getReturnCode() == WizardDialog.OK)
{
// ok, are there any?
ArrayList<BaseContribution> conts = _wizard.getContributions();
if (conts.size() > 0)
{
Iterator<BaseContribution> iter = conts.iterator();
while (iter.hasNext())
{
BaseContribution baseContribution = (BaseContribution) iter.next();
getSolver().addContribution(baseContribution);
}
}
}
return Status.CANCEL_STATUS;
}
@Override
protected BaseContribution getContribution()
{
return null;
}
}
private class StraightLegForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public StraightLegForecastContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public StraightLegForecastContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new StraightLegForecastContribution();
}
}
private abstract class ForecastContributionFromCuts extends
CoreSolutionFromCuts
{
public ForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, new TimePeriod.BaseTimePeriod(
new HiResDate(validCuts.get(0).getDTG().getDate()), new HiResDate(
validCuts.get(validCuts.size() - 1).getDTG())));
}
public ForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod timePeriod)
{
super(existingSolution, title, theLayers, timePeriod);
}
protected final BaseContribution createContribution(String contName)
{
// ok, now collate the contriubtion
BaseContribution bmc = getContribution();
// ok, do some formatting
bmc.setName(contName);
// and the dates
bmc.setStartDate(thePeriod.getStartDTG().getDate());
bmc.setFinishDate(thePeriod.getEndDTG().getDate());
return bmc;
}
abstract protected BaseContribution getContribution();
}
private abstract class CoreSolutionFromCuts extends CMAPOperation
{
private SATC_Solution _targetSolution;
private final Layers _theLayers;
protected TimePeriod thePeriod;
public CoreSolutionFromCuts(SATC_Solution existingSolution, String title,
Layers theLayers, BaseContribution existingContribution)
{
super(title);
_targetSolution = existingSolution;
_theLayers = theLayers;
thePeriod = new TimePeriod.BaseTimePeriod(new HiResDate(
existingContribution.getStartDate()), new HiResDate(
existingContribution.getFinishDate()));
}
public CoreSolutionFromCuts(SATC_Solution existingSolution, String title,
Layers theLayers, TimePeriod thePeriod)
{
super(title);
_targetSolution = existingSolution;
_theLayers = theLayers;
this.thePeriod = thePeriod;
}
protected TimePeriod getPeriod()
{
return thePeriod;
}
public String getDefaultSolutionName()
{ // grab a name
Date firstCutDate = thePeriod.getStartDTG().getDate();
String formattedName = FormatRNDateTime.toString(firstCutDate.getTime());
return formattedName;
}
@Override
public boolean canUndo()
{
return false;
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
{
initSolver();
String contName = getContributionName();
if (contName != null)
{
// ok = now get our specific contribution
BaseContribution bmc = createContribution(contName);
// and store it - if it worked
if (bmc != null)
_targetSolution.addContribution(bmc);
}
return Status.OK_STATUS;
}
protected void initSolver()
{
// ok, do we have an existing solution
if (_targetSolution == null)
{
String solutionName = getDefaultSolutionName();
// create a new solution
final ISolversManager solvMgr = SATC_Activator.getDefault().getService(
ISolversManager.class, true);
final ISolver newSolution = solvMgr.createSolver(solutionName);
_targetSolution = new SATC_Solution(newSolution);
_theLayers.addThisLayer(_targetSolution);
// ok, give it the default contributions
initialiseSolver();
}
}
protected String getContributionName()
{
String res = null;
// grab a name
// create input box dialog
InputDialog inp = new InputDialog(Display.getCurrent().getActiveShell(),
"New contribution", "What is the name of this contribution",
"name here", null);
// did he cancel?
if (inp.open() == InputDialog.OK)
{
// get the results
res = inp.getValue();
}
return res;
}
private void initialiseSolver()
{
IContributions theConts = _targetSolution.getSolver().getContributions();
theConts.addContribution(new LocationAnalysisContribution());
theConts.addContribution(new SpeedAnalysisContribution());
theConts.addContribution(new CourseAnalysisContribution());
}
public SATC_Solution getSolver()
{
return _targetSolution;
}
abstract protected BaseContribution createContribution(String contName);
@Override
public IStatus undo(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException
{
// duh, ignore
return null;
}
}
}
| satc/satc_interface/src/org/mwc/debrief/satc_interface/actions/CreateSolutionFromSensorData.java | package org.mwc.debrief.satc_interface.actions;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.CMAPOperation;
import org.mwc.cmap.core.property_support.RightClickSupport.RightClickContextItemGenerator;
import org.mwc.debrief.satc_interface.SATC_Interface_Activator;
import org.mwc.debrief.satc_interface.data.SATC_Solution;
import org.mwc.debrief.satc_interface.data.wrappers.ContributionWrapper;
import org.mwc.debrief.satc_interface.utilities.conversions;
import org.mwc.debrief.satc_interface.wizards.NewStraightLegWizard;
import Debrief.Wrappers.SensorContactWrapper;
import Debrief.Wrappers.SensorWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.TimePeriod.BaseTimePeriod;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
import com.planetmayo.debrief.satc.model.GeoPoint;
import com.planetmayo.debrief.satc.model.contributions.BaseContribution;
import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution;
import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution.BMeasurement;
import com.planetmayo.debrief.satc.model.contributions.CourseAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.CourseForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.LocationAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.RangeForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.RangeForecastContribution.ROrigin;
import com.planetmayo.debrief.satc.model.contributions.SpeedAnalysisContribution;
import com.planetmayo.debrief.satc.model.contributions.SpeedForecastContribution;
import com.planetmayo.debrief.satc.model.contributions.StraightLegForecastContribution;
import com.planetmayo.debrief.satc.model.generator.IContributions;
import com.planetmayo.debrief.satc.model.generator.ISolver;
import com.planetmayo.debrief.satc.model.manager.ISolversManager;
import com.planetmayo.debrief.satc_rcp.SATC_Activator;
public class CreateSolutionFromSensorData implements
RightClickContextItemGenerator
{
@Override
public void generate(IMenuManager parent, final Layers theLayers,
Layer[] parentLayers, Editable[] subjects)
{
ArrayList<SensorContactWrapper> validCuts = null;
IMenuManager thisMenu = new MenuManager("SemiAuto TMA");
parent.add(thisMenu);
for (int i = 0; i < subjects.length; i++)
{
Editable thisItem = subjects[i];
if (thisItem instanceof SensorContactWrapper)
{
if (validCuts == null)
validCuts = new ArrayList<SensorContactWrapper>();
validCuts.add((SensorContactWrapper) thisItem);
}
else if (thisItem instanceof SensorWrapper)
{
if (validCuts == null)
validCuts = new ArrayList<SensorContactWrapper>();
SensorWrapper sw = (SensorWrapper) thisItem;
Enumeration<Editable> cuts = sw.elements();
while (cuts.hasMoreElements())
{
validCuts.add((SensorContactWrapper) cuts.nextElement());
}
}
else if ((thisItem instanceof ContributionWrapper)
|| (thisItem instanceof SATC_Solution))
{
if (subjects.length == 1)
{
BaseTimePeriod period = null;
if (thisItem instanceof ContributionWrapper)
{
ContributionWrapper cw = (ContributionWrapper) thisItem;
BaseContribution theCont = cw.getContribution();
period = new TimePeriod.BaseTimePeriod(new HiResDate(
theCont.getStartDate()), new HiResDate(theCont.getFinishDate()));
}
else
{
SATC_Solution solution = (SATC_Solution) thisItem;
if (solution.getSolver().getProblemSpace().getStartDate() != null)
period = new TimePeriod.BaseTimePeriod(solution.getStartDTG(),
solution.getEndDTG());
}
// did it work?
if (period != null)
{
parent.add(new Separator());
SATC_Solution solution = (SATC_Solution) parentLayers[0];
String actionTitle = "Add new contribution";
parent.add(new DoIt("Add Speed Forecast for period covered by ["
+ thisItem.getName() + "]",
new SpeedForecastContributionFromCuts(solution, actionTitle,
theLayers, period), "icons/speed.png"));
parent.add(new DoIt("Add Course Forecast for period covered by ["
+ thisItem.getName() + "]",
new CourseForecastContributionFromCuts(solution, actionTitle,
theLayers, period), "icons/direction.png"));
parent.add(new DoIt("Add Straight Leg for period covered by ["
+ thisItem.getName() + "]",
new StraightLegForecastContributionFromCuts(solution,
actionTitle, theLayers, period), "icons/leg.png"));
}
}
}
}
// ok, is it worth going for?
if (validCuts != null)
{
final String title;
if (validCuts.size() > 1)
title = "sensor cuts";
else
title = "sensor cut";
// right,stick in a separator
thisMenu.add(new Separator());
// see if there's an existing solution in there.
SATC_Solution[] existingSolutions = findExistingSolutionsIn(theLayers);
if ((existingSolutions != null) && (existingSolutions.length > 0))
{
for (int i = 0; i < existingSolutions.length; i++)
{
final SATC_Solution layer = existingSolutions[i];
// create a top level menu item
MenuManager thisD = new MenuManager("Add to " + layer.getName());
thisMenu.add(thisD);
// add the child items
addItemsTo(layer, thisD, validCuts, title, null, "");
}
}
DoIt wizardItem = new DoIt("Create new scenario from these cuts",
new BearingMeasurementContributionFromCuts(null, title, theLayers,
validCuts){
@Override
public String getContributionName()
{
return "Bearing data";
}}, "icons/calculator.gif");
thisMenu.add(wizardItem);
}
}
protected void addItemsTo(final SATC_Solution solution,
final MenuManager parent,
final ArrayList<SensorContactWrapper> validItems, final String title,
Layers layers, String verb1)
{
String actionTitle = "Add new contribution";
DoIt wizardItem = new DoIt(
"Open Straight Leg Wizard for period covered by [" + title + "]",
new StraightLegWizardFromCuts(solution, actionTitle, layers, validItems),
"icons/wizard.png");
parent.add(wizardItem);
parent.add(new Separator());
parent.add(new DoIt(verb1 + "Bearing Measurement from " + title,
new BearingMeasurementContributionFromCuts(solution, actionTitle,
layers, validItems), "icons/bearings.gif"));
parent.add(new DoIt(verb1 + "Speed Forecast for period covered by ["
+ title + "]", new SpeedForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/speed.png"));
parent.add(new DoIt(verb1 + "Range Forecast for period covered by ["
+ title + "]", new RangeForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/range.png"));
parent.add(new DoIt(verb1 + "Course Forecast for period covered by ["
+ title + "]", new CourseForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/direction.png"));
parent.add(new DoIt(verb1 + "Straight Leg for period covered by [" + title
+ "]", new StraightLegForecastContributionFromCuts(solution,
actionTitle, layers, validItems), "icons/leg.png"));
}
protected static class DoIt extends Action
{
private final IUndoableOperation _myOperation;
DoIt(String title, IUndoableOperation operation, String path)
{
super(title);
_myOperation = operation;
this.setImageDescriptor(SATC_Interface_Activator.getImageDescriptor(path));
}
@Override
public void run()
{
CorePlugin.run(_myOperation);
}
}
/**
* put the operation firer onto the undo history. We've refactored this into a
* separate method so testing classes don't have to simulate the CorePlugin
*
* @param operation
*/
protected void runIt(IUndoableOperation operation)
{
CorePlugin.run(operation);
}
private SATC_Solution[] findExistingSolutionsIn(Layers theLayers)
{
ArrayList<SATC_Solution> res = null;
Enumeration<Editable> iter = theLayers.elements();
while (iter.hasMoreElements())
{
Editable thisL = iter.nextElement();
if (thisL instanceof SATC_Solution)
{
if (res == null)
res = new ArrayList<SATC_Solution>();
res.add((SATC_Solution) thisL);
}
}
SATC_Solution[] list = null;
if (res != null)
list = res.toArray(new SATC_Solution[]
{});
return list;
}
private class BearingMeasurementContributionFromCuts extends
CoreSolutionFromCuts
{
private ArrayList<SensorContactWrapper> _validCuts;
public BearingMeasurementContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, new TimePeriod.BaseTimePeriod(
new HiResDate(validCuts.get(0).getDTG().getDate()), new HiResDate(
validCuts.get(validCuts.size() - 1).getDTG())));
_validCuts = validCuts;
}
protected BearingMeasurementContribution createContribution(String contName)
{
// ok, now collate the contriubtion
final BearingMeasurementContribution bmc = new BearingMeasurementContribution();
bmc.setName(contName);
bmc.setBearingError(Math.toRadians(3.0));
bmc.setAutoDetect(false);
// add the bearing data
Iterator<SensorContactWrapper> iter = _validCuts.iterator();
while (iter.hasNext())
{
final SensorContactWrapper scw = (SensorContactWrapper) iter.next();
WorldLocation theOrigin = scw.getOrigin();
GeoPoint loc;
if (theOrigin == null)
theOrigin = scw.getCalculatedOrigin(scw.getSensor().getHost());
loc = conversions.toPoint(theOrigin);
double brg = Math.toRadians(scw.getBearing());
Date date = scw.getDTG().getDate();
Double theRange = null;
if (scw.getRange() != null)
theRange = scw.getRange().getValueIn(WorldDistance.METRES);
final BMeasurement thisM = new BMeasurement(loc, brg, date, theRange);
// give it the respective color
thisM.setColor(scw.getColor());
// ok, store it.
bmc.addMeasurement(thisM);
}
return bmc;
}
}
private class SpeedForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public SpeedForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public SpeedForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new SpeedForecastContribution();
}
}
private class CourseForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public CourseForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public CourseForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new CourseForecastContribution();
}
}
private class RangeForecastContributionFromCuts extends
ForecastContributionFromCuts
{
private ArrayList<SensorContactWrapper> _validCuts;
public RangeForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
_validCuts = validCuts;
}
@Override
protected BaseContribution getContribution()
{
RangeForecastContribution rfc = new RangeForecastContribution();
// now set the range origins
// add the bearing data
Iterator<SensorContactWrapper> iter = _validCuts.iterator();
while (iter.hasNext())
{
final SensorContactWrapper scw = (SensorContactWrapper) iter.next();
WorldLocation theOrigin = scw.getOrigin();
GeoPoint loc;
if (theOrigin == null)
theOrigin = scw.getCalculatedOrigin(scw.getSensor().getHost());
loc = conversions.toPoint(theOrigin);
RangeForecastContribution.ROrigin newR = new ROrigin(loc, scw.getDTG()
.getDate());
rfc.addThis(newR);
}
return rfc;
}
}
private class StraightLegWizardFromCuts extends ForecastContributionFromCuts
{
private NewStraightLegWizard _wizard;
public StraightLegWizardFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
// sort out the straight leg component
super(existingSolution, title, theLayers, validCuts);
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
{
// find out the period
TimePeriod period = super.getPeriod();
initSolver();
// ok, sort out the wizard
_wizard = new NewStraightLegWizard(period);
WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(),
_wizard);
wd.setTitle("New Straight Leg Forecast");
wd.open();
if (wd.getReturnCode() == WizardDialog.OK)
{
// ok, are there any?
ArrayList<BaseContribution> conts = _wizard.getContributions();
if (conts.size() > 0)
{
Iterator<BaseContribution> iter = conts.iterator();
while (iter.hasNext())
{
BaseContribution baseContribution = (BaseContribution) iter.next();
getSolver().addContribution(baseContribution);
}
}
}
return Status.CANCEL_STATUS;
}
@Override
protected BaseContribution getContribution()
{
return null;
}
}
private class StraightLegForecastContributionFromCuts extends
ForecastContributionFromCuts
{
public StraightLegForecastContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, validCuts);
}
public StraightLegForecastContributionFromCuts(
SATC_Solution existingSolution, String title, Layers theLayers,
TimePeriod period)
{
super(existingSolution, title, theLayers, period);
}
@Override
protected BaseContribution getContribution()
{
return new StraightLegForecastContribution();
}
}
private abstract class ForecastContributionFromCuts extends
CoreSolutionFromCuts
{
public ForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers,
ArrayList<SensorContactWrapper> validCuts)
{
super(existingSolution, title, theLayers, new TimePeriod.BaseTimePeriod(
new HiResDate(validCuts.get(0).getDTG().getDate()), new HiResDate(
validCuts.get(validCuts.size() - 1).getDTG())));
}
public ForecastContributionFromCuts(SATC_Solution existingSolution,
String title, Layers theLayers, TimePeriod timePeriod)
{
super(existingSolution, title, theLayers, timePeriod);
}
protected final BaseContribution createContribution(String contName)
{
// ok, now collate the contriubtion
BaseContribution bmc = getContribution();
// ok, do some formatting
bmc.setName(contName);
// and the dates
bmc.setStartDate(thePeriod.getStartDTG().getDate());
bmc.setFinishDate(thePeriod.getEndDTG().getDate());
return bmc;
}
abstract protected BaseContribution getContribution();
}
private abstract class CoreSolutionFromCuts extends CMAPOperation
{
private SATC_Solution _targetSolution;
private final Layers _theLayers;
protected TimePeriod thePeriod;
public CoreSolutionFromCuts(SATC_Solution existingSolution, String title,
Layers theLayers, BaseContribution existingContribution)
{
super(title);
_targetSolution = existingSolution;
_theLayers = theLayers;
thePeriod = new TimePeriod.BaseTimePeriod(new HiResDate(
existingContribution.getStartDate()), new HiResDate(
existingContribution.getFinishDate()));
}
public CoreSolutionFromCuts(SATC_Solution existingSolution, String title,
Layers theLayers, TimePeriod thePeriod)
{
super(title);
_targetSolution = existingSolution;
_theLayers = theLayers;
this.thePeriod = thePeriod;
}
protected TimePeriod getPeriod()
{
return thePeriod;
}
public String getDefaultSolutionName()
{ // grab a name
Date firstCutDate = thePeriod.getStartDTG().getDate();
String formattedName = FormatRNDateTime.toString(firstCutDate.getTime());
return formattedName;
}
@Override
public boolean canUndo()
{
return false;
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
{
initSolver();
String contName = getContributionName();
if (contName != null)
{
// ok = now get our specific contribution
BaseContribution bmc = createContribution(contName);
// and store it - if it worked
if (bmc != null)
_targetSolution.addContribution(bmc);
}
return Status.OK_STATUS;
}
protected void initSolver()
{
// ok, do we have an existing solution
if (_targetSolution == null)
{
String solutionName = getDefaultSolutionName();
// create a new solution
final ISolversManager solvMgr = SATC_Activator.getDefault().getService(
ISolversManager.class, true);
final ISolver newSolution = solvMgr.createSolver(solutionName);
_targetSolution = new SATC_Solution(newSolution);
_theLayers.addThisLayer(_targetSolution);
// ok, give it the default contributions
initialiseSolver();
}
}
protected String getContributionName()
{
String res = null;
// grab a name
// create input box dialog
InputDialog inp = new InputDialog(Display.getCurrent().getActiveShell(),
"New contribution", "What is the name of this contribution",
"name here", null);
// did he cancel?
if (inp.open() == InputDialog.OK)
{
// get the results
res = inp.getValue();
}
return res;
}
private void initialiseSolver()
{
IContributions theConts = _targetSolution.getSolver().getContributions();
theConts.addContribution(new LocationAnalysisContribution());
theConts.addContribution(new SpeedAnalysisContribution());
theConts.addContribution(new CourseAnalysisContribution());
}
public SATC_Solution getSolver()
{
return _targetSolution;
}
abstract protected BaseContribution createContribution(String contName);
@Override
public IStatus undo(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException
{
// duh, ignore
return null;
}
}
}
| Only add visible cuts to the bearing contribution
| satc/satc_interface/src/org/mwc/debrief/satc_interface/actions/CreateSolutionFromSensorData.java | Only add visible cuts to the bearing contribution | <ide><path>atc/satc_interface/src/org/mwc/debrief/satc_interface/actions/CreateSolutionFromSensorData.java
<ide> Editable thisItem = subjects[i];
<ide> if (thisItem instanceof SensorContactWrapper)
<ide> {
<del> if (validCuts == null)
<del> validCuts = new ArrayList<SensorContactWrapper>();
<del>
<del> validCuts.add((SensorContactWrapper) thisItem);
<add> SensorContactWrapper scw = (SensorContactWrapper) thisItem;
<add>
<add> if (scw.getVisible())
<add> {
<add> if (validCuts == null)
<add> validCuts = new ArrayList<SensorContactWrapper>();
<add>
<add> // SPECIAL PROCESSING: if the user has accidentally selected both the
<add> // sensor and a block of cuts, they will get added twice.
<add> // so - double-check we haven't already loaded this cut
<add> if (!validCuts.contains(scw))
<add> validCuts.add(scw);
<add> }
<ide> }
<ide> else if (thisItem instanceof SensorWrapper)
<ide> {
<del> if (validCuts == null)
<del> validCuts = new ArrayList<SensorContactWrapper>();
<del>
<ide> SensorWrapper sw = (SensorWrapper) thisItem;
<add>
<ide> Enumeration<Editable> cuts = sw.elements();
<ide> while (cuts.hasMoreElements())
<ide> {
<del> validCuts.add((SensorContactWrapper) cuts.nextElement());
<add> SensorContactWrapper thisCut = (SensorContactWrapper) cuts
<add> .nextElement();
<add> if (thisCut.getVisible())
<add> {
<add> if (validCuts == null)
<add> validCuts = new ArrayList<SensorContactWrapper>();
<add>
<add> // SPECIAL PROCESSING: see above for duplicate cuts
<add> if (!validCuts.contains(thisCut))
<add> validCuts.add(thisCut);
<add> }
<ide> }
<ide> }
<ide> else if ((thisItem instanceof ContributionWrapper)
<ide>
<ide> DoIt wizardItem = new DoIt("Create new scenario from these cuts",
<ide> new BearingMeasurementContributionFromCuts(null, title, theLayers,
<del> validCuts){
<del>
<del> @Override
<del> public String getContributionName()
<del> {
<del>
<del> return "Bearing data";
<del> }}, "icons/calculator.gif");
<add> validCuts)
<add> {
<add>
<add> @Override
<add> public String getContributionName()
<add> {
<add>
<add> return "Bearing data";
<add> }
<add> }, "icons/calculator.gif");
<ide> thisMenu.add(wizardItem);
<ide> }
<ide> } |
|
Java | apache-2.0 | a1bcdbbee7e136a1772a2cbb6a41ebcba46d025a | 0 | gemmellr/qpid-jms,apache/qpid-jms,gemmellr/qpid-jms,avranju/qpid-jms,andrew-buckley/qpid-jms,tabish121/qpid-jms,apache/qpid-jms,andrew-buckley/qpid-jms,avranju/qpid-jms,tabish121/qpid-jms | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.qpid.jms.provider.amqp;
import org.apache.qpid.proton.amqp.DescribedType;
import org.apache.qpid.proton.amqp.UnsignedLong;
/**
* A Described Type wrapper for JMS selector values.
*/
public class AmqpJmsSelectorType implements DescribedType {
private final String selector;
public AmqpJmsSelectorType(String selector) {
this.selector = selector;
}
@Override
public Object getDescriptor() {
return UnsignedLong.valueOf(0x0000468C00000004L);
}
@Override
public Object getDescribed() {
return this.selector;
}
@Override
public String toString() {
return "AmqpJmsSelectorType{" + selector + "}";
}
}
| qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/amqp/AmqpJmsSelectorType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.qpid.jms.provider.amqp;
import org.apache.qpid.proton.amqp.DescribedType;
import org.apache.qpid.proton.amqp.UnsignedLong;
/**
* A Described Type wrapper for JMS selector values.
*/
public class AmqpJmsSelectorType implements DescribedType {
private final String selector;
public AmqpJmsSelectorType(String selector) {
this.selector = selector;
}
@Override
public Object getDescriptor() {
return UnsignedLong.valueOf(0x0000468C00000004L);
}
@Override
public Object getDescribed() {
return this.selector;
}
}
| add toString for the selector filter
| qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/amqp/AmqpJmsSelectorType.java | add toString for the selector filter | <ide><path>pid-jms-client/src/main/java/org/apache/qpid/jms/provider/amqp/AmqpJmsSelectorType.java
<ide> public Object getDescribed() {
<ide> return this.selector;
<ide> }
<add>
<add> @Override
<add> public String toString() {
<add> return "AmqpJmsSelectorType{" + selector + "}";
<add> }
<ide> } |
|
Java | apache-2.0 | d6c82a395fc34388f012aee3626ee68d90d9b01b | 0 | osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi | package org.osgi.test.cases.converter.junit;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.osgi.test.cases.converter.junit.ConversionComplianceTest.ExtObject;
import org.osgi.test.cases.converter.junit.MapInterfaceJavaBeansDTOAndAnnotationConversionComplianceTest.MappingBean;
import org.osgi.util.converter.ConversionException;
import org.osgi.util.converter.Converter;
import org.osgi.util.converter.ConverterBuilder;
import org.osgi.util.converter.ConverterFunction;
import org.osgi.util.converter.Converters;
import org.osgi.util.converter.TypeReference;
import org.osgi.util.converter.TypeRule;
import org.osgi.util.function.Function;
import junit.framework.TestCase;
public class CustomizedConversionComplianceTest extends TestCase {
public static class MyBean {
private Date startDate;
private boolean enabled;
// empty constructor
public MyBean() {}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getStartDate() {
return this.startDate;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean getEnabled() {
return this.enabled;
}
}
public static class MyErrorBean {
private String property;
// empty constructor
public MyErrorBean() {}
public void setProperty(String property) {
this.property = property;
}
public String getProperty() {
return this.property;
}
}
/**
* 707.5 - Repeated or Deferred Conversions
* <p/>
* In certain situations the same conversion needs to be performed multiple
* times, on different source objects. Or maybe the conversion needs to be
* performed asynchronously as part of a async stream processing pipeline.
* For such cases the Converter can produce a Function, which will perform
* the conversion once applied. The function can be invoked multiple times
* with different source objects. The Converter can produce this function
* through the function() method, which provides an API similar to the
* convert(Object) method, with the difference that instead of returning the
* conversion, once to() is called, a Function that can perform the
* conversion on apply(T) is returned.
* <p/>
* The Function returned by the converter is thread safe and can be used
* concurrently or asynchronously in other threads.
*
* @throws Exception
*/
public void testRepeatedOrDeferredConversion() throws Exception {
Converter c = Converters.standardConverter();
Function<Object,Integer> cf = c.function().defaultValue(999).to(
Integer.class);
int i1 = cf.apply("123");
assertTrue(123 == i1);
int i2 = cf.apply("");
assertTrue(999 == i2);
}
/**
* 707.6 - Customizing converters
* <p/>
* The Standard Converter applies the conversion rules described in this
* specification. While this is useful for many applications, in some cases
* deviations from the specified rules may be necessary. This can be done by
* creating a customized converter. Customized converters are created based
* on an existing converter with additional rules specified that override
* the existing converter's behavior. A customized converter is created
* through a ConverterBuilder. Customized converters implement the converter
* interface and as such can be used to create further customized
* converters. Converters are immutable, once created they cannot be
* modified, so they can be freely shared without the risk of modification
* to the converter's behavior.
* <p/>
* For example converting a Date to a String may require a specific
* format.The default Date to String conversion produces a String in the
* format yyyy-MM-ddTHH:mm:ss.SSSZ. If we want to produce a String in the
* format yyMMddHHmmssZ instead a custom converter can be applied:
* <p/>
* Custom conversions are also applied to embedded conversions that are part
* of a map or other enclosing object
*
*/
public void testCustomizedConversion()
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
final AtomicInteger counter = new AtomicInteger(0);
ConverterBuilder cb = Converters.standardConverter()
.newConverterBuilder();
cb.rule(new TypeRule<Date,String>(Date.class, String.class,
new Function<Date,String>() {
@Override
public String apply(Date t) {
return sdf.format(t);
}
}) {});
cb.rule(new TypeRule<String,Date>(String.class, Date.class,
new Function<String,Date>() {
@Override
public Date apply(String t) {
try {
return sdf.parse(t);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}) {});
Converter c = cb.build();
String stringToBeConverted = "131224072100";
Date dateToBeConverted = new Date(Date.UTC(113, 11, 24, 6, 21, 0));
String stringConverted = c.convert(dateToBeConverted).to(String.class);
assertEquals(stringConverted,stringToBeConverted);
Date dateConverted = c.convert(stringToBeConverted).to(Date.class);
assertEquals(dateToBeConverted,dateConverted);
MyBean mb = new MyBean();
mb.setStartDate(dateToBeConverted);
mb.setEnabled(true);
String booleanConverted = "true";
Map<String, String> map = c.convert(mb).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
assertEquals(booleanConverted, map.get("enabled"));
assertEquals(stringConverted, map.get("startDate"));
}
/**
* 707.6 - Customizing converters
* <p/>
* [...]
* <p/>
* A converter rule can return CANNOT_HANDLE to indicate that it cannot
* handle the conversion, in which case next applicable rule is handed the
* conversion. If none of the registered rules for the current converter can
* handle the conversion, the parent converter object is asked to convert
* the value. Since custom converters can be the basis for further custom
* converters, a chain of custom converters can be created where a custom
* converter rule can either decide to handle the conversion, or it can
* delegate back to the next converter in the chain by returning
* CANNOT_HANDLE if it wishes to do so.
* <p/>
*
* 707.6.1 - Catch-all-rules
* <p/>
* It is also possible to register converter rules which are invoked for
* every conversion with the rule(ConverterFunction) method. When multiple
* rules are registered, they are evaluated in the order of registration,
* until a rule indicates that it can handle a conversion. A rule can indicate
* that it cannot handle the conversion by returning the CANNOT_HANDLE constant.
* Rules targeting specific types are evaluated before catch-all rules.
*/
public void testCustomizedChainConversion()
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
final String error = "MyErrorBean is not handled";
ConverterBuilder converterBuilder = Converters.newConverterBuilder();
Converter converter = converterBuilder.build();
ConverterBuilder parentConverterBuilder = converter.newConverterBuilder();
parentConverterBuilder.rule(new TypeRule<MappingBean,Map>(MappingBean.class, Map.class,
new Function<MappingBean,Map>() {
@Override
public Map apply(MappingBean t) {
Map<String,String> m = new HashMap<String,String>();
m.put("bean", t.toString());
m.put("prop1", t.getProp1());
m.put("prop2", t.getProp2());
m.put("prop3", t.getProp3());
m.put("embbeded", t.getEmbedded().toString());
return m;
}
}) {});
Converter parentConverter = parentConverterBuilder.build();
ConverterBuilder chilConverterBuilder = parentConverter.newConverterBuilder();
chilConverterBuilder.rule(new TypeRule<Date,String>(Date.class, String.class,
new Function<Date,String>() {
@Override
public String apply(Date t) {
return sdf.format(t);
}
}) {});
chilConverterBuilder.rule(new TypeRule<String,Date>(String.class, Date.class,
new Function<String,Date>() {
@Override
public Date apply(String t) {
try {
return sdf.parse(t);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}) {});
chilConverterBuilder.rule(new ConverterFunction() {
@Override
public Object apply(Object obj, Type targetType) throws Exception{
Class clazz = obj.getClass();
if(MappingBean.class.isAssignableFrom(clazz)){
System.out.println("Unhandled MappingBean");
}
if(MyErrorBean.class.isAssignableFrom(clazz)){
System.out.println("MyErrorBean triggers error");
throw new ConversionException(error);
}
return ConverterFunction.CANNOT_HANDLE;
}
});
Converter childConverter = chilConverterBuilder.build();
String stringToBeConverted = "131224072100";
Date dateToBeConverted = new Date(Date.UTC(113, 11, 24, 6, 21, 0));
String stringConverted = childConverter.convert(dateToBeConverted).to(String.class);
assertEquals(stringConverted,stringToBeConverted);
Date dateConverted = childConverter.convert(stringToBeConverted).to(Date.class);
assertEquals(dateToBeConverted,dateConverted);
MappingBean embbededBean = new MappingBean();
embbededBean.setEmbedded(new ExtObject());
embbededBean.setProp1("mappingBean_prop1");
embbededBean.setProp2("mappingBean_prop2");
embbededBean.setProp3("mappingBean_prop3");
Map map = childConverter.convert(embbededBean).to(Map.class);
assertEquals(embbededBean.toString(), map.get("bean"));
MyBean mb = new MyBean();
mb.setStartDate(dateToBeConverted);
mb.setEnabled(true);
map = childConverter.convert(mb).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
String booleanConverted = "true";
assertEquals(stringConverted, map.get("startDate"));
assertEquals(booleanConverted, map.get("enabled"));
MyErrorBean errorBean = new MyErrorBean();
errorBean.setProperty("simple_error");
try{
map = childConverter.convert(errorBean).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
fail("ConversionException expected");
} catch(ConversionException e)
{}
}
/**
* 707.7 - Conversion failures
* <p/>
* Not all conversions can be performed by the standard converter. It cannot convert
* text such as 'lorem ipsum' cannot into a <code>long</code> value. Or the number pi
* into a map. When a conversion fails, the converter will throw a
* org.osgi.util.converter.ConversionException.
* <p/>
* If meaningful conversions exist between types not supported by the standard converter,
* a customized converter can be used. Some applications require different behaviour for
* error scenarios. For example they can use an empty value such as 0 or "" instead of
* the exception, or they might require a different exception to be thrown.
* For these scenarios a custom error handler can be registered. The error handler is
* only invoked in cases where otherwise a <code>ConversionException</code> would be
* thrown. The error handler can return a different value instead or throw another exception.
* <p/>
* An error handler is registered by creating a custom converter and providing it with an error
* handler via the org.osgi.util.converter.ConverterBuilder.errorHandler(ConvertFunction) method.
* <p/>
* When multiple error handlers are registered for a given converter they are invoked in the order
* in which they were registered until an error handler either throws an exception or returns a
* value other than org.osgi.util.converter.ConverterFunction.CANNOT_HANDLE
*/
public void testErrorHandler()
{
final AtomicInteger countError = new AtomicInteger(0);
final String error = "handled error";
final Map FAILURE = new HashMap();
ConverterBuilder cb = Converters.newConverterBuilder();
cb.errorHandler(new ConverterFunction() {
@Override
@SuppressWarnings("unchecked")
public Object apply(Object obj, Type targetType) throws Exception
{
if(countError.get() == 0){
return ConverterFunction.CANNOT_HANDLE;
}
Class clazz = null;
try{
clazz = (Class) ((ParameterizedType) targetType).getRawType();
} catch(ClassCastException e) {
clazz = (Class) targetType;
}
if(Map.class.isAssignableFrom(clazz))
{
FAILURE.put("error", error);
return FAILURE;
}
return null;
}
});
cb.errorHandler(new ConverterFunction() {
@Override
public Object apply(Object obj, Type targetType) throws Exception
{
countError.incrementAndGet();
Class clazz = null;
try{
clazz = (Class) ((ParameterizedType) targetType).getRawType();
} catch(ClassCastException e) {
clazz = (Class) targetType;
}
throw new RuntimeException(error);
}
});
Converter c = cb.build();
Map m = null;
String tobeconverted = "to be converted";
try{
m = c.convert(tobeconverted).to(Map.class);
} catch(RuntimeException e){
assertEquals(error, e.getMessage());
m = c.convert(tobeconverted).to(Map.class);
assertNotNull(m);
assertEquals(error, m.get("error"));
}
}
}
| org.osgi.test.cases.converter/src/org/osgi/test/cases/converter/junit/CustomizedConversionComplianceTest.java | package org.osgi.test.cases.converter.junit;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.osgi.test.cases.converter.junit.ConversionComplianceTest.ExtObject;
import org.osgi.test.cases.converter.junit.MapInterfaceJavaBeansDTOAndAnnotationConversionComplianceTest.MappingBean;
import org.osgi.util.converter.ConversionException;
import org.osgi.util.converter.Converter;
import org.osgi.util.converter.ConverterBuilder;
import org.osgi.util.converter.ConverterFunction;
import org.osgi.util.converter.Converters;
import org.osgi.util.converter.TypeReference;
import org.osgi.util.converter.TypeRule;
import org.osgi.util.function.Function;
import junit.framework.TestCase;
public class CustomizedConversionComplianceTest extends TestCase {
public static class MyBean {
private Date startDate;
private boolean enabled;
// empty constructor
public MyBean() {}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getStartDate() {
return this.startDate;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean getEnabled() {
return this.enabled;
}
}
public static class MyErrorBean {
private String property;
// empty constructor
public MyErrorBean() {}
public void setProperty(String property) {
this.property = property;
}
public String getProperty() {
return this.property;
}
}
/**
* 707.5 - Repeated or Deferred Conversions
* <p/>
* In certain situations the same conversion needs to be performed multiple
* times, on different source objects. Or maybe the conversion needs to be
* performed asynchronously as part of a async stream processing pipeline.
* For such cases the Converter can produce a Function, which will perform
* the conversion once applied. The function can be invoked multiple times
* with different source objects. The Converter can produce this function
* through the function() method, which provides an API similar to the
* convert(Object) method, with the difference that instead of returning the
* conversion, once to() is called, a Function that can perform the
* conversion on apply(T) is returned.
* <p/>
* The Function returned by the converter is thread safe and can be used
* concurrently or asynchronously in other threads.
*
* @throws Exception
*/
public void testRepeatedOrDeferredConversion() throws Exception {
Converter c = Converters.standardConverter();
Function<Object,Integer> cf = c.function().defaultValue(999).to(
Integer.class);
int i1 = cf.apply("123");
assertTrue(123 == i1);
int i2 = cf.apply("");
assertTrue(999 == i2);
}
/**
* 707.6 - Customizing converters
* <p/>
* The Standard Converter applies the conversion rules described in this
* specification. While this is useful for many applications, in some cases
* deviations from the specified rules may be necessary. This can be done by
* creating a customized converter. Customized converters are created based
* on an existing converter with additional rules specified that override
* the existing converter's behavior. A customized converter is created
* through a ConverterBuilder. Customized converters implement the converter
* interface and as such can be used to create further customized
* converters. Converters are immutable, once created they cannot be
* modified, so they can be freely shared without the risk of modification
* to the converter's behavior.
* <p/>
* For example converting a Date to a String may require a specific
* format.The default Date to String conversion produces a String in the
* format yyyy-MM-ddTHH:mm:ss.SSSZ. If we want to produce a String in the
* format yyMMddHHmmssZ instead a custom converter can be applied:
* <p/>
* Custom conversions are also applied to embedded conversions that are part
* of a map or other enclosing object
*
*/
public void testCustomizedConversion()
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
final AtomicInteger counter = new AtomicInteger(0);
ConverterBuilder cb = Converters.standardConverter()
.newConverterBuilder();
cb.rule(new TypeRule<Date,String>(Date.class, String.class,
new Function<Date,String>() {
@Override
public String apply(Date t) {
return sdf.format(t);
}
}) {});
cb.rule(new TypeRule<String,Date>(String.class, Date.class,
new Function<String,Date>() {
@Override
public Date apply(String t) {
try {
return sdf.parse(t);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}) {});
Converter c = cb.build();
String stringToBeConverted = "131224072100";
Date dateToBeConverted = new Date(Date.UTC(113, 11, 24, 6, 21, 0));
String stringConverted = c.convert(dateToBeConverted).to(String.class);
assertEquals(stringConverted,stringToBeConverted);
Date dateConverted = c.convert(stringToBeConverted).to(Date.class);
assertEquals(dateToBeConverted,dateConverted);
MyBean mb = new MyBean();
mb.setStartDate(dateToBeConverted);
mb.setEnabled(true);
String booleanConverted = "true";
Map<String, String> map = c.convert(mb).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
assertEquals(booleanConverted, map.get("enabled"));
assertEquals(stringConverted, map.get("startDate"));
}
/**
* 707.6 - Customizing converters
* <p/>
* [...]
* <p/>
* A converter rule can return CANNOT_HANDLE to indicate that it cannot
* handle the conversion, in which case next applicable rule is handed the
* conversion. If none of the registered rules for the current converter can
* handle the conversion, the parent converter object is asked to convert
* the value. Since custom converters can be the basis for further custom
* converters, a chain of custom converters can be created where a custom
* converter rule can either decide to handle the conversion, or it can
* delegate back to the next converter in the chain by returning
* CANNOT_HANDLE if it wishes to do so.
*/
public void testCustomizedChainConversion()
{
final AtomicInteger countUnhandledMappingBean = new AtomicInteger(0);
final AtomicInteger countHandledMappingBean = new AtomicInteger(0);
final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
final String error = "MyErrorBean is not handled";
ConverterBuilder converterBuilder = Converters.newConverterBuilder();
Converter converter = converterBuilder.build();
ConverterBuilder parentConverterBuilder = converter.newConverterBuilder();
parentConverterBuilder.rule(new TypeRule<MappingBean,Map<String,String>>(MappingBean.class, Map.class,
new Function<MappingBean,Map<String,String>>() {
@Override
public Map<String,String> apply(MappingBean t) {
Map<String,String> m = new HashMap<String,String>();
m.put("MappingBean", t.toString());
m.put("prop1", t.getProp1());
m.put("prop2", t.getProp2());
m.put("prop3", t.getProp3());
m.put("embbeded", t.getEmbedded().toString());
countHandledMappingBean.incrementAndGet();
return m;
}
}) {});
Converter parentConverter = parentConverterBuilder.build();
ConverterBuilder chilConverterBuilder = parentConverter.newConverterBuilder();
chilConverterBuilder.rule(new TypeRule<Date,String>(Date.class, String.class,
new Function<Date,String>() {
@Override
public String apply(Date t) {
return sdf.format(t);
}
}) {});
chilConverterBuilder.rule(new TypeRule<String,Date>(String.class, Date.class,
new Function<String,Date>() {
@Override
public Date apply(String t) {
try {
return sdf.parse(t);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}) {});
chilConverterBuilder.rule(new ConverterFunction() {
@Override
public Object apply(Object obj, Type targetType) throws Exception{
Class clazz = obj.getClass();
if(MappingBean.class.isAssignableFrom(clazz)){
System.out.println("Unhandled MappingBean");
countUnhandledMappingBean.incrementAndGet();
}
if(MyErrorBean.class.isAssignableFrom(clazz)){
System.out.println("MyErrorBean trigger error");
throw new ConversionException(error);
}
return ConverterFunction.CANNOT_HANDLE;
}
});
Converter childConverter = chilConverterBuilder.build();
String stringToBeConverted = "131224072100";
Date dateToBeConverted = new Date(Date.UTC(113, 11, 24, 6, 21, 0));
String stringConverted = childConverter.convert(dateToBeConverted).to(String.class);
assertEquals(stringConverted,stringToBeConverted);
Date dateConverted = childConverter.convert(stringToBeConverted).to(Date.class);
assertEquals(dateToBeConverted,dateConverted);
MappingBean embbededBean = new MappingBean();
embbededBean.setEmbedded(new ExtObject());
embbededBean.setProp1("mappingBean_prop1");
embbededBean.setProp2("mappingBean_prop2");
embbededBean.setProp3("mappingBean_prop3");
Map<String,String> map = childConverter.convert(embbededBean).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
System.out.println(map);
MyBean mb = new MyBean();
mb.setStartDate(dateToBeConverted);
mb.setEnabled(true);
map = childConverter.convert(mb).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
String booleanConverted = "true";
assertEquals(stringConverted, map.get("startDate"));
assertEquals(booleanConverted, map.get("enabled"));
MyErrorBean errorBean = new MyErrorBean();
errorBean.setProperty("simple_error");
try{
map = childConverter.convert(errorBean).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
fail("ConversionException expected");
} catch(ConversionException e)
{}
}
/**
* 707.7 - Conversion failures
* <p/>
* Not all conversions can be performed by the standard converter. It cannot convert
* text such as 'lorem ipsum' cannot into a <code>long</code> value. Or the number pi
* into a map. When a conversion fails, the converter will throw a
* org.osgi.util.converter.ConversionException.
* <p/>
* If meaningful conversions exist between types not supported by the standard converter,
* a customized converter can be used. Some applications require different behaviour for
* error scenarios. For example they can use an empty value such as 0 or "" instead of
* the exception, or they might require a different exception to be thrown.
* For these scenarios a custom error handler can be registered. The error handler is
* only invoked in cases where otherwise a <code>ConversionException</code> would be
* thrown. The error handler can return a different value instead or throw another exception.
* <p/>
* An error handler is registered by creating a custom converter and providing it with an error
* handler via the org.osgi.util.converter.ConverterBuilder.errorHandler(ConvertFunction) method.
* <p/>
* When multiple error handlers are registered for a given converter they are invoked in the order
* in which they were registered until an error handler either throws an exception or returns a
* value other than org.osgi.util.converter.ConverterFunction.CANNOT_HANDLE
*/
public void testErrorHandler()
{
final AtomicInteger countError = new AtomicInteger(0);
final String error = "handled error";
final Map FAILURE = new HashMap();
ConverterBuilder cb = Converters.newConverterBuilder();
cb.errorHandler(new ConverterFunction() {
@Override
@SuppressWarnings("unchecked")
public Object apply(Object obj, Type targetType) throws Exception
{
if(countError.get() == 0){
return ConverterFunction.CANNOT_HANDLE;
}
Class clazz = null;
try{
clazz = (Class) ((ParameterizedType) targetType).getRawType();
} catch(ClassCastException e) {
clazz = (Class) targetType;
}
if(Map.class.isAssignableFrom(clazz))
{
FAILURE.put("error", error);
return FAILURE;
}
return null;
}
});
cb.errorHandler(new ConverterFunction() {
@Override
public Object apply(Object obj, Type targetType) throws Exception
{
countError.incrementAndGet();
Class clazz = null;
try{
clazz = (Class) ((ParameterizedType) targetType).getRawType();
} catch(ClassCastException e) {
clazz = (Class) targetType;
}
throw new RuntimeException(error);
}
});
Converter c = cb.build();
Map m = null;
String tobeconverted = "to be converted";
try{
m = c.convert(tobeconverted).to(Map.class);
} catch(RuntimeException e){
assertEquals(error, e.getMessage());
m = c.convert(tobeconverted).to(Map.class);
assertNotNull(m);
assertEquals(error, m.get("error"));
}
}
}
| update customized converter tests
| org.osgi.test.cases.converter/src/org/osgi/test/cases/converter/junit/CustomizedConversionComplianceTest.java | update customized converter tests | <ide><path>rg.osgi.test.cases.converter/src/org/osgi/test/cases/converter/junit/CustomizedConversionComplianceTest.java
<ide> import java.lang.reflect.Type;
<ide> import java.text.ParseException;
<ide> import java.text.SimpleDateFormat;
<del>import java.util.Arrays;
<ide> import java.util.Date;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> * converter rule can either decide to handle the conversion, or it can
<ide> * delegate back to the next converter in the chain by returning
<ide> * CANNOT_HANDLE if it wishes to do so.
<add> * <p/>
<add> *
<add> * 707.6.1 - Catch-all-rules
<add> * <p/>
<add> * It is also possible to register converter rules which are invoked for
<add> * every conversion with the rule(ConverterFunction) method. When multiple
<add> * rules are registered, they are evaluated in the order of registration,
<add> * until a rule indicates that it can handle a conversion. A rule can indicate
<add> * that it cannot handle the conversion by returning the CANNOT_HANDLE constant.
<add> * Rules targeting specific types are evaluated before catch-all rules.
<ide> */
<ide> public void testCustomizedChainConversion()
<ide> {
<del> final AtomicInteger countUnhandledMappingBean = new AtomicInteger(0);
<del> final AtomicInteger countHandledMappingBean = new AtomicInteger(0);
<del>
<ide> final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
<del>
<ide>
<ide> final String error = "MyErrorBean is not handled";
<ide> ConverterBuilder converterBuilder = Converters.newConverterBuilder();
<ide> Converter converter = converterBuilder.build();
<ide>
<ide> ConverterBuilder parentConverterBuilder = converter.newConverterBuilder();
<del> parentConverterBuilder.rule(new TypeRule<MappingBean,Map<String,String>>(MappingBean.class, Map.class,
<del> new Function<MappingBean,Map<String,String>>() {
<del> @Override
<del> public Map<String,String> apply(MappingBean t) {
<add> parentConverterBuilder.rule(new TypeRule<MappingBean,Map>(MappingBean.class, Map.class,
<add> new Function<MappingBean,Map>() {
<add> @Override
<add> public Map apply(MappingBean t) {
<ide>
<ide> Map<String,String> m = new HashMap<String,String>();
<del> m.put("MappingBean", t.toString());
<add> m.put("bean", t.toString());
<ide> m.put("prop1", t.getProp1());
<ide> m.put("prop2", t.getProp2());
<ide> m.put("prop3", t.getProp3());
<ide> m.put("embbeded", t.getEmbedded().toString());
<del> countHandledMappingBean.incrementAndGet();
<ide> return m;
<ide> }
<ide> }) {});
<ide> Class clazz = obj.getClass();
<ide> if(MappingBean.class.isAssignableFrom(clazz)){
<ide> System.out.println("Unhandled MappingBean");
<del> countUnhandledMappingBean.incrementAndGet();
<ide> }
<ide> if(MyErrorBean.class.isAssignableFrom(clazz)){
<del> System.out.println("MyErrorBean trigger error");
<add> System.out.println("MyErrorBean triggers error");
<ide> throw new ConversionException(error);
<ide> }
<ide> return ConverterFunction.CANNOT_HANDLE;
<ide> embbededBean.setProp2("mappingBean_prop2");
<ide> embbededBean.setProp3("mappingBean_prop3");
<ide>
<del> Map<String,String> map = childConverter.convert(embbededBean).sourceAsBean().to(new TypeReference<Map<String,String>>(){});
<del> System.out.println(map);
<add> Map map = childConverter.convert(embbededBean).to(Map.class);
<add> assertEquals(embbededBean.toString(), map.get("bean"));
<ide>
<ide> MyBean mb = new MyBean();
<ide> mb.setStartDate(dateToBeConverted); |
|
Java | apache-2.0 | 7ef24f52afabe3266164cb02bc5dd4431f700f7e | 0 | yangfuhai/jboot,yangfuhai/jboot | /**
* Copyright (c) 2015-2022, Michael Yang 杨福海 ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.web.controller;
import com.alibaba.fastjson.JSON;
import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderManager;
import io.jboot.support.jwt.JwtManager;
import io.jboot.utils.RequestUtil;
import io.jboot.utils.StrUtil;
import io.jboot.utils.TypeDef;
import io.jboot.web.json.JsonBodyParseInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class JbootController extends Controller {
private Object rawObject;
private Map jwtParas;
private Map<String, Object> jwtAttrs;
@Override
protected void _clear_() {
super._clear_();
this.rawObject = null;
this.jwtParas = null;
this.jwtAttrs = null;
}
/**
* 是否是手机浏览器
*
* @return
*/
@NotAction
public boolean isMobileBrowser() {
return RequestUtil.isMobileBrowser(getRequest());
}
/**
* 是否是微信浏览器
*
* @return
*/
@NotAction
public boolean isWechatBrowser() {
return RequestUtil.isWechatBrowser(getRequest());
}
/**
* 是否是IE浏览器
*
* @return
*/
@NotAction
public boolean isIEBrowser() {
return RequestUtil.isIEBrowser(getRequest());
}
/**
* 是否是ajax请求
*
* @return
*/
@NotAction
public boolean isAjaxRequest() {
return RequestUtil.isAjaxRequest(getRequest());
}
/**
* 是否是multpart的请求(带有文件上传的请求)
*
* @return
*/
@NotAction
public boolean isMultipartRequest() {
return RequestUtil.isMultipartRequest(getRequest());
}
/**
* 获取ip地址
*
* @return
*/
@NotAction
public String getIPAddress() {
return RequestUtil.getIpAddress(getRequest());
}
/**
* 获取 referer
*
* @return
*/
@NotAction
public String getReferer() {
return RequestUtil.getReferer(getRequest());
}
/**
* 获取ua
*
* @return
*/
@NotAction
public String getUserAgent() {
return RequestUtil.getUserAgent(getRequest());
}
@NotAction
public Controller setJwtAttr(String name, Object value) {
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
jwtAttrs.put(name, value);
return this;
}
@NotAction
public Controller setJwtMap(Map map) {
if (map == null) {
throw new NullPointerException("Jwt map is null");
}
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
jwtAttrs.putAll(map);
return this;
}
@NotAction
public Controller setJwtEmpty() {
jwtAttrs = new HashMap<>();
return this;
}
@NotAction
public <T> T getJwtAttr(String name) {
return jwtAttrs == null ? null : (T) jwtAttrs.get(name);
}
@NotAction
public Map<String, Object> getJwtAttrs() {
return jwtAttrs;
}
@NotAction
public <T> T getJwtPara(String name, Object defaultValue) {
T ret = getJwtPara(name);
return ret != null ? ret : (T) defaultValue;
}
@NotAction
public <T> T getJwtPara(String name) {
return (T) getJwtParas().get(name);
}
@NotAction
public Integer getJwtParaToInt(String name, Integer defaultValue) {
Integer ret = getJwtParaToInt(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public Integer getJwtParaToInt(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof Number) {
return ((Number) ret).intValue();
}
return ret != null ? Integer.valueOf(ret.toString()) : null;
}
@NotAction
public Long getJwtParaToLong(String name, Long defaultValue) {
Long ret = getJwtParaToLong(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public Long getJwtParaToLong(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof Number) {
return ((Number) ret).longValue();
}
return ret != null ? Long.valueOf(ret.toString()) : null;
}
@NotAction
public String getJwtParaToString(String name, String defaultValue) {
String ret = getJwtParaToString(name);
return StrUtil.isNotBlank(ret) ? ret : defaultValue;
}
@NotAction
public String getJwtParaToString(String name) {
Object ret = getJwtParas().get(name);
return ret != null ? ret.toString() : null;
}
@NotAction
public BigInteger getJwtParaToBigInteger(String name, BigInteger defaultValue) {
BigInteger ret = getJwtParaToBigInteger(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public BigInteger getJwtParaToBigInteger(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof BigInteger) {
return (BigInteger) ret;
} else if (ret instanceof Number) {
return BigInteger.valueOf(((Number) ret).longValue());
}
return ret != null ? toBigInteger(ret.toString(), null) : null;
}
@NotAction
public Map getJwtParas() {
if (jwtParas == null) {
jwtParas = JwtManager.me().parseJwtToken(this);
}
return jwtParas;
}
@NotAction
public String createJwtToken() {
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
return JwtManager.me().createJwtToken(jwtAttrs);
}
/**
* 获取当前网址
*
* @return
*/
@NotAction
public String getBaseUrl() {
return RequestUtil.getBaseUrl(getRequest());
}
@NotAction
public String getCurrentUrl() {
return RequestUtil.getCurrentUrl(getRequest());
}
/**
* 接收 Json 转化为 JsonObject 或者 JsonArray
*
* @return
*/
@NotAction
public <T> T getRawObject() {
if (rawObject == null && StrUtil.isNotBlank(getRawData())) {
rawObject = JSON.parse(getRawData());
}
return (T) rawObject;
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(Class<T> typeClass) {
return getRawObject(typeClass, null);
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(Class<T> typeClass, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getRawObject(), typeClass, typeClass, jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(TypeDef<T> typeDef) {
return getRawObject(typeDef, null);
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(TypeDef<T> typeDef, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getRawObject(), typeDef.getDefClass(), typeDef.getType(), jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 Json 转化为 JsonObject 或者 JsonArray
*
* @return
*/
@NotAction
public <T> T getJsonBody() {
if (rawObject == null && StrUtil.isNotBlank(getRawData())) {
rawObject = JSON.parse(getRawData());
}
return (T) rawObject;
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(Class<T> typeClass) {
return getJsonBody(typeClass, null);
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(Class<T> typeClass, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getJsonBody(), typeClass, typeClass, jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(TypeDef<T> typeDef) {
return getJsonBody(typeDef, null);
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(TypeDef<T> typeDef, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getJsonBody(), typeDef.getDefClass(), typeDef.getType(), jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* BeanGetter 会调用此方法生成 bean,在 Map List Array 下,JFinal
* 通过 Injector.injectBean 去实例化的时候会出错,从而无法实现通过 @JsonBody 对 map list array 的注入
*
* @param beanClass
* @param beanName
* @param skipConvertError
* @param <T>
* @return
*/
@NotAction
@Override
public <T> T getBean(Class<T> beanClass, String beanName, boolean skipConvertError) {
if (Collection.class.isAssignableFrom(beanClass)
|| Map.class.isAssignableFrom(beanClass)
|| beanClass.isArray()) {
return null;
} else {
return super.getBean(beanClass, beanName, skipConvertError);
}
}
@NotAction
public Map<String, String> getParas() {
Map<String, String> map = null;
Enumeration<String> names = getParaNames();
if (names != null) {
map = new HashMap<>();
while (names.hasMoreElements()) {
String name = names.nextElement();
map.put(name, getPara(name));
}
}
return map;
}
@NotAction
public String getTrimPara(String name) {
String value = super.getPara(name);
value = (value == null ? null : value.trim());
return "".equals(value) ? null : value;
}
@NotAction
public String getTrimPara(int index) {
String value = super.getPara(index);
value = (value == null ? null : value.trim());
return "".equals(value) ? null : value;
}
@NotAction
public String getEscapePara(String name) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return null;
}
return StrUtil.escapeHtml(value);
}
@NotAction
public String getEscapePara(String name, String defaultValue) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return defaultValue;
}
return StrUtil.escapeHtml(value);
}
@NotAction
public String getUnescapePara(String name) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return null;
}
return StrUtil.unEscapeHtml(value);
}
@NotAction
public String getUnescapePara(String name, String defaultValue) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return defaultValue;
}
return StrUtil.unEscapeHtml(value);
}
@NotAction
public String getOriginalPara(String name) {
String value = getOrginalRequest().getParameter(name);
if (value == null || value.length() == 0) {
return null;
}
return value;
}
@NotAction
public HttpServletRequest getOrginalRequest() {
HttpServletRequest req = getRequest();
if (req instanceof HttpServletRequestWrapper) {
req = getOrginalRequest((HttpServletRequestWrapper) req);
}
return req;
}
private HttpServletRequest getOrginalRequest(HttpServletRequestWrapper wrapper) {
HttpServletRequest req = (HttpServletRequest) wrapper.getRequest();
if (req instanceof HttpServletRequestWrapper) {
return getOrginalRequest((HttpServletRequestWrapper) req);
}
return req;
}
@NotAction
public String getOriginalPara(String name, String defaultValue) {
String value = getOriginalPara(name);
return value != null ? value : defaultValue;
}
private BigInteger toBigInteger(String value, BigInteger defaultValue) {
try {
if (StrKit.isBlank(value)) {
return defaultValue;
}
value = value.trim();
if (value.startsWith("N") || value.startsWith("n")) {
return BigInteger.ZERO.subtract(new BigInteger(value.substring(1)));
}
return new BigInteger(value);
} catch (Exception e) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), "Can not parse the parameter \"" + value + "\" to BigInteger value.");
}
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger() {
return toBigInteger(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger(String name) {
return toBigInteger(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger(String name, BigInteger defaultValue) {
return toBigInteger(getTrimPara(name), defaultValue);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger() {
return toBigInteger(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger(String name) {
return toBigInteger(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger(String name, BigInteger defaultValue) {
return toBigInteger(getTrimPara(name), defaultValue);
}
private BigDecimal toBigDecimal(String value, BigDecimal defaultValue) {
try {
if (StrKit.isBlank(value)) {
return defaultValue;
}
value = value.trim();
if (value.startsWith("N") || value.startsWith("n")) {
return BigDecimal.ZERO.subtract(new BigDecimal(value.substring(1)));
}
return new BigDecimal(value);
} catch (Exception e) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), "Can not parse the parameter \"" + value + "\" to BigDecimal value.");
}
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal() {
return toBigDecimal(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal(String name) {
return toBigDecimal(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal(String name, BigDecimal defaultValue) {
return toBigDecimal(getTrimPara(name), defaultValue);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal() {
return toBigDecimal(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal(String name) {
return toBigDecimal(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
return toBigDecimal(getTrimPara(name), defaultValue);
}
/**
* 获取所有 attr 信息
*
* @return attrs map
*/
@NotAction
public Map<String, Object> getAttrs() {
Map<String, Object> attrs = new HashMap<>();
for (Enumeration<String> names = getAttrNames(); names.hasMoreElements(); ) {
String attrName = names.nextElement();
attrs.put(attrName, getAttr(attrName));
}
return attrs;
}
}
| src/main/java/io/jboot/web/controller/JbootController.java | /**
* Copyright (c) 2015-2022, Michael Yang 杨福海 ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.web.controller;
import com.alibaba.fastjson.JSON;
import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderManager;
import io.jboot.support.jwt.JwtManager;
import io.jboot.utils.RequestUtil;
import io.jboot.utils.StrUtil;
import io.jboot.utils.TypeDef;
import io.jboot.web.json.JsonBodyParseInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class JbootController extends Controller {
private Object rawObject;
private Map jwtParas;
private Map<String, Object> jwtAttrs;
@Override
protected void _clear_() {
super._clear_();
this.rawObject = null;
this.jwtParas = null;
this.jwtAttrs = null;
}
/**
* 是否是手机浏览器
*
* @return
*/
@NotAction
public boolean isMobileBrowser() {
return RequestUtil.isMobileBrowser(getRequest());
}
/**
* 是否是微信浏览器
*
* @return
*/
@NotAction
public boolean isWechatBrowser() {
return RequestUtil.isWechatBrowser(getRequest());
}
/**
* 是否是IE浏览器
*
* @return
*/
@NotAction
public boolean isIEBrowser() {
return RequestUtil.isIEBrowser(getRequest());
}
/**
* 是否是ajax请求
*
* @return
*/
@NotAction
public boolean isAjaxRequest() {
return RequestUtil.isAjaxRequest(getRequest());
}
/**
* 是否是multpart的请求(带有文件上传的请求)
*
* @return
*/
@NotAction
public boolean isMultipartRequest() {
return RequestUtil.isMultipartRequest(getRequest());
}
/**
* 获取ip地址
*
* @return
*/
@NotAction
public String getIPAddress() {
return RequestUtil.getIpAddress(getRequest());
}
/**
* 获取 referer
*
* @return
*/
@NotAction
public String getReferer() {
return RequestUtil.getReferer(getRequest());
}
/**
* 获取ua
*
* @return
*/
@NotAction
public String getUserAgent() {
return RequestUtil.getUserAgent(getRequest());
}
@NotAction
public Controller setJwtAttr(String name, Object value) {
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
jwtAttrs.put(name, value);
return this;
}
@NotAction
public Controller setJwtMap(Map map) {
if (map == null) {
throw new NullPointerException("Jwt map is null");
}
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
jwtAttrs.putAll(map);
return this;
}
@NotAction
public Controller setJwtEmpty() {
jwtAttrs = new HashMap<>();
return this;
}
@NotAction
public <T> T getJwtAttr(String name) {
return jwtAttrs == null ? null : (T) jwtAttrs.get(name);
}
@NotAction
public Map<String, Object> getJwtAttrs() {
return jwtAttrs;
}
@NotAction
public <T> T getJwtPara(String name, Object defaultValue) {
T ret = getJwtPara(name);
return ret != null ? ret : (T) defaultValue;
}
@NotAction
public <T> T getJwtPara(String name) {
return (T) getJwtParas().get(name);
}
@NotAction
public Integer getJwtParaToInt(String name, Integer defaultValue) {
Integer ret = getJwtParaToInt(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public Integer getJwtParaToInt(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof Number) {
return ((Number) ret).intValue();
}
return ret != null ? Integer.valueOf(ret.toString()) : null;
}
@NotAction
public Long getJwtParaToLong(String name, Long defaultValue) {
Long ret = getJwtParaToLong(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public Long getJwtParaToLong(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof Number) {
return ((Number) ret).longValue();
}
return ret != null ? Long.valueOf(ret.toString()) : null;
}
@NotAction
public String getJwtParaToString(String name, String defaultValue) {
String ret = getJwtParaToString(name);
return StrUtil.isNotBlank(ret) ? ret : defaultValue;
}
@NotAction
public String getJwtParaToString(String name) {
Object ret = getJwtParas().get(name);
return ret != null ? ret.toString() : null;
}
@NotAction
public BigInteger getJwtParaToBigInteger(String name, BigInteger defaultValue) {
BigInteger ret = getJwtParaToBigInteger(name);
return ret != null ? ret : defaultValue;
}
@NotAction
public BigInteger getJwtParaToBigInteger(String name) {
Object ret = getJwtParas().get(name);
if (ret instanceof BigInteger) {
return (BigInteger) ret;
} else if (ret instanceof Number) {
return BigInteger.valueOf(((Number) ret).longValue());
}
return ret != null ? toBigInteger(ret.toString(), null) : null;
}
@NotAction
public Map getJwtParas() {
if (jwtParas == null) {
jwtParas = JwtManager.me().parseJwtToken(this);
}
return jwtParas;
}
@NotAction
public String createJwtToken() {
if (jwtAttrs == null) {
jwtAttrs = new HashMap<>();
}
return JwtManager.me().createJwtToken(jwtAttrs);
}
/**
* 获取当前网址
*
* @return
*/
@NotAction
public String getBaseUrl() {
return RequestUtil.getBaseUrl(getRequest());
}
@NotAction
public String getCurrentUrl() {
return RequestUtil.getCurrentUrl(getRequest());
}
/**
* 接收 Json 转化为 JsonObject 或者 JsonArray
*
* @return
*/
@NotAction
public <T> T getRawObject() {
if (rawObject == null && StrUtil.isNotBlank(getRawData())) {
rawObject = JSON.parse(getRawData());
}
return (T) rawObject;
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(Class<T> typeClass) {
return getRawObject(typeClass, null);
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(Class<T> typeClass, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getRawObject(), typeClass, typeClass, jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(TypeDef<T> typeDef) {
return getRawObject(typeDef, null);
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getRawObject(TypeDef<T> typeDef, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getRawObject(), typeDef.getDefClass(), typeDef.getType(), jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 Json 转化为 JsonObject 或者 JsonArray
*
* @return
*/
@NotAction
public <T> T getJsonBody() {
if (rawObject == null && StrUtil.isNotBlank(getRawData())) {
rawObject = JSON.parse(getRawData());
}
return (T) rawObject;
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(Class<T> typeClass) {
return getJsonBody(typeClass, null);
}
/**
* 接收 json 转化为 object
*
* @param typeClass
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(Class<T> typeClass, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getJsonBody(), typeClass, typeClass, jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(TypeDef<T> typeDef) {
return getJsonBody(typeDef, null);
}
/**
* 接收 json 转化为 object
*
* @param typeDef 泛型的定义类
* @param jsonKey
* @param <T>
* @return
*/
@NotAction
public <T> T getJsonBody(TypeDef<T> typeDef, String jsonKey) {
try {
return (T) JsonBodyParseInterceptor.parseJsonBody(getJsonBody(), typeDef.getDefClass(), typeDef.getType(), jsonKey);
} catch (Exception ex) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), ex.getMessage());
}
}
/**
* BeanGetter 会调用此方法生成 bean,在 Map List Array 下,JFinal
* 通过 Injector.injectBean 去实例化的时候会出错,从而无法实现通过 @JsonBody 对 map list array 的注入
*
* @param beanClass
* @param beanName
* @param skipConvertError
* @param <T>
* @return
*/
@NotAction
@Override
public <T> T getBean(Class<T> beanClass, String beanName, boolean skipConvertError) {
if (Collection.class.isAssignableFrom(beanClass)
|| Map.class.isAssignableFrom(beanClass)
|| beanClass.isArray()) {
return null;
} else {
return super.getBean(beanClass, beanName, skipConvertError);
}
}
@NotAction
public Map<String, String> getParas() {
Map<String, String> map = null;
Enumeration<String> names = getParaNames();
if (names != null) {
map = new HashMap<>();
while (names.hasMoreElements()) {
String name = names.nextElement();
map.put(name, getPara(name));
}
}
return map;
}
@NotAction
public String getTrimPara(String name) {
String value = super.getPara(name);
value = (value == null ? null : value.trim());
return "".equals(value) ? null : value;
}
@NotAction
public String getTrimPara(int index) {
String value = super.getPara(index);
value = (value == null ? null : value.trim());
return "".equals(value) ? null : value;
}
@NotAction
public String getEscapePara(String name) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return null;
}
return StrUtil.escapeHtml(value);
}
@NotAction
public String getEscapePara(String name, String defaultValue) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return defaultValue;
}
return StrUtil.escapeHtml(value);
}
@NotAction
public String getUnescapePara(String name) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return null;
}
return StrUtil.unEscapeHtml(value);
}
@NotAction
public String getUnescapePara(String name, String defaultValue) {
String value = getTrimPara(name);
if (value == null || value.length() == 0) {
return defaultValue;
}
return StrUtil.unEscapeHtml(value);
}
@NotAction
public String getOriginalPara(String name) {
String value = getOrginalRequest().getParameter(name);
if (value == null || value.length() == 0) {
return null;
}
return value;
}
@NotAction
public HttpServletRequest getOrginalRequest() {
HttpServletRequest req = getRequest();
if (req instanceof HttpServletRequestWrapper) {
req = getOrginalRequest((HttpServletRequestWrapper) req);
}
return req;
}
private HttpServletRequest getOrginalRequest(HttpServletRequestWrapper wrapper) {
HttpServletRequest req = (HttpServletRequest) wrapper.getRequest();
if (req instanceof HttpServletRequestWrapper) {
return getOrginalRequest((HttpServletRequestWrapper) req);
}
return req;
}
@NotAction
public String getOriginalPara(String name, String defaultValue) {
String value = getOriginalPara(name);
return value != null ? value : defaultValue;
}
private BigInteger toBigInteger(String value, BigInteger defaultValue) {
try {
if (StrKit.isBlank(value)) {
return defaultValue;
}
value = value.trim();
if (value.startsWith("N") || value.startsWith("n")) {
return BigInteger.ZERO.subtract(new BigInteger(value.substring(1)));
}
return new BigInteger(value);
} catch (Exception e) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), "Can not parse the parameter \"" + value + "\" to BigInteger value.");
}
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger() {
return toBigInteger(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger(String name) {
return toBigInteger(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getParaToBigInteger(String name, BigInteger defaultValue) {
return toBigInteger(getTrimPara(name), defaultValue);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger() {
return toBigInteger(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger(String name) {
return toBigInteger(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigInteger representing the single value of the parameter
*/
@NotAction
public BigInteger getBigInteger(String name, BigInteger defaultValue) {
return toBigInteger(getTrimPara(name), defaultValue);
}
private BigDecimal toBigDecimal(String value, BigDecimal defaultValue) {
try {
if (StrKit.isBlank(value)) {
return defaultValue;
}
value = value.trim();
if (value.startsWith("N") || value.startsWith("n")) {
return BigDecimal.ZERO.subtract(new BigDecimal(value.substring(1)));
}
return new BigDecimal(value);
} catch (Exception e) {
throw new ActionException(400, RenderManager.me().getRenderFactory().getErrorRender(400), "Can not parse the parameter \"" + value + "\" to BigDecimal value.");
}
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal() {
return toBigDecimal(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal(String name) {
return toBigDecimal(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getParaToBigDecimal(String name, BigDecimal defaultValue) {
return toBigDecimal(getTrimPara(name), defaultValue);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal() {
return toBigDecimal(getPara(), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal(String name) {
return toBigDecimal(getTrimPara(name), null);
}
/**
* Returns the value of a request parameter and convert to BigDecimal with a default value if it is null.
*
* @param name a String specifying the name of the parameter
* @return a BigDecimal representing the single value of the parameter
*/
@NotAction
public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
return toBigDecimal(getTrimPara(name), defaultValue);
}
}
| add JbootController.getAttrs() method
| src/main/java/io/jboot/web/controller/JbootController.java | add JbootController.getAttrs() method | <ide><path>rc/main/java/io/jboot/web/controller/JbootController.java
<ide> public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
<ide> return toBigDecimal(getTrimPara(name), defaultValue);
<ide> }
<add>
<add>
<add> /**
<add> * 获取所有 attr 信息
<add> *
<add> * @return attrs map
<add> */
<add> @NotAction
<add> public Map<String, Object> getAttrs() {
<add> Map<String, Object> attrs = new HashMap<>();
<add> for (Enumeration<String> names = getAttrNames(); names.hasMoreElements(); ) {
<add> String attrName = names.nextElement();
<add> attrs.put(attrName, getAttr(attrName));
<add> }
<add> return attrs;
<add> }
<ide> } |
|
Java | lgpl-2.1 | cac514b9fcde27eba77d68aeec24dda518b259d0 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.util.stream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.util.Arrays;
import java.util.zip.Checksum;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.util.Utils;
import net.jpountz.xxhash.XXHashFactory;
import org.jetel.util.LZ4Provider;
import org.jetel.util.bytes.CloverBuffer;
public class CloverDataStream {
enum DataBlockType {
RAW_DATA('D'), COMPRESSED('C'), ENCRYPTED('E'), ENCRYPTED_COMPRESSED('F'), INDEX('I'), INVALID(' ');
private byte id;
DataBlockType(int id) {
this.id = (byte) id;
}
public byte getId() {
return id;
}
public static final DataBlockType get(byte value) {
switch (value) {
case 'D':
return RAW_DATA;
case 'C':
return COMPRESSED;
case 'E':
return ENCRYPTED;
case 'F':
return ENCRYPTED_COMPRESSED;
case 'I':
return INDEX;
default:
return INVALID;
}
}
}
static abstract class Compressor {
abstract int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset);
abstract int maxCompressedLength(int sourceLength);
}
static abstract class Decompressor {
abstract int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength);
}
public static class CompressorLZ4 extends Compressor{
private final LZ4Compressor compressor;
private CompressorLZ4(LZ4Compressor compressor) {
this.compressor = compressor;
}
public CompressorLZ4() {
this(LZ4Provider.fastestInstance().fastCompressor());
}
public static final CompressorLZ4 getHighCompressor() {
return new CompressorLZ4(LZ4Provider.fastestInstance().highCompressor());
}
@Override
final int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset) {
return compressor.compress(source, sourceOffset, length, target, targetOffset);
}
@Override
final int maxCompressedLength(int sourceLength){
return compressor.maxCompressedLength(sourceLength);
}
}
public static class DecompressorLZ4 extends Decompressor{
private final LZ4FastDecompressor decompressor;
public DecompressorLZ4() {
this.decompressor = LZ4Provider.fastestInstance().fastDecompressor();
}
@Override
final int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength) {
return decompressor.decompress(source, sourceOffset, target, targetOffset, rawDataLength);
}
}
public static class CompressorGZIP extends Compressor {
private Deflater compressor;
public CompressorGZIP(){
this.compressor= new Deflater();
}
@Override
final int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset) {
compressor.setInput(source, sourceOffset, length);
compressor.finish();
int size = compressor.deflate(target, targetOffset, target.length-targetOffset);
if (!compressor.finished()){
size=-1; // problem - we need bigger target buffer
}
compressor.reset();
return size;
}
@Override
final int maxCompressedLength(int sourceLength){
return sourceLength +
((sourceLength + 7) >> 3) + ((sourceLength + 63) >> 6) + 5;
}
}
public static class DecompressorGZIP extends Decompressor {
private Inflater decompressor;
public DecompressorGZIP(){
this.decompressor = new Inflater();
}
@Override
final int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength) {
decompressor.setInput(source, sourceOffset, sourceLength );
int size;
try {
size = decompressor.inflate(target, targetOffset, rawDataLength);
if (!decompressor.finished()){
size= -1; // problem
}
} catch (DataFormatException e) {
size= -1;
}finally{
decompressor.reset();
}
return size;
}
}
/**
* the minimum compression ratio to go with compressed instead of full bytes
* if block of data after compressions is still quite large compared to full set, we store the full set to save time when reading
*/
public static final double MIN_COMPRESS_RATIO = 0.85;
/**
* number of rounds when compression ratio is lower than threshold before we switch to uncompressed mode.
* if we get often bad results (low compression) then we switch directly to uncompressed mode to save time during write
*/
static final int NO_TEST_ROUNDS = 4;
/**
* This is the identification of Clover data block
*/
static final byte[] CLOVER_BLOCK_MAGIC = new byte[] { 'C', 'L', 'V' };
static final int CLOVER_BLOCK_MAGIC_LENGTH = CLOVER_BLOCK_MAGIC.length;
static final int CLOVER_BLOCK_HEADER_LENGTH =
CLOVER_BLOCK_MAGIC_LENGTH + 1 // token (what type of bloc - compressed/raw/etcc.. - see DataBlockType
+ 4 // compressed length
+ 4 // full length
+ 4 // checksum
+ 4; // position of the first record in block
private final static int LONG_SIZE_BYTES = 8;
static final int DEFAULT_BLOCK_INDEX_SIZE = 128;
static final ByteOrder BUFFER_BYTE_ORDER = ByteOrder.BIG_ENDIAN;
public final static int findNearestPow2(int size) {
int value = 1;
while (value < size) {
value <<= 1;
}
return value;
}
public final static boolean testBlockHeader(CloverBuffer buffer) {
return testBlockHeader(buffer.array(), 0);
}
public final static boolean testBlockHeader(ByteBuffer buffer) {
return testBlockHeader(buffer.array(), 0);
}
public final static boolean testBlockHeader(ByteBuffer buffer, DataBlockType type) {
if (testBlockHeader(buffer.array(), 0) && buffer.get(CloverDataStream.CLOVER_BLOCK_MAGIC_LENGTH) == type.getId())
return true;
else
return false;
}
public final static boolean testBlockHeader(byte[] data, int offset) {
if (data[offset] == CLOVER_BLOCK_MAGIC[0] && data[offset + 1] == CLOVER_BLOCK_MAGIC[1] && data[offset + 2] == CLOVER_BLOCK_MAGIC[2]) {
return true;
} else {
return false;
}
}
public static final class Output extends FilterOutputStream {
/**
*
*/
public static final int DEFAULT_BLOCK_SIZE = 1 << 17; //131072 bytes
static final int COMPRESSION_LEVEL_BASE = 10;
static final int MIN_BLOCK_SIZE = 64;
static final int MAX_BLOCK_SIZE = 1 << (COMPRESSION_LEVEL_BASE + 0x0F);
static final int DEFAULT_SEED = 0x9747b28c;
private final Compressor compressor;
private final Checksum checksum;
private final CloverBuffer buffer;
private final CloverBuffer compressedBuffer;
private long[] blocksIndex;
private final boolean syncFlush;
private boolean finished;
private boolean compress;
private long position;
private int firstRecordPosition;
private int testRound;
/**
* Create a new {@link OutputStream} with configurable block size. Large blocks require more memory at
* compression and decompression time but should improve the compression ratio.
*
* @param out
* the {@link OutputStream} to feed
* @param blockSize
* the maximum number of bytes to try to compress at once, must be >= 64 and <= 32 M
* @param compressor
* the {@link LZ4Compressor} instance to use to compress data
* @param checksum
* the {@link Checksum} instance to use to check data for integrity.
* @param syncFlush
* true if pending data should also be flushed on {@link #flush()}
*/
public Output(OutputStream out, int blockSize, int blockIndexSize, Compressor compressor, Checksum checksum,
boolean syncFlush) {
super(out);
this.compressor = compressor;
this.checksum = checksum;
this.buffer = CloverBuffer.wrap(new byte[blockSize]);
this.buffer.order(BUFFER_BYTE_ORDER);
this.buffer.setRecapacityAllowed(false);
final int compressedBlockSize = CLOVER_BLOCK_HEADER_LENGTH + compressor.maxCompressedLength(blockSize);
this.compressedBuffer = CloverBuffer.wrap(new byte[compressedBlockSize]);
this.compressedBuffer.order(BUFFER_BYTE_ORDER);
this.compressedBuffer.setRecapacityAllowed(false);
this.syncFlush = syncFlush;
finished = false;
compressedBuffer.put(CLOVER_BLOCK_MAGIC);
this.position = 0;
this.firstRecordPosition = -1;
this.blocksIndex = blockIndexSize > DEFAULT_BLOCK_INDEX_SIZE ? new long[((blockIndexSize >> 1) << 1)] : new long[DEFAULT_BLOCK_INDEX_SIZE];
this.compress = false; // no compression by default
this.testRound=0;
}
/**
* Create a new instance which checks stream integrity using {@link StreamingXXHash32} and doesn't sync flush.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor, Checksum, boolean)
* @see StreamingXXHash32#asChecksum()
*/
public Output(OutputStream out, int blockSize, Compressor compressor) {
this(out, blockSize, DEFAULT_BLOCK_INDEX_SIZE, compressor, XXHashFactory.fastestInstance().newStreamingHash32(DEFAULT_SEED).asChecksum(), false);
}
/**
* Create a new instance which compresses with the standard LZ4 compression algorithm.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor)
* @see LZ4Factory#fastCompressor()
*/
public Output(OutputStream out, int blockSize) {
this(out, blockSize, new CompressorLZ4());
}
/**
* Create a new instance which compresses into blocks of DEFAULT_BLOCK_SIZE KB.
*
* @see #LZ4BlockOutputStream(OutputStream, int)
*/
public Output(OutputStream out) {
this(out, DEFAULT_BLOCK_SIZE);
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
public boolean isCompress() {
return compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
private final void ensureNotFinished() {
if (finished) {
throw new IllegalStateException("This stream is already closed");
}
}
@Override
public void write(int b) throws IOException {
ensureNotFinished();
if (!buffer.hasRemaining()) {
flushBufferedData();
}
buffer.put((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
//Utils.checkRange(b, off, len);
ensureNotFinished();
while (buffer.remaining() < len) {
final int l = buffer.remaining();
buffer.put(b, off, l);
flushBufferedData();
off += l;
len -= l;
}
buffer.put(b, off, len);
}
public void write(CloverBuffer inbuffer) throws IOException {
ensureNotFinished();
while (buffer.remaining() < inbuffer.remaining()) {
final int savelimit = inbuffer.limit();
inbuffer.limit(inbuffer.position() + buffer.remaining());
buffer.put(inbuffer);
inbuffer.limit(savelimit);
flushBufferedData();
}
buffer.put(inbuffer);
}
public void write(ByteBuffer inbuffer) throws IOException {
ensureNotFinished();
while (buffer.remaining() < inbuffer.remaining()) {
final int savelimit = inbuffer.limit();
inbuffer.limit(inbuffer.position() + buffer.remaining());
buffer.put(inbuffer);
inbuffer.limit(savelimit);
flushBufferedData();
}
buffer.put(inbuffer);
}
@Override
public void write(byte[] b) throws IOException {
ensureNotFinished();
write(b, 0, b.length);
}
public final void markRecordStart(){
if (firstRecordPosition < 0)
firstRecordPosition = buffer.position();
}
@Override
public void close() throws IOException {
if (out != null) {
finish();
out.close();
out = null;
}
}
private void flushBufferedData() throws IOException {
if (buffer.position() == 0)
return;
// store index of new block which will be added (but only if it contains beginning of record
if (firstRecordPosition >= 0)
storeBlockIndex();
buffer.flip();
final int rawlength = buffer.remaining();
if (compress) {
compressedBuffer.clear();
final int compressedLength = compressor.compress(buffer.array(), 0, rawlength, compressedBuffer.array(), CLOVER_BLOCK_HEADER_LENGTH);
if (compressedLength==-1){
throw new IOException("Error when compressing datablock.");
}
double ratio=((double)compressedLength)/rawlength;
//DEBUG
//System.err.println("compress ratio= "+ratio);
if (ratio > MIN_COMPRESS_RATIO){
if ((testRound++)>NO_TEST_ROUNDS){
compress=false; // we are forcing switch off of compression
}
}
if (compressedLength < rawlength) {
fillBlockHeader(compressedBuffer,DataBlockType.COMPRESSED,compressedLength,rawlength,0,firstRecordPosition);
// write header+data
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH + compressedLength);
position += CLOVER_BLOCK_HEADER_LENGTH + compressedLength;
buffer.clear();
firstRecordPosition = -1; // reset
return;
}
}
fillBlockHeader(compressedBuffer,DataBlockType.RAW_DATA,rawlength,rawlength,0,firstRecordPosition);
// write header
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
// write data
out.write(buffer.array(), 0, rawlength);
position += CLOVER_BLOCK_HEADER_LENGTH + rawlength;
buffer.clear();
firstRecordPosition = -1; // reset
}
private final void fillBlockHeader(CloverBuffer buffer,DataBlockType type,int rawLength,int compressedLength,int checksum,int firstRecPos){
buffer.position(0).put(CLOVER_BLOCK_MAGIC);
buffer.put(type.getId());
buffer.putInt(compressedLength);
buffer.putInt(rawLength);
buffer.putInt(checksum);
buffer.putInt(firstRecPos);
}
/**
* Flush this compressed {@link OutputStream}.
*
* If the stream has been created with <code>syncFlush=true</code>, pending data will be compressed and appended
* to the underlying {@link OutputStream} before calling {@link OutputStream#flush()} on the underlying stream.
* Otherwise, this method just flushes the underlying stream, so pending data might not be available for reading
* until {@link #finish()} or {@link #close()} is called.
*/
@Override
public void flush() throws IOException {
if (syncFlush) {
flushBufferedData();
}
out.flush();
}
/**
* Same as {@link #close()} except that it doesn't close the underlying stream. This can be useful if you want
* to keep on using the underlying stream.
*/
public void finish() throws IOException {
if (!finished) {
writeIndexData(); // this also marks the end of data
finished = true;
}
out.flush();
}
/**
* Writes INDEX block to the stream. This block should be very last. It contains index of all/most previous data
* (raw & compressed) blocks. The header is written twice - as the first & very last set of bytes of this block
* - so it can be read from the end of the data stream. The size of the index may vary.
*
* @throws IOException
*/
public void writeIndexData() throws IOException {
ensureNotFinished();
flushBufferedData();
try {
for (long value : blocksIndex) {
if (value > 0) {
buffer.putLong(value);
}
}
} catch (BufferOverflowException ex) {
throw new IOException("Can't store index data - internal buffer too small");
}
buffer.flip();
final int size = buffer.remaining();
checksum.reset();
checksum.update(buffer.array(), 0, size);
final int check = (int) checksum.getValue();
fillBlockHeader(compressedBuffer, DataBlockType.INDEX,size+CLOVER_BLOCK_HEADER_LENGTH, size+CLOVER_BLOCK_HEADER_LENGTH, check, 0);
position += CLOVER_BLOCK_HEADER_LENGTH + buffer.remaining();
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
out.write(buffer.array(), 0, buffer.remaining());
// write the header at the end again so it can be easily read from back
// the size this time does not contain the block HEADER length
compressedBuffer.putInt(CLOVER_BLOCK_MAGIC_LENGTH + 1, size);
compressedBuffer.putInt(CLOVER_BLOCK_MAGIC_LENGTH + 5, size);
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
out.flush();
}
private final void storeBlockIndex() throws IOException {
if (blocksIndex.length > 0) {
if (!addBlockIndex(position)) {
compactBlockIndex();
if (!addBlockIndex(position)) {
throw new IOException("Can't store position in index - no space left");
}
}
}
}
private final boolean addBlockIndex(long position) {
for (int i = 0; i < blocksIndex.length; i++) {
if (blocksIndex[i] == 0) {
blocksIndex[i] = position;
return true;
}
}
return false;
}
private final void compactBlockIndex() {
for (int i = 1; i < blocksIndex.length; i += 2) {
blocksIndex[i >> 1] = blocksIndex[i];
blocksIndex[i] = 0;
}
}
/**
* Seeks the channel to position where appending data can start.
* It first reads the stored index in existing file (if index present) and
* then positions the channel so appended data rewrites the index.
*
* @param channel
* @throws IOException
*/
public void seekToAppend(SeekableByteChannel channel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(CLOVER_BLOCK_HEADER_LENGTH);
channel.position(channel.size() - CLOVER_BLOCK_HEADER_LENGTH);
readFully(channel, buffer);
buffer.flip();
// test that it is our Index block
if (testBlockHeader(buffer, DataBlockType.INDEX)) {
int size = buffer.getInt(CLOVER_BLOCK_MAGIC_LENGTH + 1);
int check = buffer.getInt(CLOVER_BLOCK_MAGIC_LENGTH + 9);
// reallocate bytebuffer
buffer = ByteBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH + size]);
channel.position(channel.size() - CLOVER_BLOCK_HEADER_LENGTH - size);
readFully(channel, buffer);
buffer.flip();
// validate checksum
checksum.reset();
checksum.update(buffer.array(), 0, size);
if (check != (int) checksum.getValue()) {
throw new IOException("Invalid checksum when reading index data !!! Possibly corrupted data file.");
}
// we got correct checksum, so populate our index data
int storedindexsize = size / 8;
if (blocksIndex.length < storedindexsize) {
blocksIndex = new long[findNearestPow2(size)];
}
buffer.limit(size);
int index = 0;
while (buffer.hasRemaining() && (index < blocksIndex.length)) {
blocksIndex[index++] = buffer.getLong();
}
// seek to the position of index header as we are going to replace it during append
position = channel.size() - CLOVER_BLOCK_HEADER_LENGTH - size - CLOVER_BLOCK_HEADER_LENGTH;
} else {
// seek to the end
position = channel.size(); // FIXME no index? throw exception?
}
channel.position(position);
channel.truncate(position); // real fix for CLO-6015 - remove remains of old index block
}
/**
* CLO-6015:
* Blocking read from the channel.
* Throws {@link IOException} if less then {@code buffer.capacity()} bytes are read.
*
* @param channel
* @param buffer
* @throws IOException
*/
private static void readFully(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {
if (StreamUtils.readBlocking(channel, buffer) != buffer.capacity()) {
throw new IOException("Unexpected end of file");
}
}
}
public final static class Input extends FilterInputStream {
static final int DEFAULT_SEED = 0x9747b28c;
private final Decompressor decompressor;
private final Checksum checksum;
private CloverBuffer buffer;
private CloverBuffer compressedBuffer;
private long[] blocksIndex;
private long position;
private int firstRecordPosition;
private boolean hasIndex;
private boolean eof = false;
private SeekableByteChannel seekableChannel;
/**
* Create a new {@link OutputStream} with configurable block size. Large blocks require more memory at
* compression and decompression time but should improve the compression ratio.
*
* @param out
* the {@link OutputStream} to feed
* @param blockSize
* the maximum number of bytes to try to compress at once, must be >= 64 and <= 32 M
* @param decompressor
* the {@link Decompressor} instance to use to compress data
*/
public Input(InputStream in, Decompressor decompressor, Checksum checksum) {
super(in);
this.decompressor = decompressor;
this.checksum = checksum;
this.position = 0;
this.firstRecordPosition = -1;
this.blocksIndex = new long[0]; // initally set to zero length
this.buffer = CloverBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH]);
this.buffer.order(BUFFER_BYTE_ORDER);
this.buffer.flip(); // set to empty (no data)
}
/**
* Create a new instance which checks stream integrity using {@link StreamingXXHash32} and doesn't sync flush.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor, Checksum, boolean)
* @see StreamingXXHash32#asChecksum()
*/
public Input(InputStream in, Decompressor decompressor) {
this(in, decompressor, XXHashFactory.fastestInstance().newStreamingHash32(DEFAULT_SEED).asChecksum());
}
public Input(InputStream in) {
this(in, new DecompressorLZ4());
}
public Input(SeekableByteChannel channel, Decompressor decompressor){
this(Channels.newInputStream(channel),decompressor);
this.seekableChannel=channel;
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
@Override
public int read() throws IOException {
if (!buffer.hasRemaining()) {
if (!readDataBlock())
return -1; // end of stream
}
return buffer.get() & 0xFF;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
Utils.checkRange(b, off, len);
int count = 0;
while (buffer.remaining() < len) {
final int l = buffer.remaining();
buffer.get(b, off, l);
count += l;
off += l;
len -= l;
if (!readDataBlock())
return -1; //end of stream;
}
buffer.get(b, off, len);
count += len;
return count;
}
public int read(CloverBuffer inbuffer) throws IOException {
final int pos=inbuffer.position();
while (buffer.remaining() < inbuffer.remaining()) {
inbuffer.put(buffer);
if (!readDataBlock())
return -1;
}
final int savelimit = buffer.limit();
buffer.limit(buffer.position() + inbuffer.remaining());
inbuffer.put(buffer);
buffer.limit(savelimit);
return inbuffer.position()-pos;
}
public int read(ByteBuffer inbuffer) throws IOException {
final int pos=inbuffer.position();
while (buffer.remaining() < inbuffer.remaining()) {
inbuffer.put(buffer.array(), buffer.position(), buffer.remaining());
if (!readDataBlock())
return -1;
}
final int savelimit = buffer.limit();
buffer.limit(buffer.position() + inbuffer.remaining());
inbuffer.put(buffer.array(), buffer.position(), buffer.remaining());
buffer.limit(savelimit);
return inbuffer.position()-pos;
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
in = null;
}
}
/**
* Stores the EOF flag, further attempts to read a data block
* will have no effect and return <code>false</code> immediately.
*
* @return <code>true</code> if a block of data has been read
* @throws IOException
*/
private boolean readDataBlock() throws IOException {
if (eof) {
// CLO-5188
return false;
}
buffer.clear();
// store index of new block which will be added (but only if it contains beginning of record
// firstRecordPosition
final int readin=StreamUtils.readBlocking(in, buffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
if (readin==-1) {
eof = true; // CLO-5188
return false;
}
if (readin!= CLOVER_BLOCK_HEADER_LENGTH || !testBlockHeader(buffer)) {
throw new IOException("Missing block header. Probably corrupted data !");
}
boolean compressed = false;
switch (DataBlockType.get(buffer.get(CLOVER_BLOCK_MAGIC_LENGTH))) {
case COMPRESSED:
compressed = true;
break;
case RAW_DATA:
break;
case INDEX:
eof = true;
// CLO-5188: mark the buffer as empty for reading
buffer.clear();
buffer.flip();
// return, no more data, the index block is always the last
return false;
}
int rawLength = buffer.position(CLOVER_BLOCK_MAGIC_LENGTH + 1).getInt();
int compressedLength = buffer.getInt();
int checksum = buffer.getInt(); // not used currently (only in index block)
firstRecordPosition = buffer.getInt();
buffer.clear();
if (buffer.capacity() < rawLength) {
buffer = CloverBuffer.wrap(new byte[findNearestPow2(rawLength)]);
buffer.order(BUFFER_BYTE_ORDER);
}
if (compressed) {
if (compressedBuffer == null || compressedBuffer.capacity() < compressedLength) {
compressedBuffer = CloverBuffer.wrap(new byte[findNearestPow2(compressedLength)]);
compressedBuffer.order(BUFFER_BYTE_ORDER);
}
if (StreamUtils.readBlocking(in, compressedBuffer.array(), 0, compressedLength) != compressedLength) {
throw new IOException("Unexpected end of file");
}
decompressor.decompress(compressedBuffer.array(), 0, compressedLength , buffer.array(), 0, rawLength);
} else {
if (StreamUtils.readBlocking(in, buffer.array(), 0, rawLength) != rawLength) {
throw new IOException("Unexpected end of file");
}
}
buffer.position(0);
buffer.limit(rawLength);
return true;
}
private final long findNearestBlockIndex(long startAt) {
int pos = Arrays.binarySearch(blocksIndex, startAt);
if (pos < 0) {
return blocksIndex[~pos];
} else if (pos < blocksIndex.length) {
return blocksIndex[pos];
}
return -1;
}
public void readIndexData() throws IOException {
if (this.seekableChannel==null){
throw new IOException("Not a seekable channel/data stream.");
}
position = seekableChannel.position();
ByteBuffer buffer = ByteBuffer.allocate(CLOVER_BLOCK_HEADER_LENGTH);
seekableChannel.position(seekableChannel.size() - CLOVER_BLOCK_HEADER_LENGTH);
if (StreamUtils.readBlocking(seekableChannel, buffer) != CLOVER_BLOCK_HEADER_LENGTH) {
throw new IOException("Missing block header. Probably corrupted data !");
}
buffer.flip();
// test that it is our Index block
if (testBlockHeader(buffer, DataBlockType.INDEX)) {
int size = buffer.getInt(CLOVER_BLOCK_HEADER_LENGTH + 1);
int check = buffer.getInt(CLOVER_BLOCK_HEADER_LENGTH + 9);
// reallocate bytebuffer
buffer = ByteBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH + size]);
seekableChannel.position(seekableChannel.size() - CLOVER_BLOCK_HEADER_LENGTH - size);
if (StreamUtils.readBlocking(seekableChannel, buffer) != buffer.capacity()) {
throw new IOException("Unexpected end of file");
}
buffer.flip();
// validate checksum
checksum.reset();
checksum.update(buffer.array(), 0, size);
if (check != (int) checksum.getValue()) {
throw new IOException("Invalid checksum when reading index data !!! Possibly corrupted data file.");
}
// we got correct checksum, so populate our index data
int storedindexsize = size / LONG_SIZE_BYTES;
blocksIndex = new long[storedindexsize];
buffer.limit(size);
int index = 0;
while (buffer.hasRemaining() && (index < blocksIndex.length)) {
blocksIndex[index++] = buffer.getLong();
}
hasIndex = true;
} else {
hasIndex = false;
}
// seek back to where we started
seekableChannel.position(position);
}
public long size() throws IOException{
return (seekableChannel!=null) ? seekableChannel.size() : -1;
}
public long seekTo(long position) throws IOException{
if (!hasIndex) return -1;
long blockPosition = findNearestBlockIndex(position);
if (blockPosition==-1) return -1;
seekableChannel.position(blockPosition);
if(!readDataBlock()) throw new IOException("Unable to seek.");
if (firstRecordPosition>=0){
buffer.position(firstRecordPosition);
return blockPosition+firstRecordPosition;
}else{
return -1;
}
}
}
} | cloveretl.engine/src/org/jetel/util/stream/CloverDataStream.java | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.util.stream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.util.Arrays;
import java.util.zip.Checksum;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.util.Utils;
import net.jpountz.xxhash.XXHashFactory;
import org.jetel.util.LZ4Provider;
import org.jetel.util.bytes.CloverBuffer;
public class CloverDataStream {
enum DataBlockType {
RAW_DATA('D'), COMPRESSED('C'), ENCRYPTED('E'), ENCRYPTED_COMPRESSED('F'), INDEX('I'), INVALID(' ');
private byte id;
DataBlockType(int id) {
this.id = (byte) id;
}
public byte getId() {
return id;
}
public static final DataBlockType get(byte value) {
switch (value) {
case 'D':
return RAW_DATA;
case 'C':
return COMPRESSED;
case 'E':
return ENCRYPTED;
case 'F':
return ENCRYPTED_COMPRESSED;
case 'I':
return INDEX;
default:
return INVALID;
}
}
}
static abstract class Compressor {
abstract int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset);
abstract int maxCompressedLength(int sourceLength);
}
static abstract class Decompressor {
abstract int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength);
}
public static class CompressorLZ4 extends Compressor{
private final LZ4Compressor compressor;
private CompressorLZ4(LZ4Compressor compressor) {
this.compressor = compressor;
}
public CompressorLZ4() {
this(LZ4Provider.fastestInstance().fastCompressor());
}
public static final CompressorLZ4 getHighCompressor() {
return new CompressorLZ4(LZ4Provider.fastestInstance().highCompressor());
}
@Override
final int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset) {
return compressor.compress(source, sourceOffset, length, target, targetOffset);
}
@Override
final int maxCompressedLength(int sourceLength){
return compressor.maxCompressedLength(sourceLength);
}
}
public static class DecompressorLZ4 extends Decompressor{
private final LZ4FastDecompressor decompressor;
public DecompressorLZ4() {
this.decompressor = LZ4Provider.fastestInstance().fastDecompressor();
}
@Override
final int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength) {
return decompressor.decompress(source, sourceOffset, target, targetOffset, rawDataLength);
}
}
public static class CompressorGZIP extends Compressor {
private Deflater compressor;
public CompressorGZIP(){
this.compressor= new Deflater();
}
@Override
final int compress(byte[] source, int sourceOffset, int length, byte[] target, int targetOffset) {
compressor.setInput(source, sourceOffset, length);
compressor.finish();
int size = compressor.deflate(target, targetOffset, target.length-targetOffset);
if (!compressor.finished()){
size=-1; // problem - we need bigger target buffer
}
compressor.reset();
return size;
}
@Override
final int maxCompressedLength(int sourceLength){
return sourceLength +
((sourceLength + 7) >> 3) + ((sourceLength + 63) >> 6) + 5;
}
}
public static class DecompressorGZIP extends Decompressor {
private Inflater decompressor;
public DecompressorGZIP(){
this.decompressor = new Inflater();
}
@Override
final int decompress(byte[] source, int sourceOffset, int sourceLength, byte[] target, int targetOffset, int rawDataLength) {
decompressor.setInput(source, sourceOffset, sourceLength );
int size;
try {
size = decompressor.inflate(target, targetOffset, rawDataLength);
if (!decompressor.finished()){
size= -1; // problem
}
} catch (DataFormatException e) {
size= -1;
}finally{
decompressor.reset();
}
return size;
}
}
/**
* the minimum compression ratio to go with compressed instead of full bytes
* if block of data after compressions is still quite large compared to full set, we store the full set to save time when reading
*/
public static final double MIN_COMPRESS_RATIO = 0.85;
/**
* number of rounds when compression ratio is lower than threshold before we switch to uncompressed mode.
* if we get often bad results (low compression) then we switch directly to uncompressed mode to save time during write
*/
static final int NO_TEST_ROUNDS = 4;
/**
* This is the identification of Clover data block
*/
static final byte[] CLOVER_BLOCK_MAGIC = new byte[] { 'C', 'L', 'V' };
static final int CLOVER_BLOCK_MAGIC_LENGTH = CLOVER_BLOCK_MAGIC.length;
static final int CLOVER_BLOCK_HEADER_LENGTH =
CLOVER_BLOCK_MAGIC_LENGTH + 1 // token (what type of bloc - compressed/raw/etcc.. - see DataBlockType
+ 4 // compressed length
+ 4 // full length
+ 4 // checksum
+ 4; // position of the first record in block
private final static int LONG_SIZE_BYTES = 8;
static final int DEFAULT_BLOCK_INDEX_SIZE = 128;
static final ByteOrder BUFFER_BYTE_ORDER = ByteOrder.BIG_ENDIAN;
public final static int findNearestPow2(int size) {
int value = 1;
while (value < size) {
value <<= 1;
}
return value;
}
public final static boolean testBlockHeader(CloverBuffer buffer) {
return testBlockHeader(buffer.array(), 0);
}
public final static boolean testBlockHeader(ByteBuffer buffer) {
return testBlockHeader(buffer.array(), 0);
}
public final static boolean testBlockHeader(ByteBuffer buffer, DataBlockType type) {
if (testBlockHeader(buffer.array(), 0) && buffer.get(CloverDataStream.CLOVER_BLOCK_MAGIC_LENGTH) == type.getId())
return true;
else
return false;
}
public final static boolean testBlockHeader(byte[] data, int offset) {
if (data[offset] == CLOVER_BLOCK_MAGIC[0] && data[offset + 1] == CLOVER_BLOCK_MAGIC[1] && data[offset + 2] == CLOVER_BLOCK_MAGIC[2]) {
return true;
} else {
return false;
}
}
public static final class Output extends FilterOutputStream {
/**
*
*/
public static final int DEFAULT_BLOCK_SIZE = 1 << 17; //131072 bytes
static final int COMPRESSION_LEVEL_BASE = 10;
static final int MIN_BLOCK_SIZE = 64;
static final int MAX_BLOCK_SIZE = 1 << (COMPRESSION_LEVEL_BASE + 0x0F);
static final int DEFAULT_SEED = 0x9747b28c;
private final Compressor compressor;
private final Checksum checksum;
private final CloverBuffer buffer;
private final CloverBuffer compressedBuffer;
private long[] blocksIndex;
private final boolean syncFlush;
private boolean finished;
private boolean compress;
private long position;
private int firstRecordPosition;
private int testRound;
/**
* Create a new {@link OutputStream} with configurable block size. Large blocks require more memory at
* compression and decompression time but should improve the compression ratio.
*
* @param out
* the {@link OutputStream} to feed
* @param blockSize
* the maximum number of bytes to try to compress at once, must be >= 64 and <= 32 M
* @param compressor
* the {@link LZ4Compressor} instance to use to compress data
* @param checksum
* the {@link Checksum} instance to use to check data for integrity.
* @param syncFlush
* true if pending data should also be flushed on {@link #flush()}
*/
public Output(OutputStream out, int blockSize, int blockIndexSize, Compressor compressor, Checksum checksum,
boolean syncFlush) {
super(out);
this.compressor = compressor;
this.checksum = checksum;
this.buffer = CloverBuffer.wrap(new byte[blockSize]);
this.buffer.order(BUFFER_BYTE_ORDER);
this.buffer.setRecapacityAllowed(false);
final int compressedBlockSize = CLOVER_BLOCK_HEADER_LENGTH + compressor.maxCompressedLength(blockSize);
this.compressedBuffer = CloverBuffer.wrap(new byte[compressedBlockSize]);
this.compressedBuffer.order(BUFFER_BYTE_ORDER);
this.compressedBuffer.setRecapacityAllowed(false);
this.syncFlush = syncFlush;
finished = false;
compressedBuffer.put(CLOVER_BLOCK_MAGIC);
this.position = 0;
this.firstRecordPosition = -1;
this.blocksIndex = blockIndexSize > DEFAULT_BLOCK_INDEX_SIZE ? new long[((blockIndexSize >> 1) << 1)] : new long[DEFAULT_BLOCK_INDEX_SIZE];
this.compress = false; // no compression by default
this.testRound=0;
}
/**
* Create a new instance which checks stream integrity using {@link StreamingXXHash32} and doesn't sync flush.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor, Checksum, boolean)
* @see StreamingXXHash32#asChecksum()
*/
public Output(OutputStream out, int blockSize, Compressor compressor) {
this(out, blockSize, DEFAULT_BLOCK_INDEX_SIZE, compressor, XXHashFactory.fastestInstance().newStreamingHash32(DEFAULT_SEED).asChecksum(), false);
}
/**
* Create a new instance which compresses with the standard LZ4 compression algorithm.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor)
* @see LZ4Factory#fastCompressor()
*/
public Output(OutputStream out, int blockSize) {
this(out, blockSize, new CompressorLZ4());
}
/**
* Create a new instance which compresses into blocks of DEFAULT_BLOCK_SIZE KB.
*
* @see #LZ4BlockOutputStream(OutputStream, int)
*/
public Output(OutputStream out) {
this(out, DEFAULT_BLOCK_SIZE);
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
public boolean isCompress() {
return compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
private final void ensureNotFinished() {
if (finished) {
throw new IllegalStateException("This stream is already closed");
}
}
@Override
public void write(int b) throws IOException {
ensureNotFinished();
if (!buffer.hasRemaining()) {
flushBufferedData();
}
buffer.put((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
//Utils.checkRange(b, off, len);
ensureNotFinished();
while (buffer.remaining() < len) {
final int l = buffer.remaining();
buffer.put(b, off, l);
flushBufferedData();
off += l;
len -= l;
}
buffer.put(b, off, len);
}
public void write(CloverBuffer inbuffer) throws IOException {
ensureNotFinished();
while (buffer.remaining() < inbuffer.remaining()) {
final int savelimit = inbuffer.limit();
inbuffer.limit(inbuffer.position() + buffer.remaining());
buffer.put(inbuffer);
inbuffer.limit(savelimit);
flushBufferedData();
}
buffer.put(inbuffer);
}
public void write(ByteBuffer inbuffer) throws IOException {
ensureNotFinished();
while (buffer.remaining() < inbuffer.remaining()) {
final int savelimit = inbuffer.limit();
inbuffer.limit(inbuffer.position() + buffer.remaining());
buffer.put(inbuffer);
inbuffer.limit(savelimit);
flushBufferedData();
}
buffer.put(inbuffer);
}
@Override
public void write(byte[] b) throws IOException {
ensureNotFinished();
write(b, 0, b.length);
}
public final void markRecordStart(){
if (firstRecordPosition < 0)
firstRecordPosition = buffer.position();
}
@Override
public void close() throws IOException {
if (out != null) {
finish();
out.close();
out = null;
}
}
private void flushBufferedData() throws IOException {
if (buffer.position() == 0)
return;
// store index of new block which will be added (but only if it contains beginning of record
if (firstRecordPosition >= 0)
storeBlockIndex();
buffer.flip();
final int rawlength = buffer.remaining();
if (compress) {
compressedBuffer.clear();
final int compressedLength = compressor.compress(buffer.array(), 0, rawlength, compressedBuffer.array(), CLOVER_BLOCK_HEADER_LENGTH);
if (compressedLength==-1){
throw new IOException("Error when compressing datablock.");
}
double ratio=((double)compressedLength)/rawlength;
//DEBUG
//System.err.println("compress ratio= "+ratio);
if (ratio > MIN_COMPRESS_RATIO){
if ((testRound++)>NO_TEST_ROUNDS){
compress=false; // we are forcing switch off of compression
}
}
if (compressedLength < rawlength) {
fillBlockHeader(compressedBuffer,DataBlockType.COMPRESSED,compressedLength,rawlength,0,firstRecordPosition);
// write header+data
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH + compressedLength);
position += CLOVER_BLOCK_HEADER_LENGTH + compressedLength;
buffer.clear();
firstRecordPosition = -1; // reset
return;
}
}
fillBlockHeader(compressedBuffer,DataBlockType.RAW_DATA,rawlength,rawlength,0,firstRecordPosition);
// write header
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
// write data
out.write(buffer.array(), 0, rawlength);
position += CLOVER_BLOCK_HEADER_LENGTH + rawlength;
buffer.clear();
firstRecordPosition = -1; // reset
}
private final void fillBlockHeader(CloverBuffer buffer,DataBlockType type,int rawLength,int compressedLength,int checksum,int firstRecPos){
buffer.position(0).put(CLOVER_BLOCK_MAGIC);
buffer.put(type.getId());
buffer.putInt(compressedLength);
buffer.putInt(rawLength);
buffer.putInt(checksum);
buffer.putInt(firstRecPos);
}
/**
* Flush this compressed {@link OutputStream}.
*
* If the stream has been created with <code>syncFlush=true</code>, pending data will be compressed and appended
* to the underlying {@link OutputStream} before calling {@link OutputStream#flush()} on the underlying stream.
* Otherwise, this method just flushes the underlying stream, so pending data might not be available for reading
* until {@link #finish()} or {@link #close()} is called.
*/
@Override
public void flush() throws IOException {
if (syncFlush) {
flushBufferedData();
}
out.flush();
}
/**
* Same as {@link #close()} except that it doesn't close the underlying stream. This can be useful if you want
* to keep on using the underlying stream.
*/
public void finish() throws IOException {
if (!finished) {
writeIndexData(); // this also marks the end of data
finished = true;
}
out.flush();
}
/**
* Writes INDEX block to the stream. This block should be very last. It contains index of all/most previous data
* (raw & compressed) blocks. The header is written twice - as the first & very last set of bytes of this block
* - so it can be read from the end of the data stream. The size of the index may vary.
*
* @throws IOException
*/
public void writeIndexData() throws IOException {
ensureNotFinished();
flushBufferedData();
try {
for (long value : blocksIndex) {
if (value > 0) {
buffer.putLong(value);
}
}
} catch (BufferOverflowException ex) {
throw new IOException("Can't store index data - internal buffer too small");
}
buffer.flip();
final int size = buffer.remaining();
checksum.reset();
checksum.update(buffer.array(), 0, size);
final int check = (int) checksum.getValue();
fillBlockHeader(compressedBuffer, DataBlockType.INDEX,size+CLOVER_BLOCK_HEADER_LENGTH, size+CLOVER_BLOCK_HEADER_LENGTH, check, 0);
position += CLOVER_BLOCK_HEADER_LENGTH + buffer.remaining();
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
out.write(buffer.array(), 0, buffer.remaining());
// write the header at the end again so it can be easily read from back
// the size this time does not contain the block HEADER length
compressedBuffer.putInt(CLOVER_BLOCK_MAGIC_LENGTH + 1, size);
compressedBuffer.putInt(CLOVER_BLOCK_MAGIC_LENGTH + 5, size);
out.write(compressedBuffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
out.flush();
}
private final void storeBlockIndex() throws IOException {
if (blocksIndex.length > 0) {
if (!addBlockIndex(position)) {
compactBlockIndex();
if (!addBlockIndex(position)) {
throw new IOException("Can't store position in index - no space left");
}
}
}
}
private final boolean addBlockIndex(long position) {
for (int i = 0; i < blocksIndex.length; i++) {
if (blocksIndex[i] == 0) {
blocksIndex[i] = position;
return true;
}
}
return false;
}
private final void compactBlockIndex() {
for (int i = 1; i < blocksIndex.length; i += 2) {
blocksIndex[i >> 1] = blocksIndex[i];
blocksIndex[i] = 0;
}
}
/**
* Seeks the channel to position where appending data can start.
* It first reads the stored index in existing file (if index present) and
* then positions the channel so appended data rewrites the index.
*
* @param channel
* @throws IOException
*/
public void seekToAppend(SeekableByteChannel channel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(CLOVER_BLOCK_HEADER_LENGTH);
channel.position(channel.size() - CLOVER_BLOCK_HEADER_LENGTH);
readFully(channel, buffer);
buffer.flip();
// test that it is our Index block
if (testBlockHeader(buffer, DataBlockType.INDEX)) {
int size = buffer.getInt(CLOVER_BLOCK_MAGIC_LENGTH + 1);
int check = buffer.getInt(CLOVER_BLOCK_MAGIC_LENGTH + 9);
// reallocate bytebuffer
buffer = ByteBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH + size]);
channel.position(channel.size() - CLOVER_BLOCK_HEADER_LENGTH - size);
readFully(channel, buffer);
buffer.flip();
// validate checksum
checksum.reset();
checksum.update(buffer.array(), 0, size);
if (check != (int) checksum.getValue()) {
throw new IOException("Invalid checksum when reading index data !!! Possibly corrupted data file.");
}
// we got correct checksum, so populate our index data
int storedindexsize = size / 8;
if (blocksIndex.length < storedindexsize) {
blocksIndex = new long[findNearestPow2(size)];
}
buffer.limit(size);
int index = 0;
while (buffer.hasRemaining() && (index < blocksIndex.length)) {
blocksIndex[index++] = buffer.getLong();
}
// seek to the position of index header as we are going to replace it during append
position = channel.size() - CLOVER_BLOCK_HEADER_LENGTH - size - CLOVER_BLOCK_HEADER_LENGTH;
} else {
// seek to the end
position = channel.size() - 1; // FIXME krivanekm: I don't think this is correct, it overwrites the last byte
}
channel.position(position);
channel.truncate(position); // real fix for CLO-6015 - remove remains of old index block
}
/**
* CLO-6015:
* Blocking read from the channel.
* Throws {@link IOException} if less then {@code buffer.capacity()} bytes are read.
*
* @param channel
* @param buffer
* @throws IOException
*/
private static void readFully(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {
if (StreamUtils.readBlocking(channel, buffer) != buffer.capacity()) {
throw new IOException("Unexpected end of file");
}
}
}
public final static class Input extends FilterInputStream {
static final int DEFAULT_SEED = 0x9747b28c;
private final Decompressor decompressor;
private final Checksum checksum;
private CloverBuffer buffer;
private CloverBuffer compressedBuffer;
private long[] blocksIndex;
private long position;
private int firstRecordPosition;
private boolean hasIndex;
private boolean eof = false;
private SeekableByteChannel seekableChannel;
/**
* Create a new {@link OutputStream} with configurable block size. Large blocks require more memory at
* compression and decompression time but should improve the compression ratio.
*
* @param out
* the {@link OutputStream} to feed
* @param blockSize
* the maximum number of bytes to try to compress at once, must be >= 64 and <= 32 M
* @param decompressor
* the {@link Decompressor} instance to use to compress data
*/
public Input(InputStream in, Decompressor decompressor, Checksum checksum) {
super(in);
this.decompressor = decompressor;
this.checksum = checksum;
this.position = 0;
this.firstRecordPosition = -1;
this.blocksIndex = new long[0]; // initally set to zero length
this.buffer = CloverBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH]);
this.buffer.order(BUFFER_BYTE_ORDER);
this.buffer.flip(); // set to empty (no data)
}
/**
* Create a new instance which checks stream integrity using {@link StreamingXXHash32} and doesn't sync flush.
*
* @see #LZ4BlockOutputStream(OutputStream, int, LZ4Compressor, Checksum, boolean)
* @see StreamingXXHash32#asChecksum()
*/
public Input(InputStream in, Decompressor decompressor) {
this(in, decompressor, XXHashFactory.fastestInstance().newStreamingHash32(DEFAULT_SEED).asChecksum());
}
public Input(InputStream in) {
this(in, new DecompressorLZ4());
}
public Input(SeekableByteChannel channel, Decompressor decompressor){
this(Channels.newInputStream(channel),decompressor);
this.seekableChannel=channel;
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
@Override
public int read() throws IOException {
if (!buffer.hasRemaining()) {
if (!readDataBlock())
return -1; // end of stream
}
return buffer.get() & 0xFF;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
Utils.checkRange(b, off, len);
int count = 0;
while (buffer.remaining() < len) {
final int l = buffer.remaining();
buffer.get(b, off, l);
count += l;
off += l;
len -= l;
if (!readDataBlock())
return -1; //end of stream;
}
buffer.get(b, off, len);
count += len;
return count;
}
public int read(CloverBuffer inbuffer) throws IOException {
final int pos=inbuffer.position();
while (buffer.remaining() < inbuffer.remaining()) {
inbuffer.put(buffer);
if (!readDataBlock())
return -1;
}
final int savelimit = buffer.limit();
buffer.limit(buffer.position() + inbuffer.remaining());
inbuffer.put(buffer);
buffer.limit(savelimit);
return inbuffer.position()-pos;
}
public int read(ByteBuffer inbuffer) throws IOException {
final int pos=inbuffer.position();
while (buffer.remaining() < inbuffer.remaining()) {
inbuffer.put(buffer.array(), buffer.position(), buffer.remaining());
if (!readDataBlock())
return -1;
}
final int savelimit = buffer.limit();
buffer.limit(buffer.position() + inbuffer.remaining());
inbuffer.put(buffer.array(), buffer.position(), buffer.remaining());
buffer.limit(savelimit);
return inbuffer.position()-pos;
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
in = null;
}
}
/**
* Stores the EOF flag, further attempts to read a data block
* will have no effect and return <code>false</code> immediately.
*
* @return <code>true</code> if a block of data has been read
* @throws IOException
*/
private boolean readDataBlock() throws IOException {
if (eof) {
// CLO-5188
return false;
}
buffer.clear();
// store index of new block which will be added (but only if it contains beginning of record
// firstRecordPosition
final int readin=StreamUtils.readBlocking(in, buffer.array(), 0, CLOVER_BLOCK_HEADER_LENGTH);
if (readin==-1) {
eof = true; // CLO-5188
return false;
}
if (readin!= CLOVER_BLOCK_HEADER_LENGTH || !testBlockHeader(buffer)) {
throw new IOException("Missing block header. Probably corrupted data !");
}
boolean compressed = false;
switch (DataBlockType.get(buffer.get(CLOVER_BLOCK_MAGIC_LENGTH))) {
case COMPRESSED:
compressed = true;
break;
case RAW_DATA:
break;
case INDEX:
eof = true;
// CLO-5188: mark the buffer as empty for reading
buffer.clear();
buffer.flip();
// return, no more data, the index block is always the last
return false;
}
int rawLength = buffer.position(CLOVER_BLOCK_MAGIC_LENGTH + 1).getInt();
int compressedLength = buffer.getInt();
int checksum = buffer.getInt(); // not used currently (only in index block)
firstRecordPosition = buffer.getInt();
buffer.clear();
if (buffer.capacity() < rawLength) {
buffer = CloverBuffer.wrap(new byte[findNearestPow2(rawLength)]);
buffer.order(BUFFER_BYTE_ORDER);
}
if (compressed) {
if (compressedBuffer == null || compressedBuffer.capacity() < compressedLength) {
compressedBuffer = CloverBuffer.wrap(new byte[findNearestPow2(compressedLength)]);
compressedBuffer.order(BUFFER_BYTE_ORDER);
}
if (StreamUtils.readBlocking(in, compressedBuffer.array(), 0, compressedLength) != compressedLength) {
throw new IOException("Unexpected end of file");
}
decompressor.decompress(compressedBuffer.array(), 0, compressedLength , buffer.array(), 0, rawLength);
} else {
if (StreamUtils.readBlocking(in, buffer.array(), 0, rawLength) != rawLength) {
throw new IOException("Unexpected end of file");
}
}
buffer.position(0);
buffer.limit(rawLength);
return true;
}
private final long findNearestBlockIndex(long startAt) {
int pos = Arrays.binarySearch(blocksIndex, startAt);
if (pos < 0) {
return blocksIndex[~pos];
} else if (pos < blocksIndex.length) {
return blocksIndex[pos];
}
return -1;
}
public void readIndexData() throws IOException {
if (this.seekableChannel==null){
throw new IOException("Not a seekable channel/data stream.");
}
position = seekableChannel.position();
ByteBuffer buffer = ByteBuffer.allocate(CLOVER_BLOCK_HEADER_LENGTH);
seekableChannel.position(seekableChannel.size() - CLOVER_BLOCK_HEADER_LENGTH);
if (StreamUtils.readBlocking(seekableChannel, buffer) != CLOVER_BLOCK_HEADER_LENGTH) {
throw new IOException("Missing block header. Probably corrupted data !");
}
buffer.flip();
// test that it is our Index block
if (testBlockHeader(buffer, DataBlockType.INDEX)) {
int size = buffer.getInt(CLOVER_BLOCK_HEADER_LENGTH + 1);
int check = buffer.getInt(CLOVER_BLOCK_HEADER_LENGTH + 9);
// reallocate bytebuffer
buffer = ByteBuffer.wrap(new byte[CLOVER_BLOCK_HEADER_LENGTH + size]);
seekableChannel.position(seekableChannel.size() - CLOVER_BLOCK_HEADER_LENGTH - size);
if (StreamUtils.readBlocking(seekableChannel, buffer) != buffer.capacity()) {
throw new IOException("Unexpected end of file");
}
buffer.flip();
// validate checksum
checksum.reset();
checksum.update(buffer.array(), 0, size);
if (check != (int) checksum.getValue()) {
throw new IOException("Invalid checksum when reading index data !!! Possibly corrupted data file.");
}
// we got correct checksum, so populate our index data
int storedindexsize = size / LONG_SIZE_BYTES;
blocksIndex = new long[storedindexsize];
buffer.limit(size);
int index = 0;
while (buffer.hasRemaining() && (index < blocksIndex.length)) {
blocksIndex[index++] = buffer.getLong();
}
hasIndex = true;
} else {
hasIndex = false;
}
// seek back to where we started
seekableChannel.position(position);
}
public long size() throws IOException{
return (seekableChannel!=null) ? seekableChannel.size() : -1;
}
public long seekTo(long position) throws IOException{
if (!hasIndex) return -1;
long blockPosition = findNearestBlockIndex(position);
if (blockPosition==-1) return -1;
seekableChannel.position(blockPosition);
if(!readDataBlock()) throw new IOException("Unable to seek.");
if (firstRecordPosition>=0){
buffer.position(firstRecordPosition);
return blockPosition+firstRecordPosition;
}else{
return -1;
}
}
}
} | FIX: CLO-6015 - CloverDataWriter: possible file corruption on append fixed.
git-svn-id: 3b972608fd747d4039df1c934c79ac563d582597@17429 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/util/stream/CloverDataStream.java | FIX: CLO-6015 - CloverDataWriter: possible file corruption on append fixed. | <ide><path>loveretl.engine/src/org/jetel/util/stream/CloverDataStream.java
<ide> position = channel.size() - CLOVER_BLOCK_HEADER_LENGTH - size - CLOVER_BLOCK_HEADER_LENGTH;
<ide> } else {
<ide> // seek to the end
<del> position = channel.size() - 1; // FIXME krivanekm: I don't think this is correct, it overwrites the last byte
<add> position = channel.size(); // FIXME no index? throw exception?
<ide> }
<ide> channel.position(position);
<ide> channel.truncate(position); // real fix for CLO-6015 - remove remains of old index block |
|
Java | apache-2.0 | d49fc62e6fa2700d7b153f8592a7663f26cf04ac | 0 | bmatthews68/ldap-maven-plugin | /*
* Copyright 2008-2016 Brian Thomas Matthews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.btmatthews.maven.plugins.ldap.apache;
import com.btmatthews.maven.plugins.ldap.AbstractLDAPServer;
import com.btmatthews.utils.monitor.Logger;
import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.authn.AuthenticationInterceptor;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.exception.ExceptionInterceptor;
import org.apache.directory.server.core.interceptor.Interceptor;
import org.apache.directory.server.core.normalization.NormalizationInterceptor;
import org.apache.directory.server.core.operational.OperationalAttributeInterceptor;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.core.referral.ReferralInterceptor;
import org.apache.directory.server.core.subtree.SubentryInterceptor;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.protocol.shared.store.LdifFileLoader;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.shared.ldap.exception.LdapNameNotFoundException;
import org.apache.directory.shared.ldap.name.LdapDN;
import java.util.ArrayList;
import java.util.List;
/**
* Implements an embedded ApacheDS LDAP apache.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @since 1.1.0
*/
public final class ApacheDSServer extends AbstractLDAPServer {
/**
* The LDAP directory service.
*/
private DirectoryService service;
/**
* The server that listens for LDAP requests and forwards them to the directory service.
*/
private LdapServer server;
/**
* Configure and start the embedded ApacheDS server creating the root DN and loading the LDIF seed data.
*
* @param logger Used to log informational and error messages.
*/
@Override
public void start(final Logger logger) {
try {
logger.logInfo("Starting ApacheDS server");
service = new DefaultDirectoryService();
final List<Interceptor> list = new ArrayList<Interceptor>();
list.add(new NormalizationInterceptor());
list.add(new AuthenticationInterceptor());
list.add(new ReferralInterceptor());
// list.add( new AciAuthorizationInterceptor() );
// list.add( new DefaultAuthorizationInterceptor() );
list.add(new ExceptionInterceptor());
// list.add( new ChangeLogInterceptor() );
list.add(new OperationalAttributeInterceptor());
// list.add( new SchemaInterceptor() );
list.add(new SubentryInterceptor());
// list.add( new CollectiveAttributeInterceptor() );
// list.add( new EventInterceptor() );
// list.add( new TriggerInterceptor() );
// list.add( new JournalInterceptor() );
service.setInterceptors(list);
service.setWorkingDirectory(getWorkingDirectory());
final JdbmPartition partition = new JdbmPartition();
partition.setId("rootPartition");
partition.setSuffix(getRoot());
service.addPartition(partition);
service.setExitVmOnShutdown(false);
service.setShutdownHookEnabled(false);
service.getChangeLog().setEnabled(false);
service.setDenormalizeOpAttrsEnabled(true);
server = new LdapServer();
server.setDirectoryService(service);
server.setTransports(new TcpTransport(getServerPort()));
service.startup();
server.start();
createRoot(partition);
loadLdifFile();
logger.logInfo("Started ApacheDS server");
} catch (final Exception e) {
logger.logError("Error starting ApacheDS server e");
}
}
/**
* Shutdown the the embedded ApacheDS server.
*
* @param logger Used to log informational and error messages.
*/
@Override
public void stop(final Logger logger) {
try {
logger.logInfo("Stopping ApacheDS server");
server.stop();
service.shutdown();
logger.logInfo("Stopped ApacheDS server");
} catch (final Exception e) {
logger.logError("Error stopping ApacheDS server", e);
}
}
@Override
public boolean isStarted(final Logger logger) {
return server != null && server.isStarted();
}
@Override
public boolean isStopped(final Logger logger) {
return server == null || !server.isStarted();
}
/**
* Create the root DN.
*
* @param partition The partition in which to create the root DN.
* @throws Exception If there was an error creating the root DN.
*/
private void createRoot(final Partition partition) throws Exception {
try {
service.getAdminSession().lookup(partition.getSuffixDn());
} catch (final LdapNameNotFoundException e) {
final LdapDN dn = new LdapDN(getRoot());
final String dc = getRoot().substring(3, getRoot().indexOf(','));
final ServerEntry entry = service.newEntry(dn);
entry.add("objectClass", "top", "domain", "extensibleObject");
entry.add("dc", dc);
service.getAdminSession().add(entry);
}
}
/**
* Load the LDIF file used to seed the directory.
*
* @throws Exception If there was an error.
*/
private void loadLdifFile() throws Exception {
new LdifFileLoader(service.getAdminSession(), getLdifFile(), null)
.execute();
}
} | server-apacheds/src/main/java/com/btmatthews/maven/plugins/ldap/apache/ApacheDSServer.java | /*
* Copyright 2008-2016 Brian Thomas Matthews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.btmatthews.maven.plugins.ldap.apache;
import com.btmatthews.maven.plugins.ldap.AbstractLDAPServer;
import com.btmatthews.utils.monitor.Logger;
import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.authn.AuthenticationInterceptor;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.exception.ExceptionInterceptor;
import org.apache.directory.server.core.interceptor.Interceptor;
import org.apache.directory.server.core.normalization.NormalizationInterceptor;
import org.apache.directory.server.core.operational.OperationalAttributeInterceptor;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.core.referral.ReferralInterceptor;
import org.apache.directory.server.core.subtree.SubentryInterceptor;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.protocol.shared.store.LdifFileLoader;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.shared.ldap.exception.LdapNameNotFoundException;
import org.apache.directory.shared.ldap.name.LdapDN;
import java.util.ArrayList;
import java.util.List;
/**
* Implements an embedded ApacheDS LDAP apache.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @since 1.1.0
*/
public final class ApacheDSServer extends AbstractLDAPServer {
/**
* The LDAP directory service.
*/
private DirectoryService service;
/**
* The server that listens for LDAP requests and forwards them to the directory service.
*/
private LdapServer server;
/**
* Configure and start the embedded ApacheDS server creating the root DN and loading the LDIF seed data.
*
* @param logger Used to log informational and error messages.
*/
@Override
public void start(final Logger logger) {
try {
logger.logInfo("Starting ApacheDS server");
service = new DefaultDirectoryService();
final List<Interceptor> list = new ArrayList<Interceptor>();
list.add(new NormalizationInterceptor());
list.add(new AuthenticationInterceptor());
list.add(new ReferralInterceptor());
// list.add( new AciAuthorizationInterceptor() );
// list.add( new DefaultAuthorizationInterceptor() );
list.add(new ExceptionInterceptor());
// list.add( new ChangeLogInterceptor() );
list.add(new OperationalAttributeInterceptor());
// list.add( new SchemaInterceptor() );
list.add(new SubentryInterceptor());
// list.add( new CollectiveAttributeInterceptor() );
// list.add( new EventInterceptor() );
// list.add( new TriggerInterceptor() );
// list.add( new JournalInterceptor() );
service.setInterceptors(list);
final JdbmPartition partition = new JdbmPartition();
partition.setId("rootPartition");
partition.setSuffix(getRoot());
service.addPartition(partition);
service.setExitVmOnShutdown(false);
service.setShutdownHookEnabled(false);
service.getChangeLog().setEnabled(false);
service.setDenormalizeOpAttrsEnabled(true);
server = new LdapServer();
server.setDirectoryService(service);
server.setTransports(new TcpTransport(getServerPort()));
service.startup();
server.start();
createRoot(partition);
loadLdifFile();
logger.logInfo("Started ApacheDS server");
} catch (final Exception e) {
logger.logError("Error starting ApacheDS server e");
}
}
/**
* Shutdown the the embedded ApacheDS server.
*
* @param logger Used to log informational and error messages.
*/
@Override
public void stop(final Logger logger) {
try {
logger.logInfo("Stopping ApacheDS server");
server.stop();
service.shutdown();
logger.logInfo("Stopped ApacheDS server");
} catch (final Exception e) {
logger.logError("Error stopping ApacheDS server", e);
}
}
@Override
public boolean isStarted(final Logger logger) {
return server != null && server.isStarted();
}
@Override
public boolean isStopped(final Logger logger) {
return server == null || !server.isStarted();
}
/**
* Create the root DN.
*
* @param partition The partition in which to create the root DN.
* @throws Exception If there was an error creating the root DN.
*/
private void createRoot(final Partition partition) throws Exception {
try {
service.getAdminSession().lookup(partition.getSuffixDn());
} catch (final LdapNameNotFoundException e) {
final LdapDN dn = new LdapDN(getRoot());
final String dc = getRoot().substring(3, getRoot().indexOf(','));
final ServerEntry entry = service.newEntry(dn);
entry.add("objectClass", "top", "domain", "extensibleObject");
entry.add("dc", dc);
service.getAdminSession().add(entry);
}
}
/**
* Load the LDIF file used to seed the directory.
*
* @throws Exception If there was an error.
*/
private void loadLdifFile() throws Exception {
new LdifFileLoader(service.getAdminSession(), getLdifFile(), null)
.execute();
}
} | Fixes #13 by allowing setting the working directory for ApacheDS and using the target directory as the default
| server-apacheds/src/main/java/com/btmatthews/maven/plugins/ldap/apache/ApacheDSServer.java | Fixes #13 by allowing setting the working directory for ApacheDS and using the target directory as the default | <ide><path>erver-apacheds/src/main/java/com/btmatthews/maven/plugins/ldap/apache/ApacheDSServer.java
<ide> // list.add( new TriggerInterceptor() );
<ide> // list.add( new JournalInterceptor() );
<ide> service.setInterceptors(list);
<add> service.setWorkingDirectory(getWorkingDirectory());
<ide>
<ide> final JdbmPartition partition = new JdbmPartition();
<ide> partition.setId("rootPartition"); |
|
Java | bsd-2-clause | 64789830911f722d4ed0330edb95ab0bf9ae41dd | 0 | mosoft521/jodd,mosoft521/jodd,oblac/jodd,mosoft521/jodd,oblac/jodd,mosoft521/jodd,oblac/jodd,oblac/jodd | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.cli;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CliOptionsTest {
private Cli buildCli(final List<String> out) {
final Cli cli = new Cli();
cli.option()
.shortName("a")
.with(out::add);
cli.option()
.longName("bbb")
.with(out::add);
cli.option()
.shortName("c")
.longName("ccc")
.with(out::add);
cli.option()
.shortName("A")
.hasArg()
.with(out::add);
cli.param()
.with(arr -> out.add(arr[0]));
return cli;
}
@Test
void testEmpty() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("");
assertEquals("[]", out.toString());
}
@Test
void testFlags_short() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-a", "-c");
assertEquals("[a, c]", out.toString());
}
@Test
void testFlags_short_group() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-ac", "--ccc");
assertEquals("[a, c, ccc]", out.toString());
}
@Test
void testFlags_long() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("--bbb", "--ccc");
assertEquals("[bbb, ccc]", out.toString());
}
@Test
void testOption() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-A", "123");
assertEquals("[123]", out.toString());
}
@Test
void testOptionWithValue() {
final List<String> out = new ArrayList<>();
final Cli cli = new Cli();
cli.option()
.shortName("a")
.hasArg()
.with(out::add);
cli.option()
.longName("foo")
.hasArg()
.with(out::add);
cli.printUsage("cmd");
cli.accept("-a", "1", "--foo", "F");
assertEquals("[1, F]", out.toString());
out.clear();
cli.accept("-a=1", "--foo=F");
assertEquals("[1, F]", out.toString());
out.clear();
}
@Test
void testToString() throws Exception {
final List<String> out = new ArrayList<>();
final Cli cli = new Cli();
cli.option().shortName("a").hasArg().with(out::add);
cli.option().longName("foo").hasArg().with(out::add);
cli.printUsage("cmd");
cli.accept("-a", "1", "--foo", "F");
out.clear();
cli.accept("-a=1", "--foo=F");
out.clear();
Assertions.assertEquals("--foo", cli.option().longName("foo").hasArg().with(out::add).toString());
}
}
| jodd-core/src/test/java/jodd/cli/CliOptionsTest.java | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.cli;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CliOptionsTest {
private Cli buildCli(final List<String> out) {
final Cli cli = new Cli();
cli.option()
.shortName("a")
.with(out::add);
cli.option()
.longName("bbb")
.with(out::add);
cli.option()
.shortName("c")
.longName("ccc")
.with(out::add);
cli.option()
.shortName("A")
.hasArg()
.with(out::add);
cli.param()
.with(arr -> out.add(arr[0]));
return cli;
}
@Test
void testEmpty() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("");
assertEquals("[]", out.toString());
}
@Test
void testFlags_short() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-a", "-c");
assertEquals("[a, c]", out.toString());
}
@Test
void testFlags_short_group() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-ac", "--ccc");
assertEquals("[a, c, ccc]", out.toString());
}
@Test
void testFlags_long() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("--bbb", "--ccc");
assertEquals("[bbb, ccc]", out.toString());
}
@Test
void testOption() {
final List<String> out = new ArrayList<>();
final Cli cli = buildCli(out);
cli.accept("-A", "123");
assertEquals("[123]", out.toString());
}
@Test
void testOptionWithValue() {
final List<String> out = new ArrayList<>();
final Cli cli = new Cli();
cli.option()
.shortName("a")
.hasArg()
.with(out::add);
cli.option()
.longName("foo")
.hasArg()
.with(out::add);
cli.printUsage("cmd");
cli.accept("-a", "1", "--foo", "F");
assertEquals("[1, F]", out.toString());
out.clear();
cli.accept("-a=1", "--foo=F");
assertEquals("[1, F]", out.toString());
out.clear();
}
}
| Add test for Option.toString
| jodd-core/src/test/java/jodd/cli/CliOptionsTest.java | Add test for Option.toString | <ide><path>odd-core/src/test/java/jodd/cli/CliOptionsTest.java
<ide>
<ide> package jodd.cli;
<ide>
<add>import org.junit.jupiter.api.Assertions;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import java.util.ArrayList;
<ide> assertEquals("[1, F]", out.toString());
<ide> out.clear();
<ide> }
<add>
<add> @Test
<add> void testToString() throws Exception {
<add> final List<String> out = new ArrayList<>();
<add> final Cli cli = new Cli();
<add> cli.option().shortName("a").hasArg().with(out::add);
<add> cli.option().longName("foo").hasArg().with(out::add);
<add> cli.printUsage("cmd");
<add> cli.accept("-a", "1", "--foo", "F");
<add> out.clear();
<add> cli.accept("-a=1", "--foo=F");
<add> out.clear();
<add> Assertions.assertEquals("--foo", cli.option().longName("foo").hasArg().with(out::add).toString());
<add> }
<ide> } |
|
JavaScript | bsd-3-clause | f20e5d68736249950fa43d2ee62f1a5c409b8119 | 0 | lloydbenson/glue | 'use strict';
// Load modules
const Path = require('path');
const Hapi = require('hapi');
const Hoek = require('hoek');
const Items = require('items');
const Joi = require('joi');
// Declare internals
const internals = {};
internals.schema = {
options: Joi.object({
relativeTo: Joi.string(),
preConnections: Joi.func().allow(false),
preRegister: Joi.func().allow(false)
}),
manifest: Joi.object({
server: Joi.object(),
connections: Joi.array().items(Joi.object()),
registrations: Joi.array().items(Joi.object({
plugin: [
Joi.string(),
Joi.object({ register: Joi.string() }).unknown()
],
options: Joi.object()
}))
})
};
exports.compose = function (manifest /*, [options], [callback] */) {
Hoek.assert(arguments.length <= 3, 'Invalid number of arguments');
const options = arguments.length === 1 || typeof arguments[1] === 'function' ? {} : arguments[1];
const callback = typeof arguments[arguments.length - 1] === 'function' ? arguments[arguments.length - 1] : null;
Joi.assert(options, internals.schema.options, 'Invalid options');
Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');
// Return Promise if no callback provided
if (!callback) {
return new Promise((resolve, reject) => {
exports.compose(manifest, options, (err, server) => {
if (err) {
return reject(err);
}
return resolve(server);
});
});
}
// Create server
const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
const server = new Hapi.Server(serverOpts);
const steps = [];
steps.push((next) => {
if (options.preConnections) {
options.preConnections(server, next);
}
else {
next();
}
});
steps.push((next) => {
// Load connections
if (manifest.connections && manifest.connections.length > 0) {
manifest.connections.forEach((connection) => {
server.connection(connection);
});
}
else {
server.connection();
}
next();
});
steps.push((next) => {
if (options.preRegister) {
options.preRegister(server, next);
}
else {
next();
}
});
steps.push((next) => {
// Load registrations
if (manifest.registrations) {
const registrations = manifest.registrations.map((reg) => {
return {
plugin: internals.parsePlugin(reg.plugin, options.relativeTo),
options: reg.options || {}
};
});
Items.serial(registrations, (reg, nextRegister) => {
server.register(reg.plugin, reg.options, nextRegister);
}, next);
}
else {
next();
}
});
Items.serial(steps, (step, nextStep) => {
step(nextStep);
}, (err) => {
if (err) {
return Hoek.nextTick(callback)(err);
}
Hoek.nextTick(callback)(null, server);
});
};
internals.parseServer = function (server, relativeTo) {
if (server.cache) {
server = Hoek.clone(server);
const caches = [];
const config = [].concat(server.cache);
for (let i = 0; i < config.length; ++i) {
let item = config[i];
if (typeof item === 'string') {
item = { engine: item };
}
if (typeof item.engine === 'string') {
let strategy = item.engine;
if (relativeTo && strategy[0] === '.') {
strategy = Path.join(relativeTo, strategy);
}
item.engine = require(strategy);
}
caches.push(item);
}
server.cache = caches;
}
return server;
};
internals.parsePlugin = function (plugin, relativeTo) {
plugin = Hoek.cloneWithShallow(plugin, ['options']);
if (typeof plugin === 'string') {
plugin = { register: plugin };
}
let path = plugin.register;
if (relativeTo && path[0] === '.') {
path = Path.join(relativeTo, path);
}
plugin.register = require(path);
return plugin;
};
| lib/index.js | 'use strict';
// Load modules
const Path = require('path');
const Hapi = require('hapi');
const Hoek = require('hoek');
const Items = require('items');
const Joi = require('joi');
// Declare internals
const internals = {};
internals.schema = {
options: Joi.object({
relativeTo: Joi.string(),
preConnections: Joi.func().allow(false),
preRegister: Joi.func().allow(false)
}),
manifest: Joi.object({
server: Joi.object(),
connections: Joi.array(Joi.object()),
registrations: Joi.array().items(Joi.object({
plugin: [
Joi.string(),
Joi.object({ register: Joi.string() }).unknown()
],
options: Joi.object()
}))
})
};
exports.compose = function (manifest /*, [options], [callback] */) {
Hoek.assert(arguments.length <= 3, 'Invalid number of arguments');
const options = arguments.length === 1 || typeof arguments[1] === 'function' ? {} : arguments[1];
const callback = typeof arguments[arguments.length - 1] === 'function' ? arguments[arguments.length - 1] : null;
Joi.assert(options, internals.schema.options, 'Invalid options');
Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');
// Return Promise if no callback provided
if (!callback) {
return new Promise((resolve, reject) => {
exports.compose(manifest, options, (err, server) => {
if (err) {
return reject(err);
}
return resolve(server);
});
});
}
// Create server
const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
const server = new Hapi.Server(serverOpts);
const steps = [];
steps.push((next) => {
if (options.preConnections) {
options.preConnections(server, next);
}
else {
next();
}
});
steps.push((next) => {
// Load connections
if (manifest.connections && manifest.connections.length > 0) {
manifest.connections.forEach((connection) => {
server.connection(connection);
});
}
else {
server.connection();
}
next();
});
steps.push((next) => {
if (options.preRegister) {
options.preRegister(server, next);
}
else {
next();
}
});
steps.push((next) => {
// Load registrations
if (manifest.registrations) {
const registrations = manifest.registrations.map((reg) => {
return {
plugin: internals.parsePlugin(reg.plugin, options.relativeTo),
options: reg.options || {}
};
});
Items.serial(registrations, (reg, nextRegister) => {
server.register(reg.plugin, reg.options, nextRegister);
}, next);
}
else {
next();
}
});
Items.serial(steps, (step, nextStep) => {
step(nextStep);
}, (err) => {
if (err) {
return Hoek.nextTick(callback)(err);
}
Hoek.nextTick(callback)(null, server);
});
};
internals.parseServer = function (server, relativeTo) {
if (server.cache) {
server = Hoek.clone(server);
const caches = [];
const config = [].concat(server.cache);
for (let i = 0; i < config.length; ++i) {
let item = config[i];
if (typeof item === 'string') {
item = { engine: item };
}
if (typeof item.engine === 'string') {
let strategy = item.engine;
if (relativeTo && strategy[0] === '.') {
strategy = Path.join(relativeTo, strategy);
}
item.engine = require(strategy);
}
caches.push(item);
}
server.cache = caches;
}
return server;
};
internals.parsePlugin = function (plugin, relativeTo) {
plugin = Hoek.cloneWithShallow(plugin, ['options']);
if (typeof plugin === 'string') {
plugin = { register: plugin };
}
let path = plugin.register;
if (relativeTo && path[0] === '.') {
path = Path.join(relativeTo, path);
}
plugin.register = require(path);
return plugin;
};
| Refactors Joi.array() to utilize .items() [#83]
| lib/index.js | Refactors Joi.array() to utilize .items() [#83] | <ide><path>ib/index.js
<ide> }),
<ide> manifest: Joi.object({
<ide> server: Joi.object(),
<del> connections: Joi.array(Joi.object()),
<add> connections: Joi.array().items(Joi.object()),
<ide> registrations: Joi.array().items(Joi.object({
<ide> plugin: [
<ide> Joi.string(), |
|
Java | apache-2.0 | 4fdaa094c8e7153ae52f50dd6ee1800f1dc6ca25 | 0 | TangHao1987/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,holmes/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,caot/intellij-community,fnouama/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,caot/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,slisson/intellij-community,signed/intellij-community,amith01994/intellij-community,holmes/intellij-community,kdwink/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ibinti/intellij-community,clumsy/intellij-community,allotria/intellij-community,adedayo/intellij-community,izonder/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,kool79/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,fnouama/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,adedayo/intellij-community,semonte/intellij-community,nicolargo/intellij-community,signed/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,kool79/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,petteyg/intellij-community,izonder/intellij-community,ryano144/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,allotria/intellij-community,dslomov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,kool79/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,signed/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,jagguli/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,hurricup/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,slisson/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,signed/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,asedunov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,amith01994/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,samthor/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,retomerz/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,xfournet/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,izonder/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,apixandru/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,slisson/intellij-community,orekyuu/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,clumsy/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,allotria/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,semonte/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,amith01994/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,dslomov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,izonder/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,supersven/intellij-community,kool79/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,fitermay/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,izonder/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,caot/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,caot/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,semonte/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,fnouama/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,retomerz/intellij-community,diorcety/intellij-community,semonte/intellij-community,jagguli/intellij-community,amith01994/intellij-community,slisson/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,vladmm/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,samthor/intellij-community,slisson/intellij-community,signed/intellij-community,petteyg/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,izonder/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,fnouama/intellij-community,kool79/intellij-community,allotria/intellij-community,slisson/intellij-community,asedunov/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,da1z/intellij-community,hurricup/intellij-community,asedunov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,xfournet/intellij-community,xfournet/intellij-community,vladmm/intellij-community,semonte/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,hurricup/intellij-community,samthor/intellij-community,caot/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,caot/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,izonder/intellij-community,diorcety/intellij-community,robovm/robovm-studio,amith01994/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,izonder/intellij-community,da1z/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,da1z/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,hurricup/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,samthor/intellij-community,dslomov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,caot/intellij-community,da1z/intellij-community,dslomov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,vladmm/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,clumsy/intellij-community,da1z/intellij-community,adedayo/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,caot/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,ryano144/intellij-community,petteyg/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,da1z/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,allotria/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,robovm/robovm-studio,signed/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,jagguli/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,signed/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,signed/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,holmes/intellij-community,izonder/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,robovm/robovm-studio,holmes/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,robovm/robovm-studio,slisson/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,da1z/intellij-community,tmpgit/intellij-community,kool79/intellij-community,xfournet/intellij-community,signed/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,samthor/intellij-community,caot/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,FHannes/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,retomerz/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.TraceableDisposable;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author dsl
*/
public class VirtualFilePointerContainerImpl extends TraceableDisposable implements VirtualFilePointerContainer, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer");
@NotNull private final List<VirtualFilePointer> myList = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final VirtualFilePointerManager myVirtualFilePointerManager;
@NotNull private final Disposable myParent;
private final VirtualFilePointerListener myListener;
private volatile Trinity<String[], VirtualFile[], VirtualFile[]> myCachedThings;
private volatile long myTimeStampOfCachedThings = -1;
@NonNls public static final String URL_ATTR = "url";
private boolean myDisposed;
private static final boolean TRACE_CREATION = LOG.isDebugEnabled() || ApplicationManager.getApplication().isUnitTestMode();
public VirtualFilePointerContainerImpl(@NotNull VirtualFilePointerManager manager,
@NotNull Disposable parentDisposable,
@Nullable VirtualFilePointerListener listener) {
//noinspection HardCodedStringLiteral
super(TRACE_CREATION
? new Throwable("parent = '" + parentDisposable + "' (" + parentDisposable.getClass() + "); listener=" + listener)
: null);
myVirtualFilePointerManager = manager;
myParent = parentDisposable;
myListener = listener;
}
@Override
public void readExternal(@NotNull final Element rootChild, @NotNull final String childElements) throws InvalidDataException {
final List urls = rootChild.getChildren(childElements);
for (Object url : urls) {
Element pathElement = (Element)url;
final String urlAttribute = pathElement.getAttributeValue(URL_ATTR);
if (urlAttribute == null) throw new InvalidDataException("path element without url");
add(urlAttribute);
}
}
@Override
public void writeExternal(@NotNull final Element element, @NotNull final String childElementName) {
for (VirtualFilePointer pointer : myList) {
String url = pointer.getUrl();
final Element rootPathElement = new Element(childElementName);
rootPathElement.setAttribute(URL_ATTR, url);
element.addContent(rootPathElement);
}
}
@Override
public void moveUp(@NotNull String url) {
int index = indexOf(url);
if (index <= 0) return;
dropCaches();
ContainerUtil.swapElements(myList, index - 1, index);
}
@Override
public void moveDown(@NotNull String url) {
int index = indexOf(url);
if (index < 0 || index + 1 >= myList.size()) return;
dropCaches();
ContainerUtil.swapElements(myList, index, index + 1);
}
private int indexOf(@NotNull final String url) {
for (int i = 0; i < myList.size(); i++) {
final VirtualFilePointer pointer = myList.get(i);
if (url.equals(pointer.getUrl())) {
return i;
}
}
return -1;
}
@Override
public void killAll() {
myList.clear();
}
@Override
public void add(@NotNull VirtualFile file) {
assert !myDisposed;
dropCaches();
final VirtualFilePointer pointer = create(file);
myList.add(pointer);
}
@Override
public void add(@NotNull String url) {
assert !myDisposed;
dropCaches();
final VirtualFilePointer pointer = create(url);
myList.add(pointer);
}
@Override
public void remove(@NotNull VirtualFilePointer pointer) {
assert !myDisposed;
dropCaches();
final boolean result = myList.remove(pointer);
LOG.assertTrue(result);
}
@Override
@NotNull
public List<VirtualFilePointer> getList() {
assert !myDisposed;
return Collections.unmodifiableList(myList);
}
@Override
public void addAll(@NotNull VirtualFilePointerContainer that) {
assert !myDisposed;
dropCaches();
List<VirtualFilePointer> thatList = ((VirtualFilePointerContainerImpl)that).myList;
for (final VirtualFilePointer pointer : thatList) {
myList.add(duplicate(pointer));
}
}
private void dropCaches() {
myTimeStampOfCachedThings = -1; // make it never equal to myVirtualFilePointerManager.getModificationCount()
myCachedThings = EMPTY;
}
@Override
@NotNull
public String[] getUrls() {
return getOrCache().first;
}
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> getOrCache() {
assert !myDisposed;
long timeStamp = myTimeStampOfCachedThings;
Trinity<String[], VirtualFile[], VirtualFile[]> cached = myCachedThings;
return timeStamp == myVirtualFilePointerManager.getModificationCount() ? cached : cacheThings();
}
private static final Trinity<String[], VirtualFile[], VirtualFile[]> EMPTY =
Trinity.create(ArrayUtil.EMPTY_STRING_ARRAY, VirtualFile.EMPTY_ARRAY, VirtualFile.EMPTY_ARRAY);
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> cacheThings() {
Trinity<String[], VirtualFile[], VirtualFile[]> result;
if (myList.isEmpty()) {
result = EMPTY;
}
else {
VirtualFilePointer[] vf = myList.toArray(new VirtualFilePointer[myList.size()]);
List<VirtualFile> cachedFiles = new ArrayList<VirtualFile>(vf.length);
List<String> cachedUrls = new ArrayList<String>(vf.length);
List<VirtualFile> cachedDirectories = new ArrayList<VirtualFile>(vf.length / 3);
boolean allFilesAreDirs = true;
for (VirtualFilePointer v : vf) {
VirtualFile file = v.getFile();
String url = v.getUrl();
cachedUrls.add(url);
if (file != null) {
cachedFiles.add(file);
if (file.isDirectory()) {
cachedDirectories.add(file);
}
else {
allFilesAreDirs = false;
}
}
}
VirtualFile[] directories = VfsUtilCore.toVirtualFileArray(cachedDirectories);
VirtualFile[] files = allFilesAreDirs ? directories : VfsUtilCore.toVirtualFileArray(cachedFiles);
String[] urlsArray = ArrayUtil.toStringArray(cachedUrls);
result = Trinity.create(urlsArray, files, directories);
}
myCachedThings = result;
myTimeStampOfCachedThings = myVirtualFilePointerManager.getModificationCount();
return result;
}
@Override
@NotNull
public VirtualFile[] getFiles() {
return getOrCache().second;
}
@Override
@NotNull
public VirtualFile[] getDirectories() {
return getOrCache().third;
}
@Override
@Nullable
public VirtualFilePointer findByUrl(@NotNull String url) {
assert !myDisposed;
for (VirtualFilePointer pointer : myList) {
if (url.equals(pointer.getUrl())) return pointer;
}
return null;
}
@Override
public void clear() {
dropCaches();
killAll();
}
@Override
public int size() {
return myList.size();
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VirtualFilePointerContainerImpl)) return false;
final VirtualFilePointerContainerImpl virtualFilePointerContainer = (VirtualFilePointerContainerImpl)o;
return myList.equals(virtualFilePointerContainer.myList);
}
public int hashCode() {
return myList.hashCode();
}
protected VirtualFilePointer create(@NotNull VirtualFile file) {
return myVirtualFilePointerManager.create(file, myParent, myListener);
}
protected VirtualFilePointer create(@NotNull String url) {
return myVirtualFilePointerManager.create(url, myParent, myListener);
}
protected VirtualFilePointer duplicate(@NotNull VirtualFilePointer virtualFilePointer) {
return myVirtualFilePointerManager.duplicate(virtualFilePointer, myParent, myListener);
}
@NotNull
@NonNls
@Override
public String toString() {
return "VFPContainer: " + myList/*+"; parent:"+myParent*/;
}
@Override
@NotNull
public VirtualFilePointerContainer clone(@NotNull Disposable parent) {
return clone(parent, null);
}
@Override
@NotNull
public VirtualFilePointerContainer clone(@NotNull Disposable parent, @Nullable VirtualFilePointerListener listener) {
assert !myDisposed;
VirtualFilePointerContainer clone = myVirtualFilePointerManager.createContainer(parent, listener);
for (VirtualFilePointer pointer : myList) {
clone.add(pointer.getUrl());
}
return clone;
}
@Override
public void dispose() {
assert !myDisposed;
myDisposed = true;
kill(null);
}
}
| platform/core-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.TraceableDisposable;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author dsl
*/
public class VirtualFilePointerContainerImpl extends TraceableDisposable implements VirtualFilePointerContainer, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer");
@NotNull private final List<VirtualFilePointer> myList = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final VirtualFilePointerManager myVirtualFilePointerManager;
@NotNull private final Disposable myParent;
private final VirtualFilePointerListener myListener;
private volatile Trinity<String[], VirtualFile[], VirtualFile[]> myCachedThings;
private volatile long myTimeStampOfCachedThings = -1;
@NonNls public static final String URL_ATTR = "url";
private boolean myDisposed;
private static final boolean TRACE_CREATION = LOG.isDebugEnabled() || ApplicationManager.getApplication().isUnitTestMode();
public VirtualFilePointerContainerImpl(@NotNull VirtualFilePointerManager manager,
@NotNull Disposable parentDisposable,
@Nullable VirtualFilePointerListener listener) {
//noinspection HardCodedStringLiteral
super(TRACE_CREATION
? new Throwable("parent = '" + parentDisposable + "' (" + parentDisposable.getClass() + "); listener=" + listener)
: null);
myVirtualFilePointerManager = manager;
myParent = parentDisposable;
myListener = listener;
}
@Override
public void readExternal(@NotNull final Element rootChild, @NotNull final String childElements) throws InvalidDataException {
final List urls = rootChild.getChildren(childElements);
for (Object url : urls) {
Element pathElement = (Element)url;
final String urlAttribute = pathElement.getAttributeValue(URL_ATTR);
if (urlAttribute == null) throw new InvalidDataException("path element without url");
add(urlAttribute);
}
}
@Override
public void writeExternal(@NotNull final Element element, @NotNull final String childElementName) {
for (VirtualFilePointer pointer : myList) {
String url = pointer.getUrl();
final Element rootPathElement = new Element(childElementName);
rootPathElement.setAttribute(URL_ATTR, url);
element.addContent(rootPathElement);
}
}
@Override
public void moveUp(@NotNull String url) {
int index = indexOf(url);
if (index <= 0) return;
dropCaches();
ContainerUtil.swapElements(myList, index - 1, index);
}
@Override
public void moveDown(@NotNull String url) {
int index = indexOf(url);
if (index < 0 || index + 1 >= myList.size()) return;
dropCaches();
ContainerUtil.swapElements(myList, index, index + 1);
}
private int indexOf(@NotNull final String url) {
for (int i = 0; i < myList.size(); i++) {
final VirtualFilePointer pointer = myList.get(i);
if (url.equals(pointer.getUrl())) {
return i;
}
}
return -1;
}
@Override
public void killAll() {
myList.clear();
}
@Override
public void add(@NotNull VirtualFile file) {
assert !myDisposed;
dropCaches();
final VirtualFilePointer pointer = create(file);
myList.add(pointer);
}
@Override
public void add(@NotNull String url) {
assert !myDisposed;
dropCaches();
final VirtualFilePointer pointer = create(url);
myList.add(pointer);
}
@Override
public void remove(@NotNull VirtualFilePointer pointer) {
assert !myDisposed;
dropCaches();
final boolean result = myList.remove(pointer);
LOG.assertTrue(result);
}
@Override
@NotNull
public List<VirtualFilePointer> getList() {
assert !myDisposed;
return Collections.unmodifiableList(myList);
}
@Override
public void addAll(@NotNull VirtualFilePointerContainer that) {
assert !myDisposed;
dropCaches();
List<VirtualFilePointer> thatList = ((VirtualFilePointerContainerImpl)that).myList;
for (final VirtualFilePointer pointer : thatList) {
myList.add(duplicate(pointer));
}
}
private void dropCaches() {
myTimeStampOfCachedThings = -1; // make it never equal to myVirtualFilePointerManager.getModificationCount()
}
@Override
@NotNull
public String[] getUrls() {
return getOrCache().first;
}
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> getOrCache() {
assert !myDisposed;
long timeStamp = myTimeStampOfCachedThings;
Trinity<String[], VirtualFile[], VirtualFile[]> cached = myCachedThings;
return timeStamp == myVirtualFilePointerManager.getModificationCount() ? cached : cacheThings();
}
private static final Trinity<String[], VirtualFile[], VirtualFile[]> EMPTY =
Trinity.create(ArrayUtil.EMPTY_STRING_ARRAY, VirtualFile.EMPTY_ARRAY, VirtualFile.EMPTY_ARRAY);
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> cacheThings() {
Trinity<String[], VirtualFile[], VirtualFile[]> result;
if (myList.isEmpty()) {
result = EMPTY;
}
else {
VirtualFilePointer[] vf = myList.toArray(new VirtualFilePointer[myList.size()]);
List<VirtualFile> cachedFiles = new ArrayList<VirtualFile>(vf.length);
List<String> cachedUrls = new ArrayList<String>(vf.length);
List<VirtualFile> cachedDirectories = new ArrayList<VirtualFile>(vf.length / 3);
boolean allFilesAreDirs = true;
for (VirtualFilePointer v : vf) {
VirtualFile file = v.getFile();
String url = v.getUrl();
cachedUrls.add(url);
if (file != null) {
cachedFiles.add(file);
if (file.isDirectory()) {
cachedDirectories.add(file);
}
else {
allFilesAreDirs = false;
}
}
}
VirtualFile[] directories = VfsUtilCore.toVirtualFileArray(cachedDirectories);
VirtualFile[] files = allFilesAreDirs ? directories : VfsUtilCore.toVirtualFileArray(cachedFiles);
String[] urlsArray = ArrayUtil.toStringArray(cachedUrls);
result = Trinity.create(urlsArray, files, directories);
}
myCachedThings = result;
myTimeStampOfCachedThings = myVirtualFilePointerManager.getModificationCount();
return result;
}
@Override
@NotNull
public VirtualFile[] getFiles() {
return getOrCache().second;
}
@Override
@NotNull
public VirtualFile[] getDirectories() {
return getOrCache().third;
}
@Override
@Nullable
public VirtualFilePointer findByUrl(@NotNull String url) {
assert !myDisposed;
for (VirtualFilePointer pointer : myList) {
if (url.equals(pointer.getUrl())) return pointer;
}
return null;
}
@Override
public void clear() {
dropCaches();
killAll();
}
@Override
public int size() {
return myList.size();
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VirtualFilePointerContainerImpl)) return false;
final VirtualFilePointerContainerImpl virtualFilePointerContainer = (VirtualFilePointerContainerImpl)o;
return myList.equals(virtualFilePointerContainer.myList);
}
public int hashCode() {
return myList.hashCode();
}
protected VirtualFilePointer create(@NotNull VirtualFile file) {
return myVirtualFilePointerManager.create(file, myParent, myListener);
}
protected VirtualFilePointer create(@NotNull String url) {
return myVirtualFilePointerManager.create(url, myParent, myListener);
}
protected VirtualFilePointer duplicate(@NotNull VirtualFilePointer virtualFilePointer) {
return myVirtualFilePointerManager.duplicate(virtualFilePointer, myParent, myListener);
}
@NotNull
@NonNls
@Override
public String toString() {
return "VFPContainer: " + myList/*+"; parent:"+myParent*/;
}
@Override
@NotNull
public VirtualFilePointerContainer clone(@NotNull Disposable parent) {
return clone(parent, null);
}
@Override
@NotNull
public VirtualFilePointerContainer clone(@NotNull Disposable parent, @Nullable VirtualFilePointerListener listener) {
assert !myDisposed;
VirtualFilePointerContainer clone = myVirtualFilePointerManager.createContainer(parent, listener);
for (VirtualFilePointer pointer : myList) {
clone.add(pointer.getUrl());
}
return clone;
}
@Override
public void dispose() {
assert !myDisposed;
myDisposed = true;
kill(null);
}
}
| memory optimisation: do not leave stale data in cache
| platform/core-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java | memory optimisation: do not leave stale data in cache | <ide><path>latform/core-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java
<ide> /*
<del> * Copyright 2000-2012 JetBrains s.r.o.
<add> * Copyright 2000-2014 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> @NonNls public static final String URL_ATTR = "url";
<ide> private boolean myDisposed;
<ide> private static final boolean TRACE_CREATION = LOG.isDebugEnabled() || ApplicationManager.getApplication().isUnitTestMode();
<del>
<ide> public VirtualFilePointerContainerImpl(@NotNull VirtualFilePointerManager manager,
<ide> @NotNull Disposable parentDisposable,
<ide> @Nullable VirtualFilePointerListener listener) {
<ide>
<ide> private void dropCaches() {
<ide> myTimeStampOfCachedThings = -1; // make it never equal to myVirtualFilePointerManager.getModificationCount()
<add> myCachedThings = EMPTY;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 47106676c99f77d93ae870a833933442352283b9 | 0 | jtablesaw/tablesaw,jtablesaw/tablesaw,jtablesaw/tablesaw | package tech.tablesaw.io;
import java.util.HashMap;
import java.util.Map;
public class ReaderRegistry {
private final Map<String, DataReader<?>> optionTypesRegistry = new HashMap<>();
private final Map<String, DataReader<?>> extensionsRegistry = new HashMap<>();
private final Map<String, DataReader<?>> mimeTypesRegistry = new HashMap<>();
public void registerOptions(Class<? extends ReadOptions> optionsType, DataReader<?> reader) {
optionTypesRegistry.put(optionsType.getCanonicalName(), reader);
}
public void registerExtension(String extension, DataReader<?> reader) {
extensionsRegistry.put(extension, reader);
}
public void registerMimeType(String mimeType, DataReader<?> reader) {
mimeTypesRegistry.put(mimeType, reader);
}
@SuppressWarnings("unchecked")
public <T extends ReadOptions> DataReader<T> getReaderForOptions(T options) {
String clazz = options.getClass().getCanonicalName();
DataReader<T> reader = (DataReader<T>) optionTypesRegistry.get(clazz);
if (reader == null) {
throw new IllegalArgumentException("No reader registered for class " + clazz);
}
return reader;
}
public DataReader<?> getReaderForExtension(String extension) {
DataReader<?> reader = extensionsRegistry.get(extension);
if (reader == null) {
throw new IllegalArgumentException("No reader registered for extension " + extension);
}
return reader;
}
public DataReader<?> getReaderForMimeType(String mimeType) {
DataReader<?> reader = mimeTypesRegistry.get(mimeType);
if (reader == null) {
throw new IllegalArgumentException("No reader registered for mime-type " + mimeType);
}
return reader;
}
}
| core/src/main/java/tech/tablesaw/io/ReaderRegistry.java | package tech.tablesaw.io;
import java.util.HashMap;
import java.util.Map;
public class ReaderRegistry {
private final Map<String, DataReader<?>> optionTypesRegistry = new HashMap<>();
private final Map<String, DataReader<?>> extensionsRegistry = new HashMap<>();
private final Map<String, DataReader<?>> mimeTypesRegistry = new HashMap<>();
public void registerOptions(Class<? extends ReadOptions> optionsType, DataReader<?> reader) {
optionTypesRegistry.put(optionsType.getCanonicalName(), reader);
}
public void registerExtension(String extension, DataReader<?> reader) {
extensionsRegistry.put(extension, reader);
}
public void registerMimeType(String mimeType, DataReader<?> reader) {
mimeTypesRegistry.put(mimeType, reader);
}
@SuppressWarnings("unchecked")
public <T extends ReadOptions> DataReader<T> getReaderForOptions(T options) {
return (DataReader<T>) optionTypesRegistry.get(options.getClass().getCanonicalName());
}
public DataReader<?> getReaderForExtension(String extension) {
return extensionsRegistry.get(extension);
}
public DataReader<?> getReaderForMimeType(String mimeType) {
return mimeTypesRegistry.get(mimeType);
}
}
| Additional DataFrameReader parameter validation
| core/src/main/java/tech/tablesaw/io/ReaderRegistry.java | Additional DataFrameReader parameter validation | <ide><path>ore/src/main/java/tech/tablesaw/io/ReaderRegistry.java
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> public <T extends ReadOptions> DataReader<T> getReaderForOptions(T options) {
<del> return (DataReader<T>) optionTypesRegistry.get(options.getClass().getCanonicalName());
<add> String clazz = options.getClass().getCanonicalName();
<add> DataReader<T> reader = (DataReader<T>) optionTypesRegistry.get(clazz);
<add> if (reader == null) {
<add> throw new IllegalArgumentException("No reader registered for class " + clazz);
<add> }
<add> return reader;
<ide> }
<ide>
<ide> public DataReader<?> getReaderForExtension(String extension) {
<del> return extensionsRegistry.get(extension);
<add> DataReader<?> reader = extensionsRegistry.get(extension);
<add> if (reader == null) {
<add> throw new IllegalArgumentException("No reader registered for extension " + extension);
<add> }
<add> return reader;
<ide> }
<ide>
<ide> public DataReader<?> getReaderForMimeType(String mimeType) {
<del> return mimeTypesRegistry.get(mimeType);
<add> DataReader<?> reader = mimeTypesRegistry.get(mimeType);
<add> if (reader == null) {
<add> throw new IllegalArgumentException("No reader registered for mime-type " + mimeType);
<add> }
<add> return reader;
<ide> }
<ide>
<ide> } |
|
Java | bsd-3-clause | 8fa296aacbb609bfa1b2cc813e598ba15bb9265f | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.ui.search;
/**
* This class remotely searches nanoparticle metadata across the grid based on user supplied criteria
*
* @author pansu
*/
/* CVS $Id: RemoteSearchNanoparticleAction.java,v 1.3 2007-03-09 22:39:37 pansu Exp $ */
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.dto.remote.GridNodeBean;
import gov.nih.nci.calab.service.remote.GridService;
import gov.nih.nci.calab.service.search.GridSearchService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class RemoteSearchNanoparticleAction extends AbstractDispatchAction {
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String[] functionTypes = (String[]) theForm.get("functionTypes");
String[] characterizations = (String[]) theForm
.get("characterizations");
String[] gridNodeHosts = (String[]) theForm.get("gridNodes");
Map<String, GridNodeBean> gridNodeMap = new HashMap<String, GridNodeBean>(
(Map<? extends String, ? extends GridNodeBean>) request
.getSession().getAttribute("allGridNodes"));
GridNodeBean[] gridNodes = GridService.getGridNodesFromHostNames(
gridNodeMap, gridNodeHosts);
GridSearchService searchService = new GridSearchService();
List<ParticleBean> particles = searchService.getRemoteNanoparticles(
particleType, functionTypes, characterizations, gridNodes);
ActionForward forward = null;
ActionMessages msgs = new ActionMessages();
if (particles != null && !particles.isEmpty()) {
request.setAttribute("remoteParticles", particles);
forward = mapping.findForward("success");
} else {
// ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"message.searchNanoparticle.noresult");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.getInputForward();
}
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Map<String, GridNodeBean> gridNodes = GridService.discoverServices(
CaNanoLabConstants.GRID_INDEX_SERVICE_URL,
CaNanoLabConstants.DOMAIN_MODEL_NAME);
request.getSession().setAttribute("allGridNodes", gridNodes);
InitSessionSetup.getInstance().setAllParticleFunctionTypes(session);
InitSessionSetup.getInstance()
.setCharacterizationTypeCharacterizations(session);
InitSessionSetup.getInstance().clearWorkflowSession(session);
InitSessionSetup.getInstance().clearInventorySession(session);
return mapping.getInputForward();
}
public boolean loginRequired() {
return true;
}
}
| src/gov/nih/nci/calab/ui/search/RemoteSearchNanoparticleAction.java | package gov.nih.nci.calab.ui.search;
/**
* This class remotely searches nanoparticle metadata across the grid based on user supplied criteria
*
* @author pansu
*/
/* CVS $Id: RemoteSearchNanoparticleAction.java,v 1.2 2007-03-08 16:48:58 pansu Exp $ */
import gov.nih.nci.calab.dto.common.GridNodeBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.service.remote.GridService;
import gov.nih.nci.calab.service.search.GridSearchService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class RemoteSearchNanoparticleAction extends AbstractDispatchAction {
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
String[] functionTypes = (String[]) theForm.get("functionTypes");
String[] characterizations = (String[]) theForm
.get("characterizations");
String[] gridNodeHosts = (String[]) theForm.get("gridNodes");
Map<String, GridNodeBean> gridNodeMap = new HashMap<String, GridNodeBean>(
(Map<? extends String, ? extends GridNodeBean>) request
.getSession().getAttribute("allGridNodes"));
GridNodeBean[] gridNodes = GridService.getGridNodesFromHostNames(
gridNodeMap, gridNodeHosts);
GridSearchService searchService = new GridSearchService();
List<ParticleBean> particles = searchService.getRemoteNanoparticles(
particleType, functionTypes, characterizations, gridNodes);
ActionForward forward = null;
ActionMessages msgs = new ActionMessages();
if (particles != null && !particles.isEmpty()) {
request.setAttribute("remoteParticles", particles);
forward = mapping.findForward("success");
} else {
// ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"message.searchNanoparticle.noresult");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.getInputForward();
}
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Map<String, GridNodeBean> gridNodes = GridService.discoverServices(
CaNanoLabConstants.GRID_INDEX_SERVICE_URL,
CaNanoLabConstants.DOMAIN_MODEL_NAME);
request.getSession().setAttribute("allGridNodes", gridNodes);
InitSessionSetup.getInstance().setAllParticleFunctionTypes(session);
InitSessionSetup.getInstance()
.setCharacterizationTypeCharacterizations(session);
InitSessionSetup.getInstance().clearWorkflowSession(session);
InitSessionSetup.getInstance().clearInventorySession(session);
return mapping.getInputForward();
}
public boolean loginRequired() {
return true;
}
}
| updated gridNodeBean
SVN-Revision: 9617
| src/gov/nih/nci/calab/ui/search/RemoteSearchNanoparticleAction.java | updated gridNodeBean | <ide><path>rc/gov/nih/nci/calab/ui/search/RemoteSearchNanoparticleAction.java
<ide> * @author pansu
<ide> */
<ide>
<del>/* CVS $Id: RemoteSearchNanoparticleAction.java,v 1.2 2007-03-08 16:48:58 pansu Exp $ */
<add>/* CVS $Id: RemoteSearchNanoparticleAction.java,v 1.3 2007-03-09 22:39:37 pansu Exp $ */
<ide>
<del>import gov.nih.nci.calab.dto.common.GridNodeBean;
<ide> import gov.nih.nci.calab.dto.particle.ParticleBean;
<add>import gov.nih.nci.calab.dto.remote.GridNodeBean;
<ide> import gov.nih.nci.calab.service.remote.GridService;
<ide> import gov.nih.nci.calab.service.search.GridSearchService;
<ide> import gov.nih.nci.calab.service.util.CaNanoLabConstants; |
|
Java | apache-2.0 | 15abc9fa8aca470fc0cac3c75bcc8b3b5c839a15 | 0 | quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus | package org.jboss.shamrock.maven.runner;
import java.io.Closeable;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import org.jboss.shamrock.deployment.ArchiveContextBuilder;
import org.jboss.shamrock.runtime.Timing;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
/**
* The main entry point for the run mojo execution
*/
public class RunMojoMain {
private static CountDownLatch awaitChangeLatch = null;
private static CountDownLatch awaitRestartLatch = null;
private static volatile boolean keepCl = false;
private static volatile ClassLoader currentAppClassLoader;
public static void main(String... args) throws Exception {
Timing.staticInitStarted();
//the path that contains the compiled classes
File classesRoot = new File(args[0]);
File wiringDir = new File(args[1]);
URLClassLoader runtimeCl = null;
do {
if (runtimeCl == null || !keepCl) {
runtimeCl = new URLClassLoader(new URL[]{classesRoot.toURL()}, ClassLoader.getSystemClassLoader());
}
URL resource = runtimeCl.getResource("logback.xml"); //TODO: this is temporary, until David's logging thing comes it, but not having it is super annoying for demos
if(resource != null) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator configurator = new JoranConfigurator();
try (InputStream configStream = resource.openStream()) {
configurator.setContext(loggerContext);
configurator.doConfigure(configStream); // loads logback file
}
}
currentAppClassLoader = runtimeCl;
ClassLoader old = Thread.currentThread().getContextClassLoader();
//we can potentially throw away this class loader, and reload the app
synchronized (RunMojoMain.class) {
awaitChangeLatch = new CountDownLatch(1);
}
try {
Thread.currentThread().setContextClassLoader(runtimeCl);
Class<?> runnerClass = runtimeCl.loadClass("org.jboss.shamrock.runner.RuntimeRunner");
ArchiveContextBuilder acb = new ArchiveContextBuilder();
Constructor ctor = runnerClass.getDeclaredConstructor( ClassLoader.class, Path.class, Path.class, ArchiveContextBuilder.class);
Object runner = ctor.newInstance( runtimeCl, classesRoot.toPath(), wiringDir.toPath(), acb);
((Runnable) runner).run();
synchronized (RunMojoMain.class) {
if (awaitRestartLatch != null) {
awaitRestartLatch.countDown();
awaitRestartLatch = null;
}
}
awaitChangeLatch.await();
((Closeable) runner).close();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
} while (true);
}
public static void restartApp(boolean keepClassloader) {
keepCl = keepClassloader;
Timing.restart();
CountDownLatch restart = null;
synchronized (RunMojoMain.class) {
if (awaitChangeLatch != null) {
restart = awaitRestartLatch = new CountDownLatch(1);
awaitChangeLatch.countDown();
}
awaitChangeLatch = null;
}
if (restart != null) {
try {
restart.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static ClassLoader getCurrentAppClassLoader() {
return currentAppClassLoader;
}
}
| maven/src/main/java/org/jboss/shamrock/maven/runner/RunMojoMain.java | package org.jboss.shamrock.maven.runner;
import java.io.Closeable;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import org.jboss.shamrock.deployment.ArchiveContextBuilder;
import org.jboss.shamrock.runtime.Timing;
/**
* The main entry point for the run mojo execution
*/
public class RunMojoMain {
private static CountDownLatch awaitChangeLatch = null;
private static CountDownLatch awaitRestartLatch = null;
private static volatile boolean keepCl = false;
private static volatile ClassLoader currentAppClassLoader;
public static void main(String... args) throws Exception {
Timing.staticInitStarted();
//the path that contains the compiled classes
File classesRoot = new File(args[0]);
File wiringDir = new File(args[1]);
URLClassLoader runtimeCl = null;
do {
if (runtimeCl == null || !keepCl) {
runtimeCl = new URLClassLoader(new URL[]{classesRoot.toURL()}, ClassLoader.getSystemClassLoader());
}
currentAppClassLoader = runtimeCl;
ClassLoader old = Thread.currentThread().getContextClassLoader();
//we can potentially throw away this class loader, and reload the app
synchronized (RunMojoMain.class) {
awaitChangeLatch = new CountDownLatch(1);
}
try {
Thread.currentThread().setContextClassLoader(runtimeCl);
Class<?> runnerClass = runtimeCl.loadClass("org.jboss.shamrock.runner.RuntimeRunner");
ArchiveContextBuilder acb = new ArchiveContextBuilder();
Constructor ctor = runnerClass.getDeclaredConstructor( ClassLoader.class, Path.class, Path.class, ArchiveContextBuilder.class);
Object runner = ctor.newInstance( runtimeCl, classesRoot.toPath(), wiringDir.toPath(), acb);
((Runnable) runner).run();
synchronized (RunMojoMain.class) {
if (awaitRestartLatch != null) {
awaitRestartLatch.countDown();
awaitRestartLatch = null;
}
}
awaitChangeLatch.await();
((Closeable) runner).close();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
} while (true);
}
public static void restartApp(boolean keepClassloader) {
keepCl = keepClassloader;
Timing.restart();
CountDownLatch restart = null;
synchronized (RunMojoMain.class) {
if (awaitChangeLatch != null) {
restart = awaitRestartLatch = new CountDownLatch(1);
awaitChangeLatch.countDown();
}
awaitChangeLatch = null;
}
if (restart != null) {
try {
restart.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static ClassLoader getCurrentAppClassLoader() {
return currentAppClassLoader;
}
}
| Make logback work when using shamrock:run
This should be temporary but it is annoying enough to fix now
| maven/src/main/java/org/jboss/shamrock/maven/runner/RunMojoMain.java | Make logback work when using shamrock:run | <ide><path>aven/src/main/java/org/jboss/shamrock/maven/runner/RunMojoMain.java
<ide>
<ide> import java.io.Closeable;
<ide> import java.io.File;
<add>import java.io.InputStream;
<ide> import java.lang.reflect.Constructor;
<ide> import java.net.URL;
<ide> import java.net.URLClassLoader;
<ide>
<ide> import org.jboss.shamrock.deployment.ArchiveContextBuilder;
<ide> import org.jboss.shamrock.runtime.Timing;
<add>import org.slf4j.LoggerFactory;
<add>
<add>import ch.qos.logback.classic.LoggerContext;
<add>import ch.qos.logback.classic.joran.JoranConfigurator;
<ide>
<ide> /**
<ide> * The main entry point for the run mojo execution
<ide> if (runtimeCl == null || !keepCl) {
<ide> runtimeCl = new URLClassLoader(new URL[]{classesRoot.toURL()}, ClassLoader.getSystemClassLoader());
<ide> }
<add> URL resource = runtimeCl.getResource("logback.xml"); //TODO: this is temporary, until David's logging thing comes it, but not having it is super annoying for demos
<add> if(resource != null) {
<add> LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
<add> loggerContext.reset();
<add> JoranConfigurator configurator = new JoranConfigurator();
<add> try (InputStream configStream = resource.openStream()) {
<add> configurator.setContext(loggerContext);
<add> configurator.doConfigure(configStream); // loads logback file
<add> }
<add> }
<add>
<ide> currentAppClassLoader = runtimeCl;
<ide> ClassLoader old = Thread.currentThread().getContextClassLoader();
<ide> //we can potentially throw away this class loader, and reload the app |
|
JavaScript | mit | a71b6b5a5375b63479ff1d1dcd0d5f24d6da1d58 | 0 | ColorfulCakeChen/query-submit-canvas,ColorfulCakeChen/query-submit-canvas | export { Same, Bool, Int };
/**
* Provides methods for converting nothing (just return original value).
*/
class Same {
/** @return {any} Return the input value directly. */
adjust( value ) {
return value;
}
/**
* @return {function}
* Return a function object. When calling the returned function object with one value parameter, it will return
* the adjusted value which is retricted by this object.
*/
getAdjuster() {
return this.adjust.bind( this );
}
/**
* Return a generator which produces a sequence of two-value pair.
*
* For ValueRange.Same, there is no meaningful testable value pair could be generated. The reason is that any value is legal for it.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -10, +10 ). The -10 and +10 is just chosen arbitrarily.
*
* @yield {object}
* Every time yield an array with two number properties: { valueInput, valueOutput }. The valueOutput is a value from valueRangeMin to
* valueRangeMax. The valueInput is a value which could be adjusted to valueOutput by this ValueRange object.
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -10, +10 ) ) {
yield { valueInput: offsetMultiplier, valueOutput: offsetMultiplier };
}
/**
* Return a random integer between min and max. (This function comes from MDN's Math.random().)
*
* @param {number} min The the minimum integer. (inclusive)
* @param {number} max The the maximum integer. (inclusive)
*/
static getRandomIntInclusive( min, max ) {
let minReal = Math.min( min, max );
let maxReal = Math.max( min, max );
let minInt = Math.ceil( minReal );
let maxInt = Math.floor( maxReal );
let kindsInt = maxInt - minInt + 1;
return Math.floor( ( Math.random() * kindsInt ) + minInt );
}
}
/** The only one ValueRange.Same instance. */
Same.Singleton = new Same;
/**
* Provides methods for converting weight (a number) to boolean.
*/
class Bool extends Same {
constructor( min, max ) {
super();
this.kinds = 2; // Boolean has only two kinds.
}
/** @return {boolean} Convert number value into false or true. */
adjust( value ) {
// If value is not an integer, the remainder will always not zero. So convert it to integer first.
//
// According to negative or positive, the remainder could be one of [ -1, 0, +1 ].
// So simply check it whether is 0 (instead of check both -1 and +1), could result in false or true.
return ( ( Math.trunc( value ) % 2 ) != 0 );
}
/**
* For ValueRange.Bool, two two-value pairs will be generated in sequence.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -100, +100 ). The -100 and +100 is just chosen arbitrarily.
*
* @param {number} maxKinds
* An integer restricts the generator range to [ 0, maxKinds ] instead of [ 0, this.kinds ]. Default is this.kinds.
* When this.kinds is large, this parameter could lower the kinds to reduce test cases quantity. If zero or negative,
* only one value (between [ 0, this.kinds ] randomly) will be generated.
*
* @override
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -100, +100 ), maxKinds = this.kinds ) {
let baseInt = Math.trunc( offsetMultiplier );
let baseIntEven = baseInt * 2; // Any integer multiplied by 2 will be an even number.
let baseIntEvenSign = Math.sign( baseIntEven );
// If no sign (i.e. baseIntEven is zero), choose positive sign. Otherwise, there will no fractional part at all.
if ( baseIntEvenSign == 0 ) {
baseIntEvenSign = 1;
}
// A: Why not use Math.random() to generate value between [ 0, 1 ) directly?
// Q: In order to avoid rounded into another integer when converted from Float64 (here) to Float32 (weights array),
// the random value should not too close to 1. For example, 1.9999999999999999999 might become 2.0 when converted
// from Float64 to Float32.
let randomFractionalPart1 = Same.getRandomIntInclusive( 0, 99 ) / 1000;
let randomFractionalPart2 = Same.getRandomIntInclusive( 0, 99 ) / 1000;
// An even value with fractional part will become 0 by Bool.adjust().
let valueInputZero = ( baseIntEven + 0 ) + ( baseIntEvenSign * randomFractionalPart1 );
let valueInputOutputZero = { valueInput: valueInputZero, valueOutput: 0 };
// A odd value with fractional part will become 1 by Bool.adjust().
let valueInputOne = ( baseIntEven + 1 ) + ( baseIntEvenSign * randomFractionalPart2 );
let valueInputOutputOne = { valueInput: valueInputOne, valueOutput: 1 };
// Yield according to maxKinds.
if ( maxKinds >= 2 ) {
yield valueInputOutputZero; // Both zero and one.
yield valueInputOutputOne;
} else if ( maxKinds >= 1 ) {
yield valueInputOutputZero; // Always zero. (Although, not so meaningful.)
//yield valueInputOutputOne;
} else {
let index = Same.getRandomIntInclusive( 0, ( this.kinds - 1 ) );
if ( index == 0 )
yield valueInputOutputZero; // Randomly choose zero.
else
yield valueInputOutputOne; // Randomly choose one.
}
}
}
/** The only one ValueRange.Bool instance. */
Bool.Singleton = new Bool;
/**
* Provides methods for converting weight (a number) to integer between min and max (both are integers).
*/
class Int extends Same {
/**
* @param {number} min The minimum value (as integer).
* @param {number} max The maximum value (as integer).
*/
constructor( min, max ) {
super();
this.min = Math.trunc( Math.min( min, max ) ); // Confirm the minimum. Convert to an integer.
this.max = Math.trunc( Math.max( min, max ) ); // Confirm the maximum. Convert to an integer.
this.kinds = ( this.max - this.min ) + 1; // How many possible integer between them.
}
/**
* @return {number} Return the trucated value (i.e. integer). The returned value is forcibly between min and max (as integer too).
*/
adjust( value ) {
let valueInt = Math.trunc( value ); // Convert to an integer.
// Rearrange valueInt between min and max fairly (in probability).
//
// A1: Why not use remainder operator (%) directly?
// Q1: Because remainder always has the same sign as dividend, this can not handle the situation which min and
// max have different sign.
//
// A2: Why not just restrict all value less than min to valueMin and value greater than max to max?
// Q2: Although this could restrict value in range, it will skew the probability of every value in the range.
// Unfair probability could be harmful to evolution algorithm.
//
let quotient = ( valueInt - this.min ) / this.kinds;
let quotientInt = Math.floor( quotient ); // So that negative value could be handled correctly.
let result = valueInt - ( quotientInt * this.kinds );
return result;
}
/**
* @param {number} baseIntCongruence
* An integer which is divisible by this.kinds. This will be used to offset the index value to generate valueInput.
*
* @param {number} index
* An integer between [ 0, this.kinds ).
*
* @return {object}
* Return an object { valueInput, valueOutput }. The valueInput is a floating-point value composed from baseIntCongruence, this.min
* and index. The valueOutput is an integer value. When call this.adjust( valueInput ) will return valueOutput.
*/
get_valueInputOutput_byIndex( baseIntCongruence, index ) {
let valueOutputInt = ( this.min + index );
// An integer which could become valueOutputInt when adjusted by Int.adjust().
let valueInputInt = baseIntCongruence + valueOutputInt;
let valueInputIntSign = Math.sign( valueInputInt );
// If no sign (i.e. valueInputInt is zero), choose positive sign. Otherwise, there will no fractional part at all.
if ( valueInputIntSign == 0 ) {
valueInputIntSign = 1;
}
// A: Why not use Math.random() to generate value between [ 0, 1 ) directly?
// Q: In order to avoid rounded into another integer when converted from Float64 (here) to Float32 (weights array),
// the random value should not too close to 1. For example, 1.9999999999999999999 might become 2.0 when converted
// from Float64 to Float32.
let randomFractionalPart = Same.getRandomIntInclusive( 0, 99 ) / 1000;
// An floating-point number (the integer with fractional part) which could become valueOutputInt when adjusted by Int.adjust().
let valueInputFloat = valueInputInt + ( valueInputIntSign * randomFractionalPart );
//!!! (2021/07/06 Temp Test) When the random fractional part is converted (from Float64) into Float32, it might shifted to different value.
//if ( this.adjust( new Float32Array( [ valueInputFloat ] )[ 0 ] ) != valueOutputInt )
// debugger;
return { valueInput: valueInputFloat, valueOutput: valueOutputInt };
}
/**
* For ValueRange.Int, this.kinds two-value pairs will be generated in sequence.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -10, +10 ). The -10 and +10 is just chosen arbitrarily.
*
* @param {number} maxKinds
* An integer restricts the generator range to [ 0, maxKinds ] instead of [ 0, this.kinds ]. Default is this.kinds.
* When this.kinds is large, this parameter could lower the kinds to reduce test cases quantity. If zero or negative,
* only one value (between [ 0, this.kinds ] randomly) will be generated.
*
* @override
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -10, +10 ), maxKinds = this.kinds ) {
// An integer which has the same remainder as offsetMultiplier when divided by this.kinds.
let baseIntCongruence = Math.trunc( offsetMultiplier ) * this.kinds;
if ( maxKinds > 0 ) {
let testKinds = Math.min( maxKinds, this.kinds );
for ( let i = 0; i < testKinds; ++i ) {
let valueInputOutput = this.get_valueInputOutput_byIndex( baseIntCongruence, i );
yield valueInputOutput;
}
} else {
let index = Same.getRandomIntInclusive( 0, ( this.kinds - 1 ) );
let valueInputOutput = this.get_valueInputOutput_byIndex( baseIntCongruence, index );
yield valueInputOutput;
}
}
}
| CNN/Unpacker/ValueRange.js | export { Same, Bool, Int };
/**
* Provides methods for converting nothing (just return original value).
*/
class Same {
/** @return {any} Return the input value directly. */
adjust( value ) {
return value;
}
/**
* @return {function}
* Return a function object. When calling the returned function object with one value parameter, it will return
* the adjusted value which is retricted by this object.
*/
getAdjuster() {
return this.adjust.bind( this );
}
/**
* Return a generator which produces a sequence of two-value pair.
*
* For ValueRange.Same, there is no meaningful testable value pair could be generated. The reason is that any value is legal for it.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -10, +10 ). The -10 and +10 is just chosen arbitrarily.
*
* @yield {object}
* Every time yield an array with two number properties: { valueInput, valueOutput }. The valueOutput is a value from valueRangeMin to
* valueRangeMax. The valueInput is a value which could be adjusted to valueOutput by this ValueRange object.
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -10, +10 ) ) {
yield { valueInput: offsetMultiplier, valueOutput: offsetMultiplier };
}
/**
* Return a random integer between min and max. (This function comes from MDN's Math.random().)
*
* @param {number} min The the minimum integer. (inclusive)
* @param {number} max The the maximum integer. (inclusive)
*/
static getRandomIntInclusive( min, max ) {
let minReal = Math.min( min, max );
let maxReal = Math.max( min, max );
let minInt = Math.ceil( minReal );
let maxInt = Math.floor( maxReal );
let kindsInt = maxInt - minInt + 1;
return Math.floor( ( Math.random() * kindsInt ) + minInt );
}
}
/** The only one ValueRange.Same instance. */
Same.Singleton = new Same;
/**
* Provides methods for converting weight (a number) to boolean.
*/
class Bool extends Same {
constructor( min, max ) {
super();
this.kinds = 2; // Boolean has only two kinds.
}
/** @return {boolean} Convert number value into false or true. */
adjust( value ) {
// If value is not an integer, the remainder will always not zero. So convert it to integer first.
//
// According to negative or positive, the remainder could be one of [ -1, 0, +1 ].
// So simply check it whether is 0 (instead of check both -1 and +1), could result in false or true.
return ( ( Math.trunc( value ) % 2 ) != 0 );
}
/**
* For ValueRange.Bool, two two-value pairs will be generated in sequence.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -100, +100 ). The -100 and +100 is just chosen arbitrarily.
*
* @param {number} maxKinds
* An integer restricts the generator range to [ 0, maxKinds ] instead of [ 0, this.kinds ]. Default is this.kinds.
* When this.kinds is large, this parameter could lower the kinds to reduce test cases quantity. If zero or negative,
* only one value (between [ 0, this.kinds ] randomly) will be generated.
*
* @override
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -100, +100 ), maxKinds = this.kinds ) {
let baseInt = Math.trunc( offsetMultiplier );
let baseIntEven = baseInt * 2; // Any integer multiplied by 2 will be an even number.
let baseIntEvenSign = Math.sign( baseIntEven );
// If no sign (i.e. baseIntEven is zero), choose positive sign. Otherwise, there will no fractional part at all.
if ( baseIntEvenSign == 0 ) {
baseIntEvenSign = 1;
}
// A: Why not use Math.random() to generate value between [ 0, 1 ) directly?
// Q: In order to avoid rounded into another integer when converted from Float64 (here) to Float32 (weights array),
// the random value should not too close to 1. For example, 1.9999999999999999999 might become 2.0 when converted
// from Float64 to Float32.
let randomFractionalPart1 = Same.getRandomIntInclusive( 0, 99 ) / 1000;
let randomFractionalPart2 = Same.getRandomIntInclusive( 0, 99 ) / 1000;
// An even value with fractional part will become 0 by Bool.adjust().
let valueInputZero = ( baseIntEven + 0 ) + ( baseIntEvenSign * randomFractionalPart1 );
let valueInputOutputZero = { valueInput: valueInputZero, valueOutput: 0 };
// A odd value with fractional part will become 1 by Bool.adjust().
let valueInputOne = ( baseIntEven + 1 ) + ( baseIntEvenSign * randomFractionalPart2 );
let valueInputOutputOne = { valueInput: valueInputOne, valueOutput: 1 };
// Yield kinds according to maxKinds.
if ( maxKinds >= 2 ) {
yield valueInputOutputZero; // Both zero and one.
yield valueInputOutputOne;
} else if ( maxKinds >= 1 ) {
yield valueInputOutputZero; // Always zero. (Although, not so meaningful.)
//yield valueInputOutputOne;
} else {
let index = Same.getRandomIntInclusive( 0, ( this.kinds - 1 ) );
if ( index == 0 )
yield valueInputOutputZero; // Randomly choose zero.
else
yield valueInputOutputOne; // Randomly choose one.
}
}
}
/** The only one ValueRange.Bool instance. */
Bool.Singleton = new Bool;
/**
* Provides methods for converting weight (a number) to integer between min and max (both are integers).
*/
class Int extends Same {
/**
* @param {number} min The minimum value (as integer).
* @param {number} max The maximum value (as integer).
*/
constructor( min, max ) {
super();
this.min = Math.trunc( Math.min( min, max ) ); // Confirm the minimum. Convert to an integer.
this.max = Math.trunc( Math.max( min, max ) ); // Confirm the maximum. Convert to an integer.
this.kinds = ( this.max - this.min ) + 1; // How many possible integer between them.
}
/**
* @return {number} Return the trucated value (i.e. integer). The returned value is forcibly between min and max (as integer too).
*/
adjust( value ) {
let valueInt = Math.trunc( value ); // Convert to an integer.
// Rearrange valueInt between min and max fairly (in probability).
//
// A1: Why not use remainder operator (%) directly?
// Q1: Because remainder always has the same sign as dividend, this can not handle the situation which min and
// max have different sign.
//
// A2: Why not just restrict all value less than min to valueMin and value greater than max to max?
// Q2: Although this could restrict value in range, it will skew the probability of every value in the range.
// Unfair probability could be harmful to evolution algorithm.
//
let quotient = ( valueInt - this.min ) / this.kinds;
let quotientInt = Math.floor( quotient ); // So that negative value could be handled correctly.
let result = valueInt - ( quotientInt * this.kinds );
return result;
}
/**
* @param {number} baseIntCongruence
* An integer which is divisible by this.kinds. This will be used to offset the index value to generate valueInput.
*
* @param {number} index
* An integer between [ 0, this.kinds ).
*
* @return {object}
* Return an object { valueInput, valueOutput }. The valueInput is a floating-point value composed from baseIntCongruence, this.min
* and index. The valueOutput is an integer value. When call this.adjust( valueInput ) will return valueOutput.
*/
get_valueInputOutput_byIndex( baseIntCongruence, index ) {
let valueOutputInt = ( this.min + index );
// An integer which could become valueOutputInt when adjusted by Int.adjust().
let valueInputInt = baseIntCongruence + valueOutputInt;
let valueInputIntSign = Math.sign( valueInputInt );
// If no sign (i.e. valueInputInt is zero), choose positive sign. Otherwise, there will no fractional part at all.
if ( valueInputIntSign == 0 ) {
valueInputIntSign = 1;
}
// A: Why not use Math.random() to generate value between [ 0, 1 ) directly?
// Q: In order to avoid rounded into another integer when converted from Float64 (here) to Float32 (weights array),
// the random value should not too close to 1. For example, 1.9999999999999999999 might become 2.0 when converted
// from Float64 to Float32.
let randomFractionalPart = Same.getRandomIntInclusive( 0, 99 ) / 1000;
// An floating-point number (the integer with fractional part) which could become valueOutputInt when adjusted by Int.adjust().
let valueInputFloat = valueInputInt + ( valueInputIntSign * randomFractionalPart );
//!!! (2021/07/06 Temp Test) When the random fractional part is converted (from Float64) into Float32, it might shifted to different value.
//if ( this.adjust( new Float32Array( [ valueInputFloat ] )[ 0 ] ) != valueOutputInt )
// debugger;
return { valueInput: valueInputFloat, valueOutput: valueOutputInt };
}
/**
* For ValueRange.Int, this.kinds two-value pairs will be generated in sequence.
*
* @param {number} offsetMultiplier
* An integer multiplier. The ( offsetMultiplier * this.kinds ) will be used as the first test value. The default value
* is Same.getRandomIntInclusive( -10, +10 ). The -10 and +10 is just chosen arbitrarily.
*
* @param {number} maxKinds
* An integer restricts the generator range to [ 0, maxKinds ] instead of [ 0, this.kinds ]. Default is this.kinds.
* When this.kinds is large, this parameter could lower the kinds to reduce test cases quantity. If zero or negative,
* only one value (between [ 0, this.kinds ] randomly) will be generated.
*
* @override
*/
* valueInputOutputGenerator( offsetMultiplier = Same.getRandomIntInclusive( -10, +10 ), maxKinds = this.kinds ) {
// An integer which has the same remainder as offsetMultiplier when divided by this.kinds.
let baseIntCongruence = Math.trunc( offsetMultiplier ) * this.kinds;
if ( maxKinds > 0 ) {
let testKinds = Math.min( maxKinds, this.kinds );
for ( let i = 0; i < testKinds; ++i ) {
let valueInputOutput = this.get_valueInputOutput_byIndex( baseIntCongruence, i );
yield valueInputOutput;
}
} else {
let index = Same.getRandomIntInclusive( 0, ( this.kinds - 1 ) );
let valueInputOutput = this.get_valueInputOutput_byIndex( baseIntCongruence, index );
yield valueInputOutput;
}
}
}
| Update ValueRange.js | CNN/Unpacker/ValueRange.js | Update ValueRange.js | <ide><path>NN/Unpacker/ValueRange.js
<ide> let valueInputOne = ( baseIntEven + 1 ) + ( baseIntEvenSign * randomFractionalPart2 );
<ide> let valueInputOutputOne = { valueInput: valueInputOne, valueOutput: 1 };
<ide>
<del> // Yield kinds according to maxKinds.
<add> // Yield according to maxKinds.
<ide> if ( maxKinds >= 2 ) {
<ide> yield valueInputOutputZero; // Both zero and one.
<ide> yield valueInputOutputOne; |
|
JavaScript | agpl-3.0 | 0fde5a1b3dac1b53f007154e7d2e5468fc6c3f3e | 0 | lmcro/xo-web,vatesfr/xo-web,lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web | import _, { messages } from 'messages'
import { Button } from 'react-bootstrap-4/lib'
import { injectIntl } from 'react-intl'
import ActionButton from 'action-button'
import BaseComponent from 'base-component'
import classNames from 'classnames'
import debounce from 'lodash/debounce'
import every from 'lodash/every'
import forEach from 'lodash/forEach'
import Icon from 'icon'
import isArray from 'lodash/isArray'
import map from 'lodash/map'
import React from 'react'
import size from 'lodash/size'
import store from 'store'
import toArray from 'lodash/toArray'
import Wizard, { Section } from 'wizard'
import {
createVm,
getCloudInitConfig
} from 'xo'
import {
SelectVdi,
SelectNetwork,
SelectPool,
SelectSr,
SelectVmTemplate
} from 'select-objects'
import {
SizeInput,
Toggle
} from 'form'
import {
connectStore,
formatSize,
getEventValue
} from 'utils'
import {
createSelector,
createGetObject,
createGetObjectsOfType
} from 'selectors'
import styles from './index.css'
/* eslint-disable camelcase */
const SectionContent = ({ summary, column, children }) => (
<div className={classNames(
'form-inline',
summary ? styles.summary : styles.sectionContent,
column && styles.sectionContentColumn
)}>
{children}
</div>
)
const LineItem = ({ children }) => (
<div className={styles.lineItem}>
{children}
</div>
)
const Item = ({ label, children }) => (
<span className={styles.item}>
{label && <span>{_(label)} </span>}
<span className={styles.input}>{children}</span>
</span>
)
const getObject = createGetObject((_, id) => id)
@connectStore(() => ({
templates: createGetObjectsOfType('VM-template').sort()
}))
@injectIntl
export default class NewVm extends BaseComponent {
constructor () {
super()
this._uniqueId = 0
// NewVm's state is stored in this.state.state instead of this.state
// so it can be emptied easily with this.setState(state: {})
this.state = { state: {} }
}
getUniqueId () {
return this._uniqueId++
}
get _isDiskTemplate () {
const { template } = this.state.state
return template.template_info.disks.length === 0 && template.name_label !== 'Other install media'
}
_setInputValue (ref, value) {
if (!this.refs[ref]) {
return
}
const type = this.refs[ref].type
if (type === 'text' || type === 'number') {
this.refs[ref].value = value || ''
return
}
this.refs[ref].value = value
}
_setState = (newValues, callback) => {
this.setState({ state: {
...this.state.state,
...newValues
}}, callback)
}
_replaceState = (state, callback) =>
this.setState({ state }, callback)
_reset = pool => {
const { refs } = this
forEach(refs, (ref, key) => {
if (ref.tagName === 'INPUT' || ref.tagName === 'TEXTAREA') {
ref.value = ''
} else if (key !== 'pool') {
ref.value = undefined
}
})
// CPU weight should be "Normal" by default
refs.cpuWeight && (refs.cpuWeight.value = 1)
const previousPool = this.state.state.pool
this._replaceState({
bootAfterCreate: true,
fastClone: true,
cpuWeight: 1,
existingDisks: {},
pool: pool || previousPool,
VDIs: [],
VIFs: []
})
}
_create = () => {
const { state } = this.state
let installation
switch (state.installMethod) {
case 'ISO':
installation = {
method: 'cdrom',
repository: state.installIso.id
}
break
case 'network':
const matches = /^(http|ftp|nfs)/i.exec(state.installNetwork)
if (!matches) {
throw new Error('invalid network URL')
}
installation = {
method: matches[1].toLowerCase(),
repository: state.installNetwork
}
break
case 'PXE':
installation = {
method: 'network',
repository: 'pxe'
}
}
let cloudConfig
if (state.configDrive) {
const hostname = state.name_label.replace(/^\s+|\s+$/g, '').replace(/\s+/g, '-')
if (this.installMethod === 'SSH') {
cloudConfig = '#cloud-config\nhostname: ' + hostname + '\nssh_authorized_keys:\n - ' + state.sshKey + '\n'
} else {
cloudConfig = state.customConfig
}
} else if (state.template.name_label === 'CoreOS') {
cloudConfig = state.cloudConfig
}
const data = {
clone: state.fastClone,
existingDisks: state.existingDisks,
installation,
name_label: state.name_label,
template: state.template.id,
VDIs: state.VDIs,
VIFs: state.VIFs,
// TODO: To be added in xo-server
// vm.set parameters
CPUs: state.CPUs,
cpuWeight: state.cpuWeight,
name_description: state.name_description,
memory: state.memory,
pv_args: state.pv_args,
// Boolean: if true, boot the VM right after its creation
bootAfterCreate: state.bootAfterCreate,
cloudConfig,
coreOs: state.template.name_label === 'CoreOS'
}
return createVm(data)
}
_selectPool = pool =>
this._reset(pool)
_getIsInPool = createSelector(
() => this.state.state.pool.id,
poolId => object => object.$pool === poolId
)
_getSrPredicate = createSelector(
() => this.state.state.pool.id,
poolId => disk => disk.$pool === poolId && disk.content_type === 'user'
)
_initTemplate = template => {
if (!template) {
return this._reset()
}
const state = store.getState()
const existingDisks = {}
forEach(template.$VBDs, vbdId => {
const vbd = getObject(state, vbdId)
if (vbd.is_cd_drive) {
return
}
const vdi = getObject(state, vbd.VDI)
existingDisks[this.getUniqueId()] = {
name_label: vdi.name_label,
name_description: vdi.name_description,
size: vdi.size,
$SR: vdi.$SR
}
})
const VIFs = []
forEach(template.VIFs, vifId => {
const vif = getObject(state, vifId)
VIFs.push({
mac: vif.MAC,
network: vif.$network,
id: this.getUniqueId()
})
})
this._setState({
// infos
name_label: template.name_label,
template,
name_description: template.name_description || this.state.state.name_description || '',
// performances
memory: template.memory.size,
CPUs: template.CPUs.number,
cpuWeight: 1,
// installation
installMethod: template.install_methods && template.install_methods[0] || this.state.state.installMethod,
// interfaces
VIFs,
// disks
existingDisks,
VDIs: map(template.template_info.disks, disk => ({ ...disk, device: String(this.getUniqueId()) }))
}, () => forEach(this.state.state, (element, key) => {
!isArray(element) && this._setInputValue(key, element)
}))
getCloudInitConfig(template.id).then(cloudConfig => {
this._setState({ cloudConfig }, () => {
this.refs.cloudConfig && (this.refs.cloudConfig.value = cloudConfig)
})
})
}
_addVdi = () => this._setState({ VDIs: [ ...this.state.state.VDIs, {
device: String(this.getUniqueId()),
type: 'system'
}] })
_removeVdi = index => {
const { VDIs } = this.state.state
this._setState({ VDIs: [ ...VDIs.slice(0, index), ...VDIs.slice(index + 1) ] })
}
_addInterface = () => this._setState({ VIFs: [ ...this.state.state.VIFs, {
id: this.getUniqueId()
}] })
_removeInterface = index => {
const { VIFs } = this.state.state
this._setState({ VIFs: [ ...VIFs.slice(0, index), ...VIFs.slice(index + 1) ] })
}
_getOnChange (prop) {
const debouncer = debounce(param => this._setState({ [prop]: param }), 100)
return param => {
const _param = param && param.target ? param.target.value : param
debouncer(_param)
}
}
_getOnChangeCheckbox (prop) {
const debouncer = debounce(checked =>
this._setState({ [prop]: checked }), 100
)
return event => {
const _param = event.target.checked
debouncer(_param)
}
}
_getOnChangeObject (stateElement, key, stateProperty, targetProperty) {
const debouncer = debounce(param => {
let stateValue = this.state.state[stateElement]
stateValue = isArray(stateValue) ? [ ...stateValue ] : { ...stateValue }
stateValue[key][stateProperty] = param && param[targetProperty] || param
this._setState({ [stateElement]: stateValue })
}, 100)
return param => debouncer(getEventValue(param))
}
_getOnChangeObjectCheckbox (stateElement, key, stateProperty, targetProperty) {
const debouncer = debounce(param => {
const stateValue = { ...this.state.state[stateElement] }
stateValue[key][stateProperty] = param
this._setState({ [stateElement]: stateValue })
}, 100)
return event => {
const _param = event.target.checked
debouncer(_param)
}
}
render () {
return <div>
<h1>
{_('newVmCreateNewVmOn', {
pool: <span className={styles.inlineSelect}>
<SelectPool ref='pool' onChange={this._selectPool} />
</span>
})}
</h1>
{this.state.state.pool && <form id='vmCreation' ref='form'>
<Wizard>
{this._renderInfo()}
{this._renderPerformances()}
{this._renderInstallSettings()}
{this._renderInterfaces()}
{this._renderDisks()}
{this._renderSummary()}
</Wizard>
<div className={styles.submitSection}>
<ActionButton
btnStyle='secondary'
className={styles.button}
handler={this._reset}
icon='new-vm-reset'
>
{_('newVmReset')}
</ActionButton>
<ActionButton
btnStyle='primary'
className={styles.button}
disabled={!(
this._isInfoDone() &&
this._isPerformancesDone() &&
this._isInstallSettingsDone() &&
this._isInterfacesDone() &&
this._isDisksDone()
)}
form='vmCreation'
handler={this._create}
icon='new-vm-create'
redirectOnSuccess='/home'
>
{_('newVmCreate')}
</ActionButton>
</div>
</form>}
</div>
}
_renderInfo = () => {
return <Section icon='new-vm-infos' title='newVmInfoPanel' done={this._isInfoDone()}>
<SectionContent>
<Item label='newVmNameLabel'>
<input ref='name_label' onChange={this._getOnChange('name_label')} className='form-control' type='text' required />
</Item>
<Item label='newVmTemplateLabel'>
<span className={styles.inlineSelect}>
<SelectVmTemplate
onChange={this._initTemplate}
placeholder={_('newVmSelectTemplate')}
predicate={this._getIsInPool()}
ref='template'
/>
</span>
</Item>
<Item label='newVmDescriptionLabel'>
<input ref='name_description' onChange={this._getOnChange('name_description')} className='form-control' type='text' />
</Item>
</SectionContent>
</Section>
}
_isInfoDone = () => {
const { template, name_label } = this.state.state
return name_label && template
}
_renderPerformances = () => {
return <Section icon='new-vm-perf' title='newVmPerfPanel' done={this._isPerformancesDone()}>
<SectionContent>
<Item label='newVmVcpusLabel'>
<input ref='CPUs' onChange={this._getOnChange('CPUs')} className='form-control' type='number' />
</Item>
<Item label='newVmRamLabel'>
<SizeInput ref='memory' onChange={this._getOnChange('memory')} className={styles.sizeInput} />
</Item>
<Item label='newVmCpuWeightLabel'>
<select
className='form-control'
defaultValue={1}
onChange={this._getOnChange('cpuWeight')}
ref='cpuWeight'
>
{_('newVmCpuWeightQuarter', message => <option value={0.25}>{message}</option>)}
{_('newVmCpuWeightHalf', message => <option value={0.5}>{message}</option>)}
{_('newVmCpuWeightNormal', message => <option value={1}>{message}</option>)}
{_('newVmCpuWeightDouble', message => <option value={2}>{message}</option>)}
</select>
</Item>
</SectionContent>
</Section>
}
_isPerformancesDone = () => {
const { CPUs, memory } = this.state.state
return CPUs && memory !== undefined
}
_renderInstallSettings = () => {
const { template } = this.state.state
if (!template) {
return
}
const { configDrive, installMethod, pool } = this.state.state
return <Section icon='new-vm-install-settings' title='newVmInstallSettingsPanel' done={this._isInstallSettingsDone()}>
{this._isDiskTemplate ? <SectionContent key='diskTemplate'>
<div className={styles.configDrive}>
<span className={styles.configDriveToggle}>
{_('newVmConfigDrive')}
</span>
<span className={styles.configDriveToggle}>
<Toggle
defaultValue={false}
onChange={this._getOnChange('configDrive')}
/>
</span>
</div>
<Item>
<input disabled={!configDrive} onChange={this._getOnChange('installMethod')} name='installMethod' value='SSH' type='radio' />
{' '}
<span>{_('newVmSshKey')}</span>
{' '}
<input onChange={this._getOnChange('sshKey')} disabled={installMethod !== 'SSH'} className='form-control' type='text' />
</Item>
<Item>
<input disabled={!configDrive} onChange={this._getOnChange('installMethod')} name='installMethod' value='customConfig' type='radio' />
{' '}
<span>{_('newVmCustomConfig')}</span>
{' '}
<textarea
className='form-control'
disabled={installMethod !== 'customConfig'}
onChange={this._getOnChange('customConfig')}
ref='customConfig'
type='text'
/>
</Item>
</SectionContent>
: <SectionContent>
<Item>
<span className={styles.item}>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='ISO' type='radio' />
<span>{_('newVmIsoDvdLabel')}</span>
<span className={styles.inlineSelect}>
<SelectVdi
disabled={installMethod !== 'ISO'}
onChange={this._getOnChange('installIso')}
srPredicate={sr => sr.$pool === pool.id && sr.SR_type === 'iso'}
ref='installIso'
/>
</span>
</span>
</Item>
<Item>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='network' type='radio' />
{' '}
<span>{_('newVmNetworkLabel')}</span>
{' '}
<input key='networkInput' ref='installNetwork' onChange={this._getOnChange('installNetwork')} disabled={installMethod !== 'network'} placeholder='e.g: http://ftp.debian.org/debian' type='text' className='form-control' />
</Item>
{template.virtualizationMode === 'pv'
? <Item label='newVmPvArgsLabel'>
<input onChange={this._getOnChange('pv_args')} className='form-control' type='text' />
</Item>
: <Item>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='PXE' type='radio' />
{' '}
<span>{_('newVmPxeLabel')}</span>
</Item>
}
</SectionContent>}
{template.name_label === 'CoreOS' && <div>
<label>{_('newVmCloudConfig')}</label>
<textarea
className='form-control'
onChange={this._getOnChange('cloudConfig')}
ref='cloudConfig'
rows={7}
/>
</div>}
</Section>
}
_isInstallSettingsDone = () => {
const {
configDrive,
customConfig,
installIso,
installMethod,
installNetwork,
sshKey,
template
} = this.state.state
switch (installMethod) {
case 'customConfig': return customConfig
case 'ISO': return installIso
case 'network': return /^(http|ftp|nfs)/i.exec(installNetwork)
case 'PXE': return true
case 'SSH': return sshKey
default: return template && this._isDiskTemplate && !configDrive
}
}
_renderInterfaces = () => {
const { formatMessage } = this.props.intl
return <Section icon='new-vm-interfaces' title='newVmInterfacesPanel' done={this._isInterfacesDone()}>
<SectionContent column>
{map(this.state.state.VIFs, (vif, index) => <div key={index}>
<LineItem>
<Item label='newVmMacLabel'>
<input ref={`mac_${vif.id}`} onChange={this._getOnChangeObject('VIFs', index, 'mac')} defaultValue={vif.mac} placeholder={formatMessage(messages.newVmMacPlaceholder)} className='form-control' type='text' />
</Item>
<Item label='newVmNetworkLabel'>
<span className={styles.inlineSelect}>
<SelectNetwork
defaultValue={vif.network}
onChange={this._getOnChangeObject('VIFs', index, 'network', 'id')}
predicate={this._getIsInPool()}
ref='network'
/>
</span>
</Item>
<Item>
<Button onClick={() => this._removeInterface(index)} bsStyle='secondary'>
<Icon icon='new-vm-remove' />
</Button>
</Item>
</LineItem>
{index < this.state.state.VIFs.length - 1 && <hr />}
</div>
)}
<Item>
<Button onClick={this._addInterface} bsStyle='secondary'>
<Icon icon='new-vm-add' />
{' '}
{_('newVmAddInterface')}
</Button>
</Item>
</SectionContent>
</Section>
}
_isInterfacesDone = () => every(this.state.state.VIFs, vif =>
vif.network
)
_renderDisks = () => {
return <Section icon='new-vm-disks' title='newVmDisksPanel' done={this._isDisksDone()}>
<SectionContent column>
{/* Existing disks */}
{map(toArray(this.state.state.existingDisks), (disk, index) => <div key={index}>
<LineItem>
<Item label='newVmSrLabel'>
<span className={styles.inlineSelect}>
<SelectSr
defaultValue={disk.$SR}
onChange={this._getOnChangeObject('existingDisks', index, '$SR', 'id')}
predicate={this._getSrPredicate()}
ref={`sr_${index}`}
/>
</span>
</Item>
{' '}
<Item label='newVmNameLabel'>
<input
className='form-control'
defaultValue={disk.name_label}
onChange={this._getOnChangeObject('existingDisks', index, 'name_label')}
ref={`name_label_${index}`}
type='text'
/>
</Item>
<Item label='newVmDescriptionLabel'>
<input
className='form-control'
defaultValue={disk.name_description}
onChange={this._getOnChangeObject('existingDisks', index, 'name_description')}
ref={`name_description_${index}`}
type='text'
/>
</Item>
<Item label='newVmSizeLabel'>
<SizeInput
className={styles.sizeInput}
defaultValue={disk.size}
onChange={this._getOnChangeObject('existingDisks', index, 'size')}
readOnly={!this.state.state.configDrive}
ref={`size_${index}`}
/>
</Item>
</LineItem>
{index < size(this.state.state.existingDisks) + this.state.state.VDIs.length - 1 && <hr />}
</div>
)}
{/* VDIs */}
{map(this.state.state.VDIs, (vdi, index) => <div key={vdi.device}>
<LineItem>
<Item label='newVmSrLabel'>
<span className={styles.inlineSelect}>
<SelectSr
defaultValue={vdi.SR}
onChange={this._getOnChangeObject('VDIs', index, 'SR', 'id')}
predicate={this._getSrPredicate()}
ref={`sr_${vdi.device}`}
/>
</span>
</Item>
{' '}
<Item className='checkbox'>
<label>
<input
checked={vdi.bootable}
onChange={this._getOnChangeObjectCheckbox('VDIs', index, 'bootable')}
ref={`bootable_${vdi.device}`}
type='checkbox'
/>
{' '}
{_('newVmBootableLabel')}
</label>
</Item>
<Item label='newVmNameLabel'>
<input
className='form-control'
defaultValue={vdi.name_label}
onChange={this._getOnChangeObject('VDIs', index, 'name_label')}
ref={`name_label_${vdi.device}`}
type='text'
/>
</Item>
<Item label='newVmDescriptionLabel'>
<input
className='form-control'
defaultValue={vdi.name_description}
onChange={this._getOnChangeObject('VDIs', index, 'name_description')}
ref={`name_description_${vdi.device}`}
type='text'
/>
</Item>
<Item label='newVmSizeLabel'>
<SizeInput
className={styles.sizeInput}
defaultValue={vdi.size}
onChange={this._getOnChangeObject('VDIs', index, 'size')}
ref={`size_${vdi.device}`}
/>
</Item>
<Item>
<Button onClick={() => this._removeVdi(index)} bsStyle='secondary'>
<Icon icon='new-vm-remove' />
</Button>
</Item>
</LineItem>
{index < this.state.state.VDIs.length - 1 && <hr />}
</div>
)}
<Item>
<Button onClick={this._addVdi} bsStyle='secondary'>
<Icon icon='new-vm-add' />
{' '}
{_('newVmAddDisk')}
</Button>
</Item>
</SectionContent>
</Section>
}
_isDisksDone = () => every(this.state.state.VDIs, vdi =>
vdi.SR && vdi.name_label && vdi.size !== undefined
) &&
every(this.state.state.existingDisks, (vdi, index) =>
vdi.$SR && vdi.name_label && vdi.size !== undefined
)
_renderSummary = () => {
const { bootAfterCreate, CPUs, existingDisks, fastClone, memory, VDIs, VIFs } = this.state.state
return <Section icon='new-vm-summary' title='newVmSummaryPanel' summary>
<SectionContent summary>
<span>
{CPUs || 0}x{' '}
<Icon icon='cpu' />
</span>
<span>
{memory ? formatSize(memory) : '0 B'}
{' '}
<Icon icon='memory' />
</span>
<span>
{size(existingDisks) + VDIs.length || 0}x{' '}
<Icon icon='disk' />
</span>
<span>
{VIFs.length}x{' '}
<Icon icon='network' />
</span>
</SectionContent>
<div style={{display: 'flex'}}>
<span style={{margin: 'auto'}}>
<input
checked={fastClone}
onChange={this._getOnChangeCheckbox('fastClone')}
ref='fastClone'
type='checkbox'
/>
{' '}
<Icon icon='vm-fast-clone' />
{' '}
{_('fastCloneVmLabel')}
</span>
</div>
<div style={{display: 'flex'}}>
<span style={{margin: 'auto'}}>
<input
checked={bootAfterCreate}
onChange={this._getOnChangeCheckbox('bootAfterCreate')}
ref='bootAfterCreate'
type='checkbox'
/>
{' '}
{_('newVmBootAfterCreate')}
</span>
</div>
</Section>
}
}
/* eslint-enable camelcase*/
| src/xo-app/new-vm/index.js | import _, { messages } from 'messages'
import { Button } from 'react-bootstrap-4/lib'
import { injectIntl } from 'react-intl'
import ActionButton from 'action-button'
import BaseComponent from 'base-component'
import classNames from 'classnames'
import debounce from 'lodash/debounce'
import every from 'lodash/every'
import forEach from 'lodash/forEach'
import Icon from 'icon'
import isArray from 'lodash/isArray'
import map from 'lodash/map'
import React from 'react'
import size from 'lodash/size'
import store from 'store'
import toArray from 'lodash/toArray'
import Wizard, { Section } from 'wizard'
import {
createVm,
getCloudInitConfig
} from 'xo'
import {
SelectVdi,
SelectNetwork,
SelectPool,
SelectSr,
SelectVmTemplate
} from 'select-objects'
import {
SizeInput,
Toggle
} from 'form'
import {
connectStore,
formatSize,
getEventValue
} from 'utils'
import {
createSelector,
createGetObject,
createGetObjectsOfType
} from 'selectors'
import styles from './index.css'
/* eslint-disable camelcase */
const SectionContent = ({ summary, column, children }) => (
<div className={classNames(
'form-inline',
summary ? styles.summary : styles.sectionContent,
column && styles.sectionContentColumn
)}>
{children}
</div>
)
const LineItem = ({ children }) => (
<div className={styles.lineItem}>
{children}
</div>
)
const Item = ({ label, children }) => (
<span className={styles.item}>
{label && <span>{_(label)} </span>}
<span className={styles.input}>{children}</span>
</span>
)
const getObject = createGetObject((_, id) => id)
@connectStore(() => ({
templates: createGetObjectsOfType('VM-template').sort()
}))
@injectIntl
export default class NewVm extends BaseComponent {
constructor () {
super()
this._uniqueId = 0
// NewVm's state is stored in this.state.state instead of this.state
// so it can be emptied easily with this.setState(state: {})
this.state = { state: {} }
}
getUniqueId () {
return this._uniqueId++
}
get _isDiskTemplate () {
const { template } = this.state.state
return template.template_info.disks.length === 0 && template.name_label !== 'Other install media'
}
_setInputValue (ref, value) {
if (!this.refs[ref]) {
return
}
const type = this.refs[ref].type
if (type === 'text' || type === 'number') {
this.refs[ref].value = value || ''
return
}
this.refs[ref].value = value
}
_setState = (newValues, callback) => {
this.setState({ state: {
...this.state.state,
...newValues
}}, callback)
}
_replaceState = (state, callback) =>
this.setState({ state }, callback)
_reset = pool => {
const { refs } = this
forEach(refs, (ref, key) => {
if (ref.tagName === 'INPUT' || ref.tagName === 'TEXTAREA') {
ref.value = ''
} else if (key !== 'pool') {
ref.value = undefined
}
})
// CPU weight should be "Normal" by default
refs.cpuWeight && (refs.cpuWeight.value = 1)
const previousPool = this.state.state.pool
this._replaceState({
bootAfterCreate: true,
fastClone: true,
cpuWeight: 1,
existingDisks: {},
pool: pool || previousPool,
VDIs: [],
VIFs: []
})
}
_create = () => {
const { state } = this.state
let installation
switch (state.installMethod) {
case 'ISO':
installation = {
method: 'cdrom',
repository: state.installIso.id
}
break
case 'network':
const matches = /^(http|ftp|nfs)/i.exec(state.installNetwork)
if (!matches) {
throw new Error('invalid network URL')
}
installation = {
method: matches[1].toLowerCase(),
repository: state.installNetwork
}
break
case 'PXE':
installation = {
method: 'network',
repository: 'pxe'
}
}
let cloudConfig
if (state.configDrive) {
const hostname = state.name_label.replace(/^\s+|\s+$/g, '').replace(/\s+/g, '-')
if (this.installMethod === 'SSH') {
cloudConfig = '#cloud-config\nhostname: ' + hostname + '\nssh_authorized_keys:\n - ' + state.sshKey + '\n'
} else {
cloudConfig = state.customConfig
}
} else if (state.template.name_label === 'CoreOS') {
cloudConfig = state.cloudConfig
}
const data = {
clone: state.fastClone,
existingDisks: state.existingDisks,
installation,
name_label: state.name_label,
template: state.template.id,
VDIs: state.VDIs,
VIFs: state.VIFs,
// TODO: To be added in xo-server
// vm.set parameters
CPUs: state.CPUs,
cpuWeight: state.cpuWeight,
name_description: state.name_description,
memory: state.memory,
pv_args: state.pv_args,
// Boolean: if true, boot the VM right after its creation
bootAfterCreate: state.bootAfterCreate,
cloudConfig,
coreOs: state.template.name_label === 'CoreOS'
}
return createVm(data)
}
_selectPool = pool =>
this._reset(pool)
_getIsInPool = createSelector(
() => this.state.state.pool.id,
poolId => object => object.$pool === poolId
)
_getSrPredicate = createSelector(
() => this.state.state.pool.id,
poolId => disk => disk.$pool === poolId && disk.content_type === 'user'
)
_initTemplate = template => {
if (!template) {
return this._reset()
}
const state = store.getState()
const existingDisks = {}
forEach(template.$VBDs, vbdId => {
const vbd = getObject(state, vbdId)
if (vbd.is_cd_drive) {
return
}
const vdi = getObject(state, vbd.VDI)
existingDisks[this.getUniqueId()] = {
name_label: vdi.name_label,
name_description: vdi.name_description,
size: vdi.size,
$SR: vdi.$SR
}
})
const VIFs = []
forEach(template.VIFs, vifId => {
const vif = getObject(state, vifId)
VIFs.push({
mac: vif.MAC,
network: vif.$network,
id: this.getUniqueId()
})
})
this._setState({
// infos
name_label: template.name_label,
template,
name_description: template.name_description || this.state.state.name_description || '',
// performances
memory: template.memory.size,
CPUs: template.CPUs.number,
cpuWeight: 1,
// installation
installMethod: template.install_methods && template.install_methods[0] || this.state.state.installMethod,
// interfaces
VIFs,
// disks
existingDisks,
VDIs: map(template.template_info.disks, disk => ({ ...disk, device: String(this.getUniqueId()) }))
}, () => forEach(this.state.state, (element, key) => {
!isArray(element) && this._setInputValue(key, element)
}))
getCloudInitConfig(template.id).then(cloudConfig => {
this._setState({ cloudConfig }, () => {
this.refs.cloudConfig && (this.refs.cloudConfig.value = cloudConfig)
})
})
}
_addVdi = () => this._setState({ VDIs: [ ...this.state.state.VDIs, {
device: String(this.getUniqueId()),
type: 'system'
}] })
_removeVdi = index => {
const { VDIs } = this.state.state
this._setState({ VDIs: [ ...VDIs.slice(0, index), ...VDIs.slice(index + 1) ] })
}
_addInterface = () => this._setState({ VIFs: [ ...this.state.state.VIFs, {
id: this.getUniqueId()
}] })
_removeInterface = index => {
const { VIFs } = this.state.state
this._setState({ VIFs: [ ...VIFs.slice(0, index), ...VIFs.slice(index + 1) ] })
}
_getOnChange (prop) {
const debouncer = debounce(param => this._setState({ [prop]: param }), 100)
return param => {
const _param = param && param.target ? param.target.value : param
debouncer(_param)
}
}
_getOnChangeCheckbox (prop) {
const debouncer = debounce(checked =>
this._setState({ [prop]: checked }), 100
)
return event => {
const _param = event.target.checked
debouncer(_param)
}
}
_getOnChangeObject (stateElement, key, stateProperty, targetProperty) {
const debouncer = debounce(param => {
let stateValue = this.state.state[stateElement]
stateValue = isArray(stateValue) ? [ ...stateValue ] : { ...stateValue }
stateValue[key][stateProperty] = param && param[targetProperty] || param
this._setState({ [stateElement]: stateValue })
}, 100)
return param => debouncer(getEventValue(param))
}
_getOnChangeObjectCheckbox (stateElement, key, stateProperty, targetProperty) {
const debouncer = debounce(param => {
const stateValue = { ...this.state.state[stateElement] }
stateValue[key][stateProperty] = param
this._setState({ [stateElement]: stateValue })
}, 100)
return event => {
const _param = event.target.checked
debouncer(_param)
}
}
render () {
return <div>
<h1>
{_('newVmCreateNewVmOn', {
pool: <span className={styles.inlineSelect}>
<SelectPool ref='pool' onChange={this._selectPool} />
</span>
})}
</h1>
{this.state.state.pool && <form id='vmCreation' ref='form'>
<Wizard>
{this._renderInfo()}
{this._renderPerformances()}
{this._renderInstallSettings()}
{this._renderInterfaces()}
{this._renderDisks()}
{this._renderSummary()}
</Wizard>
<div className={styles.submitSection}>
<ActionButton
btnStyle='secondary'
className={styles.button}
handler={this._reset}
icon='new-vm-reset'
>
{_('newVmReset')}
</ActionButton>
<ActionButton
btnStyle='primary'
className={styles.button}
disabled={!(
this._isInfoDone() &&
this._isPerformancesDone() &&
this._isInstallSettingsDone() &&
this._isInterfacesDone() &&
this._isDisksDone()
)}
form='vmCreation'
handler={this._create}
icon='new-vm-create'
redirectOnSuccess='/home'
>
{_('newVmCreate')}
</ActionButton>
</div>
</form>}
</div>
}
_renderInfo = () => {
return <Section icon='new-vm-infos' title='newVmInfoPanel' done={this._isInfoDone()}>
<SectionContent>
<Item label='newVmNameLabel'>
<input ref='name_label' onChange={this._getOnChange('name_label')} className='form-control' type='text' required />
</Item>
<Item label='newVmTemplateLabel'>
<span className={styles.inlineSelect}>
<SelectVmTemplate
onChange={this._initTemplate}
placeholder={_('newVmSelectTemplate')}
predicate={this._getIsInPool()}
ref='template'
/>
</span>
</Item>
<Item label='newVmDescriptionLabel'>
<input ref='name_description' onChange={this._getOnChange('name_description')} className='form-control' type='text' />
</Item>
</SectionContent>
</Section>
}
_isInfoDone = () => {
const { template, name_label } = this.state.state
return name_label && template
}
_renderPerformances = () => {
return <Section icon='new-vm-perf' title='newVmPerfPanel' done={this._isPerformancesDone()}>
<SectionContent>
<Item label='newVmVcpusLabel'>
<input ref='CPUs' onChange={this._getOnChange('CPUs')} className='form-control' type='number' />
</Item>
<Item label='newVmRamLabel'>
<SizeInput ref='memory' onChange={this._getOnChange('memory')} className={styles.sizeInput} />
</Item>
<Item label='newVmCpuWeightLabel'>
<select
className='form-control'
defaultValue={1}
onChange={this._getOnChange('cpuWeight')}
ref='cpuWeight'
>
{_('newVmCpuWeightQuarter', message => <option value={0.25}>{message}</option>)}
{_('newVmCpuWeightHalf', message => <option value={0.5}>{message}</option>)}
{_('newVmCpuWeightNormal', message => <option value={1}>{message}</option>)}
{_('newVmCpuWeightDouble', message => <option value={2}>{message}</option>)}
</select>
</Item>
</SectionContent>
</Section>
}
_isPerformancesDone = () => {
const { CPUs, memory } = this.state.state
return CPUs && memory !== undefined
}
_renderInstallSettings = () => {
const { template } = this.state.state
if (!template) {
return
}
const { configDrive, installMethod, pool } = this.state.state
return <Section icon='new-vm-install-settings' title='newVmInstallSettingsPanel' done={this._isInstallSettingsDone()}>
{this._isDiskTemplate ? <SectionContent key='diskTemplate'>
<div className={styles.configDrive}>
<span className={styles.configDriveToggle}>
{_('newVmConfigDrive')}
</span>
<span className={styles.configDriveToggle}>
<Toggle
defaultValue={false}
onChange={this._getOnChange('configDrive')}
/>
</span>
</div>
<Item>
<input disabled={!configDrive} onChange={this._getOnChange('installMethod')} name='installMethod' value='SSH' type='radio' />
{' '}
<span>{_('newVmSshKey')}</span>
{' '}
<input onChange={this._getOnChange('sshKey')} disabled={installMethod !== 'SSH'} className='form-control' type='text' />
</Item>
<Item>
<input disabled={!configDrive} onChange={this._getOnChange('installMethod')} name='installMethod' value='customConfig' type='radio' />
{' '}
<span>{_('newVmCustomConfig')}</span>
{' '}
<textarea
className='form-control'
disabled={installMethod !== 'customConfig'}
onChange={this._getOnChange('customConfig')}
ref='customConfig'
type='text'
/>
</Item>
</SectionContent>
: <SectionContent>
<Item>
<span className={styles.item}>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='ISO' type='radio' />
<span>{_('newVmIsoDvdLabel')}</span>
<span className={styles.inlineSelect}>
<SelectVdi
disabled={installMethod !== 'ISO'}
onChange={this._getOnChange('installIso')}
srPredicate={sr => sr.$pool === pool.id && sr.SR_type === 'iso'}
ref='installIso'
/>
</span>
</span>
</Item>
<Item>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='network' type='radio' />
{' '}
<span>{_('newVmNetworkLabel')}</span>
{' '}
<input key='networkInput' ref='installNetwork' onChange={this._getOnChange('installNetwork')} disabled={installMethod !== 'network'} placeholder='e.g: http://ftp.debian.org/debian' type='text' className='form-control' />
</Item>
{template.virtualizationMode === 'pv'
? <Item label='newVmPvArgsLabel'>
<input onChange={this._getOnChange('pv_args')} className='form-control' type='text' />
</Item>
: <Item>
<input onChange={this._getOnChange('installMethod')} name='installMethod' value='PXE' type='radio' />
{' '}
<span>{_('newVmPxeLabel')}</span>
</Item>
}
</SectionContent>}
{template.name_label === 'CoreOS' && <div>
<label>{_('newVmCloudConfig')}</label>
<textarea
className='form-control'
onChange={this._getOnChange('cloudConfig')}
ref='cloudConfig'
rows={7}
/>
</div>}
</Section>
}
_isInstallSettingsDone = () => {
const {
configDrive,
customConfig,
installIso,
installMethod,
installNetwork,
sshKey,
template
} = this.state.state
switch (installMethod) {
case 'customConfig': return customConfig
case 'ISO': return installIso
case 'network': return /^(http|ftp|nfs)/i.exec(installNetwork)
case 'PXE': return true
case 'SSH': return sshKey
default: return template && this._isDiskTemplate && !configDrive
}
}
_renderInterfaces = () => {
const { formatMessage } = this.props.intl
return <Section icon='new-vm-interfaces' title='newVmInterfacesPanel' done={this._isInterfacesDone()}>
<SectionContent column>
{map(this.state.state.VIFs, (vif, index) => <div key={index}>
<LineItem>
<Item label='newVmMacLabel'>
<input ref={`mac_${vif.id}`} onChange={this._getOnChangeObject('VIFs', index, 'mac')} defaultValue={vif.mac} placeholder={formatMessage(messages.newVmMacPlaceholder)} className='form-control' type='text' />
</Item>
<Item label='newVmNetworkLabel'>
<span className={styles.inlineSelect}>
<SelectNetwork
defaultValue={vif.network}
onChange={this._getOnChangeObject('VIFs', index, '$network', 'id')}
predicate={this._getIsInPool()}
ref='network'
/>
</span>
</Item>
<Item>
<Button onClick={() => this._removeInterface(index)} bsStyle='secondary'>
<Icon icon='new-vm-remove' />
</Button>
</Item>
</LineItem>
{index < this.state.state.VIFs.length - 1 && <hr />}
</div>
)}
<Item>
<Button onClick={this._addInterface} bsStyle='secondary'>
<Icon icon='new-vm-add' />
{' '}
{_('newVmAddInterface')}
</Button>
</Item>
</SectionContent>
</Section>
}
_isInterfacesDone = () => every(this.state.state.VIFs, vif =>
vif.network
)
_renderDisks = () => {
return <Section icon='new-vm-disks' title='newVmDisksPanel' done={this._isDisksDone()}>
<SectionContent column>
{/* Existing disks */}
{map(toArray(this.state.state.existingDisks), (disk, index) => <div key={index}>
<LineItem>
<Item label='newVmSrLabel'>
<span className={styles.inlineSelect}>
<SelectSr
defaultValue={disk.$SR}
onChange={this._getOnChangeObject('existingDisks', index, '$SR', 'id')}
predicate={this._getSrPredicate()}
ref={`sr_${index}`}
/>
</span>
</Item>
{' '}
<Item label='newVmNameLabel'>
<input
className='form-control'
defaultValue={disk.name_label}
onChange={this._getOnChangeObject('existingDisks', index, 'name_label')}
ref={`name_label_${index}`}
type='text'
/>
</Item>
<Item label='newVmDescriptionLabel'>
<input
className='form-control'
defaultValue={disk.name_description}
onChange={this._getOnChangeObject('existingDisks', index, 'name_description')}
ref={`name_description_${index}`}
type='text'
/>
</Item>
<Item label='newVmSizeLabel'>
<SizeInput
className={styles.sizeInput}
defaultValue={disk.size}
onChange={this._getOnChangeObject('existingDisks', index, 'size')}
readOnly={!this.state.state.configDrive}
ref={`size_${index}`}
/>
</Item>
</LineItem>
{index < size(this.state.state.existingDisks) + this.state.state.VDIs.length - 1 && <hr />}
</div>
)}
{/* VDIs */}
{map(this.state.state.VDIs, (vdi, index) => <div key={vdi.device}>
<LineItem>
<Item label='newVmSrLabel'>
<span className={styles.inlineSelect}>
<SelectSr
defaultValue={vdi.SR}
onChange={this._getOnChangeObject('VDIs', index, 'SR', 'id')}
predicate={this._getSrPredicate()}
ref={`sr_${vdi.device}`}
/>
</span>
</Item>
{' '}
<Item className='checkbox'>
<label>
<input
checked={vdi.bootable}
onChange={this._getOnChangeObjectCheckbox('VDIs', index, 'bootable')}
ref={`bootable_${vdi.device}`}
type='checkbox'
/>
{' '}
{_('newVmBootableLabel')}
</label>
</Item>
<Item label='newVmNameLabel'>
<input
className='form-control'
defaultValue={vdi.name_label}
onChange={this._getOnChangeObject('VDIs', index, 'name_label')}
ref={`name_label_${vdi.device}`}
type='text'
/>
</Item>
<Item label='newVmDescriptionLabel'>
<input
className='form-control'
defaultValue={vdi.name_description}
onChange={this._getOnChangeObject('VDIs', index, 'name_description')}
ref={`name_description_${vdi.device}`}
type='text'
/>
</Item>
<Item label='newVmSizeLabel'>
<SizeInput
className={styles.sizeInput}
defaultValue={vdi.size}
onChange={this._getOnChangeObject('VDIs', index, 'size')}
ref={`size_${vdi.device}`}
/>
</Item>
<Item>
<Button onClick={() => this._removeVdi(index)} bsStyle='secondary'>
<Icon icon='new-vm-remove' />
</Button>
</Item>
</LineItem>
{index < this.state.state.VDIs.length - 1 && <hr />}
</div>
)}
<Item>
<Button onClick={this._addVdi} bsStyle='secondary'>
<Icon icon='new-vm-add' />
{' '}
{_('newVmAddDisk')}
</Button>
</Item>
</SectionContent>
</Section>
}
_isDisksDone = () => every(this.state.state.VDIs, vdi =>
vdi.SR && vdi.name_label && vdi.size !== undefined
) &&
every(this.state.state.existingDisks, (vdi, index) =>
vdi.$SR && vdi.name_label && vdi.size !== undefined
)
_renderSummary = () => {
const { bootAfterCreate, CPUs, existingDisks, fastClone, memory, VDIs, VIFs } = this.state.state
return <Section icon='new-vm-summary' title='newVmSummaryPanel' summary>
<SectionContent summary>
<span>
{CPUs || 0}x{' '}
<Icon icon='cpu' />
</span>
<span>
{memory ? formatSize(memory) : '0 B'}
{' '}
<Icon icon='memory' />
</span>
<span>
{size(existingDisks) + VDIs.length || 0}x{' '}
<Icon icon='disk' />
</span>
<span>
{VIFs.length}x{' '}
<Icon icon='network' />
</span>
</SectionContent>
<div style={{display: 'flex'}}>
<span style={{margin: 'auto'}}>
<input
checked={fastClone}
onChange={this._getOnChangeCheckbox('fastClone')}
ref='fastClone'
type='checkbox'
/>
{' '}
<Icon icon='vm-fast-clone' />
{' '}
{_('fastCloneVmLabel')}
</span>
</div>
<div style={{display: 'flex'}}>
<span style={{margin: 'auto'}}>
<input
checked={bootAfterCreate}
onChange={this._getOnChangeCheckbox('bootAfterCreate')}
ref='bootAfterCreate'
type='checkbox'
/>
{' '}
{_('newVmBootAfterCreate')}
</span>
</div>
</Section>
}
}
/* eslint-enable camelcase*/
| fix(new-vm): network instead of $network (#1085)
| src/xo-app/new-vm/index.js | fix(new-vm): network instead of $network (#1085) | <ide><path>rc/xo-app/new-vm/index.js
<ide> <span className={styles.inlineSelect}>
<ide> <SelectNetwork
<ide> defaultValue={vif.network}
<del> onChange={this._getOnChangeObject('VIFs', index, '$network', 'id')}
<add> onChange={this._getOnChangeObject('VIFs', index, 'network', 'id')}
<ide> predicate={this._getIsInPool()}
<ide> ref='network'
<ide> /> |
|
JavaScript | mit | 834671ab0d1d1ca1d309b8ee252e9a5b3d3cb56e | 0 | radishengine/drowsy,radishengine/drowsy |
define(['ByteSource'], function(ByteSource) {
'use strict';
var PHYSICAL_BLOCK_BYTES = 512;
var BTREE_NODE_BYTES = 512;
var MAC_CHARSET_128_255
= '\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8'
+ '\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC'
+ '\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8'
+ '\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u03A9\xE6\xF8'
+ '\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153'
+ '\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\u20AC\u2039\u203A\uFB01\uFB02'
+ '\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4'
+ '\uF8FF\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7';
function macintoshRoman(u8array, offset, length) {
switch(arguments.length) {
case 2: u8array = u8array.subarray(offset); break;
case 3: u8array = u8array.subarray(offset, offset + length); break;
}
return String.fromCharCode.apply(null, u8array)
.replace(/[\x80-\xFF]/g, function(c) {
return MAC_CHARSET_128_255[c.charCodeAt(0) - 128];
});
}
function macintoshDate(dv, offset) {
var offset = dv.getUint32(offset, false);
if (offset === 0) return null;
return new Date(new Date(1904, 0).getTime() + offset * 1000);
}
function nullTerminate(str) {
return str.replace(/\0.*/, '');
}
function extentDataRecord(dv, offset) {
var record = [];
for (var i = 0; i < 3; i++) {
record.push({
offset: dv.getUint16(offset + i*4, false),
length: dv.getUint16(offset + i*4 + 2, false),
});
}
return record;
}
function hfsPlusForkData(dv, offset) {
var forkData = {
logicalSize1: dv.getUint32(offset, false),
logicalSize2: dv.getUint32(offset + 4, false),
clumpSize: dv.getUint32(offset + 8, false),
totalBlocks: dv.getUint32(offset + 12, false),
extents: [],
};
for (var i = 0; i < 8; i++) {
forkData.extents.push({
startBlock: dv.getUint32(offset + 16 + (i * 8), false),
blockCount: dv.getUint32(offset + 16 + (i * 8) + 4, false),
});
}
return forkData;
}
hfsPlusForkData.byteLength = 8 + 4 + 4 + (8 * (4 + 4));
var PIXEL0 = new Uint8Array([255,255,255,255]);
var PIXEL1 = new Uint8Array([0,0,0,255]);
var mac4BitSystemPalette = [
[255,255,255, 255], [255,255, 0, 255], [255,102, 0, 255], [221, 0, 0, 255],
[255, 0,153, 255], [ 51, 0,153, 255], [ 0, 0,204, 255], [ 0,153,255, 255],
[ 0,170, 0, 255], [ 0,102, 0, 255], [102, 51, 0, 255], [153,102, 51, 255],
[187,187,187, 255], [136,136,136, 255], [ 68, 68, 68, 255], [ 0, 0, 0, 255],
];
var mac8BitSystemPalette = [
[255,255,255, 255], [255,255,204, 255], [255,255,153, 255], [255,255,102, 255], [255,255, 51, 255], [255,255, 0, 255],
[255,204,255, 255], [255,204,204, 255], [255,204,153, 255], [255,204,102, 255], [255,204, 51, 255], [255,204, 0, 255],
[255,153,255, 255], [255,153,204, 255], [255,153,153, 255], [255,153,102, 255], [255,153, 51, 255], [255,153, 0, 255],
[255,102,255, 255], [255,102,204, 255], [255,102,153, 255], [255,102,102, 255], [255,102, 51, 255], [255,102, 0, 255],
[255, 51,255, 255], [255, 51,204, 255], [255, 51,153, 255], [255, 51,102, 255], [255, 51, 51, 255], [255, 51, 0, 255],
[255, 0,255, 255], [255, 0,204, 255], [255, 0,153, 255], [255, 0,102, 255], [255, 0, 51, 255], [255, 0, 0, 255],
[204,255,255, 255], [204,255,204, 255], [204,255,153, 255], [204,255,102, 255], [204,255, 51, 255], [204,255, 0, 255],
[204,204,255, 255], [204,204,204, 255], [204,204,153, 255], [204,204,102, 255], [204,204, 51, 255], [204,204, 0, 255],
[204,153,255, 255], [204,153,204, 255], [204,153,153, 255], [204,153,102, 255], [204,153, 51, 255], [204,153, 0, 255],
[204,102,255, 255], [204,102,204, 255], [204,102,153, 255], [204,102,102, 255], [204,102, 51, 255], [204,102, 0, 255],
[204, 51,255, 255], [204, 51,204, 255], [204, 51,153, 255], [204, 51,102, 255], [204, 51, 51, 255], [204, 51, 0, 255],
[204, 0,255, 255], [204, 0,204, 255], [204, 0,153, 255], [204, 0,102, 255], [204, 0, 51, 255], [204, 0, 0, 255],
[153,255,255, 255], [153,255,204, 255], [153,255,153, 255], [153,255,102, 255], [153,255, 51, 255], [153,255, 0, 255],
[153,204,255, 255], [153,204,204, 255], [153,204,153, 255], [153,204,102, 255], [153,204, 51, 255], [153,204, 0, 255],
[153,153,255, 255], [153,153,204, 255], [153,153,153, 255], [153,153,102, 255], [153,153, 51, 255], [153,153, 0, 255],
[153,102,255, 255], [153,102,204, 255], [153,102,153, 255], [153,102,102, 255], [153,102, 51, 255], [153,102, 0, 255],
[153, 51,255, 255], [153, 51,204, 255], [153, 51,153, 255], [153, 51,102, 255], [153, 51, 51, 255], [153, 51, 0, 255],
[153, 0,255, 255], [153, 0,204, 255], [153, 0,153, 255], [153, 0,102, 255], [153, 0, 51, 255], [153, 0, 0, 255],
[102,255,255, 255], [102,255,204, 255], [102,255,153, 255], [102,255,102, 255], [102,255, 51, 255], [102,255, 0, 255],
[102,204,255, 255], [102,204,204, 255], [102,204,153, 255], [102,204,102, 255], [102,204, 51, 255], [102,204, 0, 255],
[102,153,255, 255], [102,153,204, 255], [102,153,153, 255], [102,153,102, 255], [102,153, 51, 255], [102,153, 0, 255],
[102,102,255, 255], [102,102,204, 255], [102,102,153, 255], [102,102,102, 255], [102,102, 51, 255], [102,102, 0, 255],
[102, 51,255, 255], [102, 51,204, 255], [102, 51,153, 255], [102, 51,102, 255], [102, 51, 51, 255], [102, 51, 0, 255],
[102, 0,255, 255], [102, 0,204, 255], [102, 0,153, 255], [102, 0,102, 255], [102, 0, 51, 255], [102, 0, 0, 255],
[ 51,255,255, 255], [ 51,255,204, 255], [ 51,255,153, 255], [ 51,255,102, 255], [ 51,255, 51, 255], [ 51,255, 0, 255],
[ 51,204,255, 255], [ 51,204,204, 255], [ 51,204,153, 255], [ 51,204,102, 255], [ 51,204, 51, 255], [ 51,204, 0, 255],
[ 51,153,255, 255], [ 51,153,204, 255], [ 51,153,153, 255], [ 51,153,102, 255], [ 51,153, 51, 255], [ 51,153, 0, 255],
[ 51,102,255, 255], [ 51,102,204, 255], [ 51,102,153, 255], [ 51,102,102, 255], [ 51,102, 51, 255], [ 51,102, 0, 255],
[ 51, 51,255, 255], [ 51, 51,204, 255], [ 51, 51,153, 255], [ 51, 51,102, 255], [ 51, 51, 51, 255], [ 51, 51, 0, 255],
[ 51, 0,255, 255], [ 51, 0,204, 255], [ 51, 0,153, 255], [ 51, 0,102, 255], [ 51, 0, 51, 255], [ 51, 0, 0, 255],
[ 0,255,255, 255], [ 0,255,204, 255], [ 0,255,153, 255], [ 0,255,102, 255], [ 0,255, 51, 255], [ 0,255, 0, 255],
[ 0,204,255, 255], [ 0,204,204, 255], [ 0,204,153, 255], [ 0,204,102, 255], [ 0,204, 51, 255], [ 0,204, 0, 255],
[ 0,153,255, 255], [ 0,153,204, 255], [ 0,153,153, 255], [ 0,153,102, 255], [ 0,153, 51, 255], [ 0,153, 0, 255],
[ 0,102,255, 255], [ 0,102,204, 255], [ 0,102,153, 255], [ 0,102,102, 255], [ 0,102, 51, 255], [ 0,102, 0, 255],
[ 0, 51,255, 255], [ 0, 51,204, 255], [ 0, 51,153, 255], [ 0, 51,102, 255], [ 0, 51, 51, 255], [ 0, 51, 0, 255],
[ 0, 0,255, 255], [ 0, 0,204, 255], [ 0, 0,153, 255], [ 0, 0,102, 255], [ 0, 0, 51, 255],
[238,0,0, 255], [221,0,0, 255], [187,0,0, 255], [170,0,0, 255], [136,0,0, 255],
[119,0,0, 255], [ 85,0,0, 255], [ 68,0,0, 255], [ 34,0,0, 255], [ 17,0,0, 255],
[0,238,0, 255], [0,221,0, 255], [0,187,0, 255], [0,170,0, 255], [0,136,0, 255],
[0,119,0, 255], [0, 85,0, 255], [0, 68,0, 255], [0, 34,0, 255], [0, 17,0, 255],
[0,0,238, 255], [0,0,221, 255], [0,0,187, 255], [0,0,170, 255], [0,0,136, 255],
[0,0,119, 255], [0,0, 85, 255], [0,0, 68, 255], [0,0, 34, 255], [0,0, 17, 255],
[238,238,238, 255], [221,221,221, 255], [187,187,187, 255], [170,170,170, 255], [136,136,136, 255],
[119,119,119, 255], [ 85, 85, 85, 255], [ 68, 68, 68, 255], [ 34, 34, 34, 255], [ 17, 17, 17, 255],
[0,0,0,255],
];
function AppleVolume(byteSource) {
this.byteSource = byteSource;
}
AppleVolume.prototype = {
read: function(reader) {
this.readPartitions(this.byteSource, reader);
},
readPartitions: function(byteSource, reader) {
var self = this;
function doPartition(n) {
byteSource.slice(PHYSICAL_BLOCK_BYTES * n, PHYSICAL_BLOCK_BYTES * (n+1)).read({
onbytes: function(bytes) {
if (macintoshRoman(bytes, 0, 4) !== 'PM\0\0') {
console.error('invalid partition map signature');
return;
}
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var mapBlockCount = dv.getInt32(4, false);
var partitionInfo = {
blockOffset: dv.getInt32(8, false),
blockCount: dv.getInt32(12, false),
type: nullTerminate(macintoshRoman(bytes, 48, 32)),
status: dv.getInt32(88, false),
};
var dataAreaBlockCount = dv.getInt32(84, false);
if (dataAreaBlockCount > 0) {
partitionInfo.dataArea = {
blockCount: dataAreaBlockCount,
blockOffset: dv.getInt32(80, false),
};
}
var bootCodeByteLength = dv.getInt32(96, false);
if (bootCodeByteLength > 0) {
partitionInfo.bootCode = {
byteLength: bootCodeByteLength,
blockOffset: dv.getInt32(92, false),
loadAddress: dv.getInt32(100, false),
entryPoint: dv.getInt32(108, false),
checksum: dv.getInt32(116, false),
};
}
var partitionName = nullTerminate(macintoshRoman(bytes, 16, 32));
if (partitionName) partitionInfo.name = partitionName;
var processorType = nullTerminate(macintoshRoman(bytes, 124, 16));
if (processorType) partitionInfo.processorType = processorType;
switch (partitionInfo.type) {
case 'Apple_HFS':
self.readHFS(
byteSource.slice(
PHYSICAL_BLOCK_BYTES * partitionInfo.blockOffset,
PHYSICAL_BLOCK_BYTES * (partitionInfo.blockOffset + partitionInfo.blockCount)),
reader);
break;
default:
break;
}
if (typeof reader.onpartition === 'function') {
reader.onpartition(partitionInfo);
}
if (n < mapBlockCount) {
doPartition(n + 1);
}
},
});
}
doPartition(1);
},
readHFS: function(byteSource, reader) {
var self = this;
// first 2 blocks are boot blocks
var masterDirectoryBlock = byteSource.slice(PHYSICAL_BLOCK_BYTES * 2, PHYSICAL_BLOCK_BYTES * (2+1));
masterDirectoryBlock.read({
onbytes: function(bytes) {
var tag;
switch(tag = macintoshRoman(bytes, 0, 2)) {
case 'BD':
this.onhfs(bytes);
break;
case 'H+':
this.onhfsplus(bytes);
break;
default:
console.error('Unknown master directory block signature: ' + tag);
break;
}
},
onhfs: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var volumeInfo = {
createdAt: macintoshDate(dv, 2),
lastModifiedAt: macintoshDate(dv, 6),
attributes: dv.getUint16(10, false),
rootFileCount: dv.getUint16(12, false),
bitmapBlockOffset: dv.getUint16(14, false), // always 3?
nextAllocationSearch: dv.getUint16(16, false), // used internally
allocationBlockCount: dv.getUint16(18, false),
allocationBlockByteLength: dv.getInt32(20, false), // size of one block, always multiple of 512
defaultClumpSize: dv.getInt32(24, false),
allocationBlocksOffset: dv.getUint16(28, false),
nextUnusedCatalogNodeId: dv.getInt32(30, false), // catalog node: file or folder
unusedAllocationBlockCount: dv.getUint16(34, false),
name: nullTerminate(macintoshRoman(bytes, 36 + 1, bytes[36])),
lastBackupAt: macintoshDate(dv, 64),
backupSequenceNumber: dv.getUint16(68, false), // used internally
writeCount: dv.getInt32(70, false),
extentsOverflowFileClumpSize: dv.getInt32(74, false),
catalogFileClumpSize: dv.getInt32(78, false),
rootFolderCount: dv.getUint16(82, false),
fileCount: dv.getInt32(84, false),
folderCount: dv.getInt32(88, false),
finderInfo: [
dv.getInt32(92, false),
dv.getInt32(96, false),
dv.getInt32(100, false),
dv.getInt32(104, false),
dv.getInt32(108, false),
dv.getInt32(112, false),
dv.getInt32(116, false),
dv.getInt32(120, false),
],
cacheBlockCount: dv.getUint16(124, false), // used internally
bitmapCacheBlockCount: dv.getUint16(126, false), // used internally
commonCacheBlockCount: dv.getUint16(128, false), // used internally
extentsOverflowFileByteLength: dv.getInt32(130, false),
extentsOverflowFileExtentRecord: extentDataRecord(dv, 134),
catalogFileByteLength: dv.getInt32(146, false),
catalogFileExtentRecord: extentDataRecord(dv, 150),
};
if (typeof reader.onvolumestart === 'function') {
reader.onvolumestart(volumeInfo);
}
var allocationBlocksAt = PHYSICAL_BLOCK_BYTES * volumeInfo.allocationBlocksOffset;
var allocationBlocksLen = volumeInfo.allocationBlockByteLength * volumeInfo.allocationBlockCount;
var allocationBlocks = byteSource.slice(allocationBlocksAt, allocationBlocksAt + allocationBlocksLen);
allocationBlocks.blockSize = volumeInfo.allocationBlockByteLength;
var catalogExtents = volumeInfo.catalogFileExtentRecord[0];
catalogExtents = allocationBlocks.slice(
allocationBlocks.blockSize * catalogExtents.offset,
allocationBlocks.blockSize * catalogExtents.offset + volumeInfo.catalogFileByteLength);
catalogExtents.allocationBlocks = allocationBlocks;
self.readCatalog(catalogExtents, {
});
},
onhfsplus: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var volumeInfo = {
version: dv.getUint16(2, false),
attributes: dv.getUint32(4, false),
lastMountedVersion: macintoshRoman(bytes, 8, 4),
journalInfoBlock: dv.getUint32(12, false),
createdAt: macintoshDate(dv, 16),
lastModifiedAt: macintoshDate(dv, 20),
backupAt: macintoshDate(dv, 24),
fileCount: dv.getUint32(28, false),
folderCount: dv.getUint32(32, false),
blockSize: dv.getUint32(36, false),
totalBlocks: dv.getUint32(40, false),
freeBlocks: dv.getUint32(44, false),
nextAllocation: dv.getUint32(48, false),
resourceClumpSize: dv.getUint32(52, false),
dataClumpSize: dv.getUint32(56, false),
nextCatalogId: dv.getUint32(60, false),
writeCount: dv.getUint32(64, false),
encodingsBitmap1: dv.getUint32(68, false),
encodingsBitmap2: dv.getUint32(72, false),
finderInfo: [
dv.getInt32(76, false),
dv.getInt32(80, false),
dv.getInt32(84, false),
dv.getInt32(88, false),
dv.getInt32(92, false),
dv.getInt32(96, false),
dv.getInt32(100, false),
dv.getInt32(104, false),
],
allocationFile: hfsPlusForkData(dv, 108),
extentsFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength),
catalogFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 2),
attributesFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 3),
startupFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 4),
};
console.log(volumeInfo);
},
});
},
readCatalog: function(byteSource, reader) {
var self = this;
var folders = {};
var allocation = byteSource.allocationBlocks;
this.readBTreeNode(byteSource.slice(0, BTREE_NODE_BYTES), {
onheadernode: function(headerNode) {
var rootNode = byteSource.slice(
headerNode.rootNodeNumber * BTREE_NODE_BYTES,
(headerNode.rootNodeNumber + 1) * BTREE_NODE_BYTES);
self.readBTreeNode(rootNode, this);
},
onindexnode: function(indexNode) {
for (var i = 0; i < indexNode.pointers.length; i++) {
var pointer = indexNode.pointers[i];
var pointedBytes = byteSource.slice(
pointer.nodeNumber * BTREE_NODE_BYTES,
(pointer.nodeNumber + 1) * BTREE_NODE_BYTES);
self.readBTreeNode(pointedBytes, this);
}
},
onfolderthread: function(threadInfo) {
},
onfolder: function(folderInfo) {
var container = document.createElement('DETAILS');
if (folderInfo.isInvisible) {
container.classList.add('invisible');
}
container.classList.add('folder');
container.dataset.name = folderInfo.name;
var title = document.createElement('SUMMARY');
title.innerHTML = folderInfo.name;
container.appendChild(title);
var timestamp = folderInfo.modifiedAt || folderInfo.createdAt;
if (timestamp) {
container.dataset.lastModified = timestamp.toISOString();
}
if (folderInfo.id in folders) {
container.appendChild(folders[folderInfo.id]);
}
else {
var children = document.createElement('SECTION');
children.classList.add('folder-children');
container.appendChild(children);
folders[folderInfo.id] = children;
}
if (folderInfo.parentDirectoryId === 1) {
container.setAttribute('open', 'open');
document.body.appendChild(container);
}
else if (folderInfo.parentDirectoryId in folders) {
folders[folderInfo.parentDirectoryId].appendChild(container);
}
else {
var siblings = document.createElement('SECTION');
siblings.classList.add('folder-children');
siblings.appendChild(container);
folders[folderInfo.parentDirectoryId] = siblings;
}
},
onfile: function(fileInfo) {
var container = document.createElement('DETAILS');
if (fileInfo.isInvisible) {
container.classList.add('invisible');
}
container.classList.add('file');
container.dataset.name = fileInfo.name;
var title = document.createElement('SUMMARY');
title.innerHTML = fileInfo.name;
container.appendChild(title);
if (fileInfo.type !== null) {
container.dataset.macType = fileInfo.type;
}
if (fileInfo.creator !== null) {
container.dataset.macCreator = fileInfo.creator;
}
var timestamp = fileInfo.modifiedAt || fileInfo.createdAt;
if (timestamp) {
container.dataset.lastModified = timestamp.toISOString();
}
if (fileInfo.dataFork.logicalEOF) {
var dataFork = document.createElement('A');
dataFork.setAttribute('href', '#');
dataFork.classList.add('data-fork');
dataFork.innerText = 'Data Fork';
var extent = fileInfo.dataFork.firstExtentRecord[0];
allocation.slice(
allocation.blockSize * extent.offset,
allocation.blockSize * extent.offset + fileInfo.dataFork.logicalEOF
).getURL().then(function(url) {
dataFork.setAttribute('href', url);
dataFork.setAttribute('download', fileInfo.name);
});
dataFork.dataset.size = fileInfo.dataFork.logicalEOF;
container.appendChild(dataFork);
}
if (fileInfo.resourceFork.logicalEOF) {
var extent = fileInfo.resourceFork.firstExtentRecord[0];
self.readResourceFork(allocation.slice(
allocation.blockSize * extent.offset,
allocation.blockSize * extent.offset + fileInfo.resourceFork.logicalEOF
), {
onresource: function(resource) {
var resourceEl = document.createElement('DIV');
resourceEl.classList.add('resource');
if (resource.name !== null) {
resourceEl.dataset.name = resource.name;
}
resourceEl.dataset.type = resource.type;
resourceEl.dataset.id = resource.id;
resourceEl.dataset.size = resource.data.length;
if ('image' in resource) {
var img = document.createElement('IMG');
img.width = resource.image.width;
img.height = resource.image.height;
img.src = resource.image.url;
img.style.background = '#ccc';
if ('hotspot' in resource) {
img.style.cursor = 'url(' + resource.image.url + ') '
+ resource.hotspot.x + ' ' + resource.hotspot.y + ', url(' + resource.image.url + '), auto';
}
resourceEl.appendChild(img);
}
if ('text' in resource) {
var scr = document.createElement('SCRIPT');
scr.setAttribute('type', 'text/plain');
scr.appendChild(document.createTextNode(resource.text));
resourceEl.appendChild(scr);
}
container.appendChild(resourceEl);
}
});
}
if (fileInfo.parentDirectoryId === 1) {
document.body.appendChild(container);
}
else if (fileInfo.parentDirectoryId in folders) {
folders[fileInfo.parentDirectoryId].appendChild(container);
}
else {
var siblings = document.createElement('SECTION');
siblings.classList.add('folder-children');
siblings.appendChild(container);
folders[fileInfo.parentDirectoryId] = siblings;
}
},
});
},
readResourceFork: function(byteSource, reader) {
byteSource.read({
onbytes: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffet, bytes.byteLength);
var dataOffset = dv.getUint32(0, false);
var mapDV = new DataView(bytes.buffer, bytes.byteOffset + dv.getUint32(4, false), dv.getUint32(12, false));
var attributes = mapDV.getUint16(22, false);
var isReadOnly = !!(attributes & 0x80);
var typeListOffset = mapDV.getUint16(24, false);
var nameListOffset = mapDV.getUint16(26, false);
var typeCount = mapDV.getInt16(typeListOffset, false) + 1;
var resources = [];
for (var i = 0; i < typeCount; i++) {
var resourceTypeName = macintoshRoman(
new Uint8Array(mapDV.buffer, mapDV.byteOffset + typeListOffset + 2 + (i * 8), 4),
0, 4);
var resourceCount = mapDV.getInt16(typeListOffset + 2 + (i * 8) + 4, false) + 1;
var referenceListOffset = mapDV.getUint16(typeListOffset + 2 + (i * 8) + 4 + 2, false);
var referenceListDV = new DataView(
mapDV.buffer,
mapDV.byteOffset + typeListOffset + referenceListOffset,
resourceCount * 12);
for (var j = 0; j < resourceCount; j++) {
var resourceID = referenceListDV.getUint16(j * 12, false);
var resourceNameOffset = referenceListDV.getInt16(j * 12 + 2, false);
var resourceAttributes = referenceListDV.getUint8(j * 12 + 4, false);
var resourceDataOffset = referenceListDV.getUint32(j * 12 + 4, false) & 0xffffff;
var resourceName;
if (resourceNameOffset === -1) {
resourceName = null;
}
else {
resourceNameOffset += nameListOffset;
resourceName = new Uint8Array(
mapDV.buffer,
mapDV.byteOffset + resourceNameOffset + 1,
mapDV.getUint8(resourceNameOffset));
resourceName = macintoshRoman(resourceName, 0, resourceName.length);
}
resourceDataOffset += dataOffset;
var data = bytes.subarray(
resourceDataOffset + 4,
resourceDataOffset + 4 + dv.getUint32(resourceDataOffset, false));
var resource = {
name: resourceName,
type: resourceTypeName,
id: resourceID,
data: data,
};
switch (resource.type) {
case 'STR ':
resource.text = macintoshRoman(resource.data, 0, resource.data.length);
break;
case 'CURS':
if (resource.data.length !== 68) {
console.error('CURS resource expected to be 68 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 32; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[32 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
var hotspotDV = new DataView(resource.data.buffer, resource.data.byteOffset + 64, 8);
resource.hotspot = {y:hotspotDV.getInt16(0), x:hotspotDV.getInt16(2)};
break;
case 'ICN#':
if (resource.data.length !== 256) {
console.error('ICS# resource expected to be 256 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 32;
img.height = 32;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(32, 32);
for (var ibyte = 0; ibyte < 128; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[128 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:32, height:32};
break;
case 'ics#':
if (resource.data.length !== 64) {
console.error('ics# resource expected to be 64 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 32; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[32 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
break;
case 'icl8':
if (resource.data.length !== 1024) {
console.error('icl8 resource expected to be 1024 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 32;
img.height = 32;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(32, 32);
for (var ibyte = 0; ibyte < 1024; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte]], ibyte*4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:32, height:32};
break;
case 'ics8':
if (resource.data.length !== 256) {
console.error('ics8 resource expected to be 256 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 256; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte]], ibyte*4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
break;
case 'icl4':
if (resource.data.length !== 512) {
console.error('icl4 resource expected to be 512 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 32;
img.height = 32;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(32, 32);
for (var ibyte = 0; ibyte < 512; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte] >> 4], ibyte*8);
pix.data.set(mac8BitSystemPalette[resource.data[ibyte] & 15], ibyte*8 + 4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:32, height:32};
break;
case 'ics4':
if (resource.data.length !== 128) {
console.error('ics4 resource expected to be 128 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 128; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte] >> 4], ibyte*8);
pix.data.set(mac8BitSystemPalette[resource.data[ibyte] & 15], ibyte*8 + 4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
break;
}
if (resourceAttributes & 0x40) resource.loadInSystemHeap = true; // instead of application heap
if (resourceAttributes & 0x20) resource.mayBePagedOutOfMemory = true;
if (resourceAttributes & 0x10) resource.doNotMoveInMemory = true;
if (resourceAttributes & 0x08) resource.isReadOnly = true;
if (resourceAttributes & 0x04) resource.preload = true;
if (resourceAttributes & 0x01) resource.compressed = true;
if (typeof reader.onresource === 'function') {
reader.onresource(resource);
}
}
}
},
});
},
readBTreeNode: function(byteSource, reader) {
var self = this;
byteSource.read({
onbytes: function(bytes) {
var node = {};
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var records = new Array(dv.getUint16(10, false));
for (var i = 0; i < records.length; i++) {
records[i] = bytes.subarray(
dv.getUint16(BTREE_NODE_BYTES - 2*(i+1), false),
dv.getUint16(BTREE_NODE_BYTES - 2*(i+2), false));
}
var forwardLink = dv.getInt32(0, false);
var backwardLink = dv.getInt32(4, false);
if (forwardLink !== 0) node.forwardLink = forwardLink;
if (backwardLink !== 0) node.backwardLink = backwardLink;
node.depth = bytes[9];
switch(bytes[8]) {
case 0: // index
node.pointers = [];
for (var i = 0; i < records.length; i++) {
var recordBytes = records[i];
var keyLength;
if (recordBytes.length === 0 || (keyLength = recordBytes[0]) === 0) {
// deleted record
continue;
}
var dv = new DataView(recordBytes.buffer, recordBytes.byteOffset, recordBytes.byteLength);
var parentDirectoryID = dv.getUint32(2, false);
var name = macintoshRoman(recordBytes, 7, recordBytes[6]);
var nodeNumber = dv.getUint32(1 + keyLength, false);
node.pointers.push({name:name, nodeNumber:nodeNumber, parentDirectoryID:parentDirectoryID});
}
if (typeof reader.onindexnode === 'function') {
reader.onindexnode(node);
}
break;
case 1: // header
if (records.length !== 3) {
console.error('header node: expected 3 records, got ' + recordCount);
return;
}
var recordDV = new DataView(records[0].buffer, records[0].byteOffset, records[0].byteLength);
node.treeDepth = recordDV.getUint16(0, false);
node.rootNodeNumber = recordDV.getUint32(2, false);
node.leafRecordCount = recordDV.getUint32(6, false);
node.firstLeaf = recordDV.getUint32(10, false);
node.lastLeaf = recordDV.getUint32(14, false);
node.nodeByteLength = recordDV.getUint16(18, false); // always 512?
node.maxKeyByteLength = recordDV.getUint16(20, false);
node.nodeCount = recordDV.getUint32(22, false);
node.freeNodeCount = recordDV.getUint32(26, false);
node.bitmap = records[2];
if (typeof reader.onheadernode === 'function') {
reader.onheadernode(node);
}
break;
case 2: // map
console.error('NYI: map node');
break;
case 0xff: // leaf
for (var i = 0; i < records.length; i++) {
var record = records[i];
var keyLength;
if (record.length === 0 || (keyLength = record[0]) === 0) {
// deleted record
continue;
}
var dv = new DataView(record.buffer, record.byteOffset, record.byteLength);
var parentDirectoryId = dv.getUint32(2, false);
var name = macintoshRoman(record, 7, record[6]);
var offset = 1 + keyLength;
offset = offset + (offset % 2);
record = record.subarray(offset);
dv = new DataView(record.buffer, record.byteOffset, record.byteLength);
switch(record[0]) {
case 1: // folder
var folderInfo = {
name: name,
id: dv.getUint32(6, false),
modifiedAt: macintoshDate(dv, 14),
location: {
v: dv.getInt16(32, false),
h: dv.getInt16(34, false),
},
window: {
top: dv.getInt16(22, false),
left: dv.getInt16(24, false),
bottom: dv.getInt16(26, false),
right: dv.getInt16(28, false),
scroll: {
v: dv.getInt16(38, false),
h: dv.getInt16(40, false),
},
},
parentDirectoryId: parentDirectoryId,
// dinfoReserved: dv.getInt16(36, false),
// dxinfoReserved: dv.getInt32(42, false),
dxinfoFlags: dv.getUint16(46, false),
dxinfoComment: dv.getUint16(48, false),
fileCount: dv.getUint16(4, false),
createdAt: macintoshDate(dv, 10),
backupAt: macintoshDate(dv, 18),
putAwayFolderID: dv.getInt32(50, false),
flags: dv.getUint16(2, false),
};
if (!folderInfo.flags) delete folderInfo.flags;
var dinfoFlags = dv.getUint16(30, false);
if (dinfoFlags & 0x0001) folderInfo.isOnDesk = true;
if (dinfoFlags & 0x000E) folderInfo.color = true;
if (dinfoFlags & 0x0020) folderInfo.requireSwitchLaunch = true;
if (dinfoFlags & 0x0400) folderInfo.hasCustomIcon = true;
if (dinfoFlags & 0x1000) folderInfo.nameLocked = true;
if (dinfoFlags & 0x2000) folderInfo.hasBundle = true;
if (dinfoFlags & 0x4000) folderInfo.isInvisible = true;
if (typeof reader.onfolder === 'function') {
reader.onfolder(folderInfo);
}
break;
case 2: // file
var fileInfo = {
name: name,
creator: macintoshRoman(record, 8, 4),
type: macintoshRoman(record, 4, 4),
id: dv.getUint32(20, false),
parentDirectoryId: parentDirectoryId,
// type: record[3], /* always zero */
position: {v:dv.getInt16(14, false), h:dv.getInt16(16, false)},
// finfoReserved: dv.getInt16(18, false),
dataFork: {
firstAllocationBlock: dv.getUint16(24, false),
logicalEOF: dv.getUint32(26, false),
physicalEOF: dv.getUint32(30, false),
firstExtentRecord: extentDataRecord(dv, 74),
},
resourceFork: {
firstAllocationBlock: dv.getUint16(34, false),
logicalEOF: dv.getUint32(36, false),
physicalEOF: dv.getUint32(40, false),
firstExtentRecord: extentDataRecord(dv, 86),
},
createdAt: macintoshDate(dv, 44),
modifiedAt: macintoshDate(dv, 48),
backupAt: macintoshDate(dv, 52),
// fxinfoReserved: (8 bytes)
fxinfoFlags: dv.getUint16(64, false),
putAwayFolderID: dv.getUint32(68, false),
clumpSize: dv.getUint16(72),
};
if (fileInfo.creator === '\0\0\0\0') fileInfo.creator = null;
if (fileInfo.type === '\0\0\0\0') fileInfo.type = null;
if (!(fileInfo.position.v || fileInfo.position.h)) fileInfo.position = 'default';
if (record[2] & 0x01) fileInfo.locked = true;
if (record[2] & 0x02) fileInfo.hasThreadRecord = true;
if (record[2] & 0x80) fileInfo.recordUsed = true;
var finfoFlags = dv.getUint16(12, false);
if (finfoFlags & 0x0001) fileInfo.isOnDesk = true;
if (finfoFlags & 0x000E) fileInfo.color = true;
if (finfoFlags & 0x0020) fileInfo.requireSwitchLaunch = true;
if (finfoFlags & 0x0040) fileInfo.isShared = true;
if (finfoFlags & 0x0080) fileInfo.hasNoINITs = true;
if (finfoFlags & 0x0100) fileInfo.hasBeenInited = true;
if (finfoFlags & 0x0400) fileInfo.hasCustomIcon = true;
if (finfoFlags & 0x0800) fileInfo.isStationery = true;
if (finfoFlags & 0x1000) fileInfo.nameLocked = true;
if (finfoFlags & 0x2000) fileInfo.hasBundle = true;
if (finfoFlags & 0x4000) fileInfo.isInvisible = true;
if (finfoFlags & 0x8000) fileInfo.isAlias = true;
if (typeof reader.onfile === 'function') {
reader.onfile(fileInfo);
}
break;
case 3: // folder thread
case 4: // file thread
var threadInfo = {
parentDirectoryId: parentDirectoryId,
parentFolderID: dv.getUint32(10, false),
parentFolderName: macintoshRoman(record, 15, record[14]),
};
if (record[0] === 3) {
if (typeof reader.onfolderthread === 'function') {
reader.onfolderthread(threadInfo);
}
}
else {
if (typeof reader.onfilethread === 'function') {
reader.onfilethread(threadInfo);
}
}
break;
default:
console.error('unknown folder record type: ' + dv.getUint8(0));
break;
}
}
if (typeof reader.onleafnode === 'function') {
reader.onleafnode(node);
}
break;
default:
console.error('unknown node type: ' + bytes[8]);
break;
}
}
});
},
};
return AppleVolume;
});
| AppleVolume.js |
define(['ByteSource'], function(ByteSource) {
'use strict';
var PHYSICAL_BLOCK_BYTES = 512;
var BTREE_NODE_BYTES = 512;
var MAC_CHARSET_128_255
= '\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8'
+ '\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC'
+ '\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8'
+ '\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u03A9\xE6\xF8'
+ '\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153'
+ '\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\u20AC\u2039\u203A\uFB01\uFB02'
+ '\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4'
+ '\uF8FF\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7';
function macintoshRoman(u8array, offset, length) {
switch(arguments.length) {
case 2: u8array = u8array.subarray(offset); break;
case 3: u8array = u8array.subarray(offset, offset + length); break;
}
return String.fromCharCode.apply(null, u8array)
.replace(/[\x80-\xFF]/g, function(c) {
return MAC_CHARSET_128_255[c.charCodeAt(0) - 128];
});
}
function macintoshDate(dv, offset) {
var offset = dv.getUint32(offset, false);
if (offset === 0) return null;
return new Date(new Date(1904, 0).getTime() + offset * 1000);
}
function nullTerminate(str) {
return str.replace(/\0.*/, '');
}
function extentDataRecord(dv, offset) {
var record = [];
for (var i = 0; i < 3; i++) {
record.push({
offset: dv.getUint16(offset + i*4, false),
length: dv.getUint16(offset + i*4 + 2, false),
});
}
return record;
}
function hfsPlusForkData(dv, offset) {
var forkData = {
logicalSize1: dv.getUint32(offset, false),
logicalSize2: dv.getUint32(offset + 4, false),
clumpSize: dv.getUint32(offset + 8, false),
totalBlocks: dv.getUint32(offset + 12, false),
extents: [],
};
for (var i = 0; i < 8; i++) {
forkData.extents.push({
startBlock: dv.getUint32(offset + 16 + (i * 8), false),
blockCount: dv.getUint32(offset + 16 + (i * 8) + 4, false),
});
}
return forkData;
}
hfsPlusForkData.byteLength = 8 + 4 + 4 + (8 * (4 + 4));
var PIXEL0 = new Uint8Array([255,255,255,255]);
var PIXEL1 = new Uint8Array([0,0,0,255]);
var mac8BitSystemPalette = [
[255,255,255, 255], [255,255,204, 255], [255,255,153, 255], [255,255,102, 255], [255,255, 51, 255], [255,255, 0, 255],
[255,204,255, 255], [255,204,204, 255], [255,204,153, 255], [255,204,102, 255], [255,204, 51, 255], [255,204, 0, 255],
[255,153,255, 255], [255,153,204, 255], [255,153,153, 255], [255,153,102, 255], [255,153, 51, 255], [255,153, 0, 255],
[255,102,255, 255], [255,102,204, 255], [255,102,153, 255], [255,102,102, 255], [255,102, 51, 255], [255,102, 0, 255],
[255, 51,255, 255], [255, 51,204, 255], [255, 51,153, 255], [255, 51,102, 255], [255, 51, 51, 255], [255, 51, 0, 255],
[255, 0,255, 255], [255, 0,204, 255], [255, 0,153, 255], [255, 0,102, 255], [255, 0, 51, 255], [255, 0, 0, 255],
[204,255,255, 255], [204,255,204, 255], [204,255,153, 255], [204,255,102, 255], [204,255, 51, 255], [204,255, 0, 255],
[204,204,255, 255], [204,204,204, 255], [204,204,153, 255], [204,204,102, 255], [204,204, 51, 255], [204,204, 0, 255],
[204,153,255, 255], [204,153,204, 255], [204,153,153, 255], [204,153,102, 255], [204,153, 51, 255], [204,153, 0, 255],
[204,102,255, 255], [204,102,204, 255], [204,102,153, 255], [204,102,102, 255], [204,102, 51, 255], [204,102, 0, 255],
[204, 51,255, 255], [204, 51,204, 255], [204, 51,153, 255], [204, 51,102, 255], [204, 51, 51, 255], [204, 51, 0, 255],
[204, 0,255, 255], [204, 0,204, 255], [204, 0,153, 255], [204, 0,102, 255], [204, 0, 51, 255], [204, 0, 0, 255],
[153,255,255, 255], [153,255,204, 255], [153,255,153, 255], [153,255,102, 255], [153,255, 51, 255], [153,255, 0, 255],
[153,204,255, 255], [153,204,204, 255], [153,204,153, 255], [153,204,102, 255], [153,204, 51, 255], [153,204, 0, 255],
[153,153,255, 255], [153,153,204, 255], [153,153,153, 255], [153,153,102, 255], [153,153, 51, 255], [153,153, 0, 255],
[153,102,255, 255], [153,102,204, 255], [153,102,153, 255], [153,102,102, 255], [153,102, 51, 255], [153,102, 0, 255],
[153, 51,255, 255], [153, 51,204, 255], [153, 51,153, 255], [153, 51,102, 255], [153, 51, 51, 255], [153, 51, 0, 255],
[153, 0,255, 255], [153, 0,204, 255], [153, 0,153, 255], [153, 0,102, 255], [153, 0, 51, 255], [153, 0, 0, 255],
[102,255,255, 255], [102,255,204, 255], [102,255,153, 255], [102,255,102, 255], [102,255, 51, 255], [102,255, 0, 255],
[102,204,255, 255], [102,204,204, 255], [102,204,153, 255], [102,204,102, 255], [102,204, 51, 255], [102,204, 0, 255],
[102,153,255, 255], [102,153,204, 255], [102,153,153, 255], [102,153,102, 255], [102,153, 51, 255], [102,153, 0, 255],
[102,102,255, 255], [102,102,204, 255], [102,102,153, 255], [102,102,102, 255], [102,102, 51, 255], [102,102, 0, 255],
[102, 51,255, 255], [102, 51,204, 255], [102, 51,153, 255], [102, 51,102, 255], [102, 51, 51, 255], [102, 51, 0, 255],
[102, 0,255, 255], [102, 0,204, 255], [102, 0,153, 255], [102, 0,102, 255], [102, 0, 51, 255], [102, 0, 0, 255],
[ 51,255,255, 255], [ 51,255,204, 255], [ 51,255,153, 255], [ 51,255,102, 255], [ 51,255, 51, 255], [ 51,255, 0, 255],
[ 51,204,255, 255], [ 51,204,204, 255], [ 51,204,153, 255], [ 51,204,102, 255], [ 51,204, 51, 255], [ 51,204, 0, 255],
[ 51,153,255, 255], [ 51,153,204, 255], [ 51,153,153, 255], [ 51,153,102, 255], [ 51,153, 51, 255], [ 51,153, 0, 255],
[ 51,102,255, 255], [ 51,102,204, 255], [ 51,102,153, 255], [ 51,102,102, 255], [ 51,102, 51, 255], [ 51,102, 0, 255],
[ 51, 51,255, 255], [ 51, 51,204, 255], [ 51, 51,153, 255], [ 51, 51,102, 255], [ 51, 51, 51, 255], [ 51, 51, 0, 255],
[ 51, 0,255, 255], [ 51, 0,204, 255], [ 51, 0,153, 255], [ 51, 0,102, 255], [ 51, 0, 51, 255], [ 51, 0, 0, 255],
[ 0,255,255, 255], [ 0,255,204, 255], [ 0,255,153, 255], [ 0,255,102, 255], [ 0,255, 51, 255], [ 0,255, 0, 255],
[ 0,204,255, 255], [ 0,204,204, 255], [ 0,204,153, 255], [ 0,204,102, 255], [ 0,204, 51, 255], [ 0,204, 0, 255],
[ 0,153,255, 255], [ 0,153,204, 255], [ 0,153,153, 255], [ 0,153,102, 255], [ 0,153, 51, 255], [ 0,153, 0, 255],
[ 0,102,255, 255], [ 0,102,204, 255], [ 0,102,153, 255], [ 0,102,102, 255], [ 0,102, 51, 255], [ 0,102, 0, 255],
[ 0, 51,255, 255], [ 0, 51,204, 255], [ 0, 51,153, 255], [ 0, 51,102, 255], [ 0, 51, 51, 255], [ 0, 51, 0, 255],
[ 0, 0,255, 255], [ 0, 0,204, 255], [ 0, 0,153, 255], [ 0, 0,102, 255], [ 0, 0, 51, 255],
[238,0,0, 255], [221,0,0, 255], [187,0,0, 255], [170,0,0, 255], [136,0,0, 255],
[119,0,0, 255], [ 85,0,0, 255], [ 68,0,0, 255], [ 34,0,0, 255], [ 17,0,0, 255],
[0,238,0, 255], [0,221,0, 255], [0,187,0, 255], [0,170,0, 255], [0,136,0, 255],
[0,119,0, 255], [0, 85,0, 255], [0, 68,0, 255], [0, 34,0, 255], [0, 17,0, 255],
[0,0,238, 255], [0,0,221, 255], [0,0,187, 255], [0,0,170, 255], [0,0,136, 255],
[0,0,119, 255], [0,0, 85, 255], [0,0, 68, 255], [0,0, 34, 255], [0,0, 17, 255],
[238,238,238, 255], [221,221,221, 255], [187,187,187, 255], [170,170,170, 255], [136,136,136, 255],
[119,119,119, 255], [ 85, 85, 85, 255], [ 68, 68, 68, 255], [ 34, 34, 34, 255], [ 17, 17, 17, 255],
[0,0,0,255],
];
function AppleVolume(byteSource) {
this.byteSource = byteSource;
}
AppleVolume.prototype = {
read: function(reader) {
this.readPartitions(this.byteSource, reader);
},
readPartitions: function(byteSource, reader) {
var self = this;
function doPartition(n) {
byteSource.slice(PHYSICAL_BLOCK_BYTES * n, PHYSICAL_BLOCK_BYTES * (n+1)).read({
onbytes: function(bytes) {
if (macintoshRoman(bytes, 0, 4) !== 'PM\0\0') {
console.error('invalid partition map signature');
return;
}
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var mapBlockCount = dv.getInt32(4, false);
var partitionInfo = {
blockOffset: dv.getInt32(8, false),
blockCount: dv.getInt32(12, false),
type: nullTerminate(macintoshRoman(bytes, 48, 32)),
status: dv.getInt32(88, false),
};
var dataAreaBlockCount = dv.getInt32(84, false);
if (dataAreaBlockCount > 0) {
partitionInfo.dataArea = {
blockCount: dataAreaBlockCount,
blockOffset: dv.getInt32(80, false),
};
}
var bootCodeByteLength = dv.getInt32(96, false);
if (bootCodeByteLength > 0) {
partitionInfo.bootCode = {
byteLength: bootCodeByteLength,
blockOffset: dv.getInt32(92, false),
loadAddress: dv.getInt32(100, false),
entryPoint: dv.getInt32(108, false),
checksum: dv.getInt32(116, false),
};
}
var partitionName = nullTerminate(macintoshRoman(bytes, 16, 32));
if (partitionName) partitionInfo.name = partitionName;
var processorType = nullTerminate(macintoshRoman(bytes, 124, 16));
if (processorType) partitionInfo.processorType = processorType;
switch (partitionInfo.type) {
case 'Apple_HFS':
self.readHFS(
byteSource.slice(
PHYSICAL_BLOCK_BYTES * partitionInfo.blockOffset,
PHYSICAL_BLOCK_BYTES * (partitionInfo.blockOffset + partitionInfo.blockCount)),
reader);
break;
default:
break;
}
if (typeof reader.onpartition === 'function') {
reader.onpartition(partitionInfo);
}
if (n < mapBlockCount) {
doPartition(n + 1);
}
},
});
}
doPartition(1);
},
readHFS: function(byteSource, reader) {
var self = this;
// first 2 blocks are boot blocks
var masterDirectoryBlock = byteSource.slice(PHYSICAL_BLOCK_BYTES * 2, PHYSICAL_BLOCK_BYTES * (2+1));
masterDirectoryBlock.read({
onbytes: function(bytes) {
var tag;
switch(tag = macintoshRoman(bytes, 0, 2)) {
case 'BD':
this.onhfs(bytes);
break;
case 'H+':
this.onhfsplus(bytes);
break;
default:
console.error('Unknown master directory block signature: ' + tag);
break;
}
},
onhfs: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var volumeInfo = {
createdAt: macintoshDate(dv, 2),
lastModifiedAt: macintoshDate(dv, 6),
attributes: dv.getUint16(10, false),
rootFileCount: dv.getUint16(12, false),
bitmapBlockOffset: dv.getUint16(14, false), // always 3?
nextAllocationSearch: dv.getUint16(16, false), // used internally
allocationBlockCount: dv.getUint16(18, false),
allocationBlockByteLength: dv.getInt32(20, false), // size of one block, always multiple of 512
defaultClumpSize: dv.getInt32(24, false),
allocationBlocksOffset: dv.getUint16(28, false),
nextUnusedCatalogNodeId: dv.getInt32(30, false), // catalog node: file or folder
unusedAllocationBlockCount: dv.getUint16(34, false),
name: nullTerminate(macintoshRoman(bytes, 36 + 1, bytes[36])),
lastBackupAt: macintoshDate(dv, 64),
backupSequenceNumber: dv.getUint16(68, false), // used internally
writeCount: dv.getInt32(70, false),
extentsOverflowFileClumpSize: dv.getInt32(74, false),
catalogFileClumpSize: dv.getInt32(78, false),
rootFolderCount: dv.getUint16(82, false),
fileCount: dv.getInt32(84, false),
folderCount: dv.getInt32(88, false),
finderInfo: [
dv.getInt32(92, false),
dv.getInt32(96, false),
dv.getInt32(100, false),
dv.getInt32(104, false),
dv.getInt32(108, false),
dv.getInt32(112, false),
dv.getInt32(116, false),
dv.getInt32(120, false),
],
cacheBlockCount: dv.getUint16(124, false), // used internally
bitmapCacheBlockCount: dv.getUint16(126, false), // used internally
commonCacheBlockCount: dv.getUint16(128, false), // used internally
extentsOverflowFileByteLength: dv.getInt32(130, false),
extentsOverflowFileExtentRecord: extentDataRecord(dv, 134),
catalogFileByteLength: dv.getInt32(146, false),
catalogFileExtentRecord: extentDataRecord(dv, 150),
};
if (typeof reader.onvolumestart === 'function') {
reader.onvolumestart(volumeInfo);
}
var allocationBlocksAt = PHYSICAL_BLOCK_BYTES * volumeInfo.allocationBlocksOffset;
var allocationBlocksLen = volumeInfo.allocationBlockByteLength * volumeInfo.allocationBlockCount;
var allocationBlocks = byteSource.slice(allocationBlocksAt, allocationBlocksAt + allocationBlocksLen);
allocationBlocks.blockSize = volumeInfo.allocationBlockByteLength;
var catalogExtents = volumeInfo.catalogFileExtentRecord[0];
catalogExtents = allocationBlocks.slice(
allocationBlocks.blockSize * catalogExtents.offset,
allocationBlocks.blockSize * catalogExtents.offset + volumeInfo.catalogFileByteLength);
catalogExtents.allocationBlocks = allocationBlocks;
self.readCatalog(catalogExtents, {
});
},
onhfsplus: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var volumeInfo = {
version: dv.getUint16(2, false),
attributes: dv.getUint32(4, false),
lastMountedVersion: macintoshRoman(bytes, 8, 4),
journalInfoBlock: dv.getUint32(12, false),
createdAt: macintoshDate(dv, 16),
lastModifiedAt: macintoshDate(dv, 20),
backupAt: macintoshDate(dv, 24),
fileCount: dv.getUint32(28, false),
folderCount: dv.getUint32(32, false),
blockSize: dv.getUint32(36, false),
totalBlocks: dv.getUint32(40, false),
freeBlocks: dv.getUint32(44, false),
nextAllocation: dv.getUint32(48, false),
resourceClumpSize: dv.getUint32(52, false),
dataClumpSize: dv.getUint32(56, false),
nextCatalogId: dv.getUint32(60, false),
writeCount: dv.getUint32(64, false),
encodingsBitmap1: dv.getUint32(68, false),
encodingsBitmap2: dv.getUint32(72, false),
finderInfo: [
dv.getInt32(76, false),
dv.getInt32(80, false),
dv.getInt32(84, false),
dv.getInt32(88, false),
dv.getInt32(92, false),
dv.getInt32(96, false),
dv.getInt32(100, false),
dv.getInt32(104, false),
],
allocationFile: hfsPlusForkData(dv, 108),
extentsFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength),
catalogFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 2),
attributesFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 3),
startupFile: hfsPlusForkData(dv, 108 + hfsPlusForkData.byteLength * 4),
};
console.log(volumeInfo);
},
});
},
readCatalog: function(byteSource, reader) {
var self = this;
var folders = {};
var allocation = byteSource.allocationBlocks;
this.readBTreeNode(byteSource.slice(0, BTREE_NODE_BYTES), {
onheadernode: function(headerNode) {
var rootNode = byteSource.slice(
headerNode.rootNodeNumber * BTREE_NODE_BYTES,
(headerNode.rootNodeNumber + 1) * BTREE_NODE_BYTES);
self.readBTreeNode(rootNode, this);
},
onindexnode: function(indexNode) {
for (var i = 0; i < indexNode.pointers.length; i++) {
var pointer = indexNode.pointers[i];
var pointedBytes = byteSource.slice(
pointer.nodeNumber * BTREE_NODE_BYTES,
(pointer.nodeNumber + 1) * BTREE_NODE_BYTES);
self.readBTreeNode(pointedBytes, this);
}
},
onfolderthread: function(threadInfo) {
},
onfolder: function(folderInfo) {
var container = document.createElement('DETAILS');
if (folderInfo.isInvisible) {
container.classList.add('invisible');
}
container.classList.add('folder');
container.dataset.name = folderInfo.name;
var title = document.createElement('SUMMARY');
title.innerHTML = folderInfo.name;
container.appendChild(title);
var timestamp = folderInfo.modifiedAt || folderInfo.createdAt;
if (timestamp) {
container.dataset.lastModified = timestamp.toISOString();
}
if (folderInfo.id in folders) {
container.appendChild(folders[folderInfo.id]);
}
else {
var children = document.createElement('SECTION');
children.classList.add('folder-children');
container.appendChild(children);
folders[folderInfo.id] = children;
}
if (folderInfo.parentDirectoryId === 1) {
container.setAttribute('open', 'open');
document.body.appendChild(container);
}
else if (folderInfo.parentDirectoryId in folders) {
folders[folderInfo.parentDirectoryId].appendChild(container);
}
else {
var siblings = document.createElement('SECTION');
siblings.classList.add('folder-children');
siblings.appendChild(container);
folders[folderInfo.parentDirectoryId] = siblings;
}
},
onfile: function(fileInfo) {
var container = document.createElement('DETAILS');
if (fileInfo.isInvisible) {
container.classList.add('invisible');
}
container.classList.add('file');
container.dataset.name = fileInfo.name;
var title = document.createElement('SUMMARY');
title.innerHTML = fileInfo.name;
container.appendChild(title);
if (fileInfo.type !== null) {
container.dataset.macType = fileInfo.type;
}
if (fileInfo.creator !== null) {
container.dataset.macCreator = fileInfo.creator;
}
var timestamp = fileInfo.modifiedAt || fileInfo.createdAt;
if (timestamp) {
container.dataset.lastModified = timestamp.toISOString();
}
if (fileInfo.dataFork.logicalEOF) {
var dataFork = document.createElement('A');
dataFork.setAttribute('href', '#');
dataFork.classList.add('data-fork');
dataFork.innerText = 'Data Fork';
var extent = fileInfo.dataFork.firstExtentRecord[0];
allocation.slice(
allocation.blockSize * extent.offset,
allocation.blockSize * extent.offset + fileInfo.dataFork.logicalEOF
).getURL().then(function(url) {
dataFork.setAttribute('href', url);
dataFork.setAttribute('download', fileInfo.name);
});
dataFork.dataset.size = fileInfo.dataFork.logicalEOF;
container.appendChild(dataFork);
}
if (fileInfo.resourceFork.logicalEOF) {
var extent = fileInfo.resourceFork.firstExtentRecord[0];
self.readResourceFork(allocation.slice(
allocation.blockSize * extent.offset,
allocation.blockSize * extent.offset + fileInfo.resourceFork.logicalEOF
), {
onresource: function(resource) {
var resourceEl = document.createElement('DIV');
resourceEl.classList.add('resource');
if (resource.name !== null) {
resourceEl.dataset.name = resource.name;
}
resourceEl.dataset.type = resource.type;
resourceEl.dataset.id = resource.id;
resourceEl.dataset.size = resource.data.length;
if ('image' in resource) {
var img = document.createElement('IMG');
img.width = resource.image.width;
img.height = resource.image.height;
img.src = resource.image.url;
img.style.background = '#ccc';
if ('hotspot' in resource) {
img.style.cursor = 'url(' + resource.image.url + ') '
+ resource.hotspot.x + ' ' + resource.hotspot.y + ', url(' + resource.image.url + '), auto';
}
resourceEl.appendChild(img);
}
if ('text' in resource) {
var scr = document.createElement('SCRIPT');
scr.setAttribute('type', 'text/plain');
scr.appendChild(document.createTextNode(resource.text));
resourceEl.appendChild(scr);
}
container.appendChild(resourceEl);
}
});
}
if (fileInfo.parentDirectoryId === 1) {
document.body.appendChild(container);
}
else if (fileInfo.parentDirectoryId in folders) {
folders[fileInfo.parentDirectoryId].appendChild(container);
}
else {
var siblings = document.createElement('SECTION');
siblings.classList.add('folder-children');
siblings.appendChild(container);
folders[fileInfo.parentDirectoryId] = siblings;
}
},
});
},
readResourceFork: function(byteSource, reader) {
byteSource.read({
onbytes: function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffet, bytes.byteLength);
var dataOffset = dv.getUint32(0, false);
var mapDV = new DataView(bytes.buffer, bytes.byteOffset + dv.getUint32(4, false), dv.getUint32(12, false));
var attributes = mapDV.getUint16(22, false);
var isReadOnly = !!(attributes & 0x80);
var typeListOffset = mapDV.getUint16(24, false);
var nameListOffset = mapDV.getUint16(26, false);
var typeCount = mapDV.getInt16(typeListOffset, false) + 1;
var resources = [];
for (var i = 0; i < typeCount; i++) {
var resourceTypeName = macintoshRoman(
new Uint8Array(mapDV.buffer, mapDV.byteOffset + typeListOffset + 2 + (i * 8), 4),
0, 4);
var resourceCount = mapDV.getInt16(typeListOffset + 2 + (i * 8) + 4, false) + 1;
var referenceListOffset = mapDV.getUint16(typeListOffset + 2 + (i * 8) + 4 + 2, false);
var referenceListDV = new DataView(
mapDV.buffer,
mapDV.byteOffset + typeListOffset + referenceListOffset,
resourceCount * 12);
for (var j = 0; j < resourceCount; j++) {
var resourceID = referenceListDV.getUint16(j * 12, false);
var resourceNameOffset = referenceListDV.getInt16(j * 12 + 2, false);
var resourceAttributes = referenceListDV.getUint8(j * 12 + 4, false);
var resourceDataOffset = referenceListDV.getUint32(j * 12 + 4, false) & 0xffffff;
var resourceName;
if (resourceNameOffset === -1) {
resourceName = null;
}
else {
resourceNameOffset += nameListOffset;
resourceName = new Uint8Array(
mapDV.buffer,
mapDV.byteOffset + resourceNameOffset + 1,
mapDV.getUint8(resourceNameOffset));
resourceName = macintoshRoman(resourceName, 0, resourceName.length);
}
resourceDataOffset += dataOffset;
var data = bytes.subarray(
resourceDataOffset + 4,
resourceDataOffset + 4 + dv.getUint32(resourceDataOffset, false));
var resource = {
name: resourceName,
type: resourceTypeName,
id: resourceID,
data: data,
};
switch (resource.type) {
case 'STR ':
resource.text = macintoshRoman(resource.data, 0, resource.data.length);
break;
case 'CURS':
if (resource.data.length !== 68) {
console.error('CURS resource expected to be 68 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 32; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[32 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
var hotspotDV = new DataView(resource.data.buffer, resource.data.byteOffset + 64, 8);
resource.hotspot = {y:hotspotDV.getInt16(0), x:hotspotDV.getInt16(2)};
break;
case 'ICN#':
if (resource.data.length !== 256) {
console.error('ICS# resource expected to be 256 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 32;
img.height = 32;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(32, 32);
for (var ibyte = 0; ibyte < 128; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[128 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:32, height:32};
break;
case 'ics#':
if (resource.data.length !== 64) {
console.error('ics# resource expected to be 64 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 32; ibyte++) {
var databyte = resource.data[ibyte], maskbyte = resource.data[32 + ibyte];
for (var ibit = 0; ibit < 8; ibit++) {
var imask = 0x80 >> ibit;
if (maskbyte & imask) {
pix.data.set(databyte & imask ? PIXEL1 : PIXEL0, (ibyte*8 + ibit) * 4);
}
}
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
break;
case 'icl8':
if (resource.data.length !== 1024) {
console.error('icl8 resource expected to be 1024 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 32;
img.height = 32;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(32, 32);
for (var ibyte = 0; ibyte < 1024; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte]], ibyte*4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:32, height:32};
break;
case 'ics8':
if (resource.data.length !== 256) {
console.error('ics8 resource expected to be 256 bytes, got ' + resource.data.length);
break;
}
var img = document.createElement('CANVAS');
img.width = 16;
img.height = 16;
var ctx = img.getContext('2d');
var pix = ctx.createImageData(16, 16);
for (var ibyte = 0; ibyte < 256; ibyte++) {
pix.data.set(mac8BitSystemPalette[resource.data[ibyte]], ibyte*4);
}
ctx.putImageData(pix, 0, 0);
resource.image = {url: img.toDataURL(), width:16, height:16};
break;
}
if (resourceAttributes & 0x40) resource.loadInSystemHeap = true; // instead of application heap
if (resourceAttributes & 0x20) resource.mayBePagedOutOfMemory = true;
if (resourceAttributes & 0x10) resource.doNotMoveInMemory = true;
if (resourceAttributes & 0x08) resource.isReadOnly = true;
if (resourceAttributes & 0x04) resource.preload = true;
if (resourceAttributes & 0x01) resource.compressed = true;
if (typeof reader.onresource === 'function') {
reader.onresource(resource);
}
}
}
},
});
},
readBTreeNode: function(byteSource, reader) {
var self = this;
byteSource.read({
onbytes: function(bytes) {
var node = {};
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var records = new Array(dv.getUint16(10, false));
for (var i = 0; i < records.length; i++) {
records[i] = bytes.subarray(
dv.getUint16(BTREE_NODE_BYTES - 2*(i+1), false),
dv.getUint16(BTREE_NODE_BYTES - 2*(i+2), false));
}
var forwardLink = dv.getInt32(0, false);
var backwardLink = dv.getInt32(4, false);
if (forwardLink !== 0) node.forwardLink = forwardLink;
if (backwardLink !== 0) node.backwardLink = backwardLink;
node.depth = bytes[9];
switch(bytes[8]) {
case 0: // index
node.pointers = [];
for (var i = 0; i < records.length; i++) {
var recordBytes = records[i];
var keyLength;
if (recordBytes.length === 0 || (keyLength = recordBytes[0]) === 0) {
// deleted record
continue;
}
var dv = new DataView(recordBytes.buffer, recordBytes.byteOffset, recordBytes.byteLength);
var parentDirectoryID = dv.getUint32(2, false);
var name = macintoshRoman(recordBytes, 7, recordBytes[6]);
var nodeNumber = dv.getUint32(1 + keyLength, false);
node.pointers.push({name:name, nodeNumber:nodeNumber, parentDirectoryID:parentDirectoryID});
}
if (typeof reader.onindexnode === 'function') {
reader.onindexnode(node);
}
break;
case 1: // header
if (records.length !== 3) {
console.error('header node: expected 3 records, got ' + recordCount);
return;
}
var recordDV = new DataView(records[0].buffer, records[0].byteOffset, records[0].byteLength);
node.treeDepth = recordDV.getUint16(0, false);
node.rootNodeNumber = recordDV.getUint32(2, false);
node.leafRecordCount = recordDV.getUint32(6, false);
node.firstLeaf = recordDV.getUint32(10, false);
node.lastLeaf = recordDV.getUint32(14, false);
node.nodeByteLength = recordDV.getUint16(18, false); // always 512?
node.maxKeyByteLength = recordDV.getUint16(20, false);
node.nodeCount = recordDV.getUint32(22, false);
node.freeNodeCount = recordDV.getUint32(26, false);
node.bitmap = records[2];
if (typeof reader.onheadernode === 'function') {
reader.onheadernode(node);
}
break;
case 2: // map
console.error('NYI: map node');
break;
case 0xff: // leaf
for (var i = 0; i < records.length; i++) {
var record = records[i];
var keyLength;
if (record.length === 0 || (keyLength = record[0]) === 0) {
// deleted record
continue;
}
var dv = new DataView(record.buffer, record.byteOffset, record.byteLength);
var parentDirectoryId = dv.getUint32(2, false);
var name = macintoshRoman(record, 7, record[6]);
var offset = 1 + keyLength;
offset = offset + (offset % 2);
record = record.subarray(offset);
dv = new DataView(record.buffer, record.byteOffset, record.byteLength);
switch(record[0]) {
case 1: // folder
var folderInfo = {
name: name,
id: dv.getUint32(6, false),
modifiedAt: macintoshDate(dv, 14),
location: {
v: dv.getInt16(32, false),
h: dv.getInt16(34, false),
},
window: {
top: dv.getInt16(22, false),
left: dv.getInt16(24, false),
bottom: dv.getInt16(26, false),
right: dv.getInt16(28, false),
scroll: {
v: dv.getInt16(38, false),
h: dv.getInt16(40, false),
},
},
parentDirectoryId: parentDirectoryId,
// dinfoReserved: dv.getInt16(36, false),
// dxinfoReserved: dv.getInt32(42, false),
dxinfoFlags: dv.getUint16(46, false),
dxinfoComment: dv.getUint16(48, false),
fileCount: dv.getUint16(4, false),
createdAt: macintoshDate(dv, 10),
backupAt: macintoshDate(dv, 18),
putAwayFolderID: dv.getInt32(50, false),
flags: dv.getUint16(2, false),
};
if (!folderInfo.flags) delete folderInfo.flags;
var dinfoFlags = dv.getUint16(30, false);
if (dinfoFlags & 0x0001) folderInfo.isOnDesk = true;
if (dinfoFlags & 0x000E) folderInfo.color = true;
if (dinfoFlags & 0x0020) folderInfo.requireSwitchLaunch = true;
if (dinfoFlags & 0x0400) folderInfo.hasCustomIcon = true;
if (dinfoFlags & 0x1000) folderInfo.nameLocked = true;
if (dinfoFlags & 0x2000) folderInfo.hasBundle = true;
if (dinfoFlags & 0x4000) folderInfo.isInvisible = true;
if (typeof reader.onfolder === 'function') {
reader.onfolder(folderInfo);
}
break;
case 2: // file
var fileInfo = {
name: name,
creator: macintoshRoman(record, 8, 4),
type: macintoshRoman(record, 4, 4),
id: dv.getUint32(20, false),
parentDirectoryId: parentDirectoryId,
// type: record[3], /* always zero */
position: {v:dv.getInt16(14, false), h:dv.getInt16(16, false)},
// finfoReserved: dv.getInt16(18, false),
dataFork: {
firstAllocationBlock: dv.getUint16(24, false),
logicalEOF: dv.getUint32(26, false),
physicalEOF: dv.getUint32(30, false),
firstExtentRecord: extentDataRecord(dv, 74),
},
resourceFork: {
firstAllocationBlock: dv.getUint16(34, false),
logicalEOF: dv.getUint32(36, false),
physicalEOF: dv.getUint32(40, false),
firstExtentRecord: extentDataRecord(dv, 86),
},
createdAt: macintoshDate(dv, 44),
modifiedAt: macintoshDate(dv, 48),
backupAt: macintoshDate(dv, 52),
// fxinfoReserved: (8 bytes)
fxinfoFlags: dv.getUint16(64, false),
putAwayFolderID: dv.getUint32(68, false),
clumpSize: dv.getUint16(72),
};
if (fileInfo.creator === '\0\0\0\0') fileInfo.creator = null;
if (fileInfo.type === '\0\0\0\0') fileInfo.type = null;
if (!(fileInfo.position.v || fileInfo.position.h)) fileInfo.position = 'default';
if (record[2] & 0x01) fileInfo.locked = true;
if (record[2] & 0x02) fileInfo.hasThreadRecord = true;
if (record[2] & 0x80) fileInfo.recordUsed = true;
var finfoFlags = dv.getUint16(12, false);
if (finfoFlags & 0x0001) fileInfo.isOnDesk = true;
if (finfoFlags & 0x000E) fileInfo.color = true;
if (finfoFlags & 0x0020) fileInfo.requireSwitchLaunch = true;
if (finfoFlags & 0x0040) fileInfo.isShared = true;
if (finfoFlags & 0x0080) fileInfo.hasNoINITs = true;
if (finfoFlags & 0x0100) fileInfo.hasBeenInited = true;
if (finfoFlags & 0x0400) fileInfo.hasCustomIcon = true;
if (finfoFlags & 0x0800) fileInfo.isStationery = true;
if (finfoFlags & 0x1000) fileInfo.nameLocked = true;
if (finfoFlags & 0x2000) fileInfo.hasBundle = true;
if (finfoFlags & 0x4000) fileInfo.isInvisible = true;
if (finfoFlags & 0x8000) fileInfo.isAlias = true;
if (typeof reader.onfile === 'function') {
reader.onfile(fileInfo);
}
break;
case 3: // folder thread
case 4: // file thread
var threadInfo = {
parentDirectoryId: parentDirectoryId,
parentFolderID: dv.getUint32(10, false),
parentFolderName: macintoshRoman(record, 15, record[14]),
};
if (record[0] === 3) {
if (typeof reader.onfolderthread === 'function') {
reader.onfolderthread(threadInfo);
}
}
else {
if (typeof reader.onfilethread === 'function') {
reader.onfilethread(threadInfo);
}
}
break;
default:
console.error('unknown folder record type: ' + dv.getUint8(0));
break;
}
}
if (typeof reader.onleafnode === 'function') {
reader.onleafnode(node);
}
break;
default:
console.error('unknown node type: ' + bytes[8]);
break;
}
}
});
},
};
return AppleVolume;
});
| Support 16-color icons | AppleVolume.js | Support 16-color icons | <ide><path>ppleVolume.js
<ide>
<ide> var PIXEL0 = new Uint8Array([255,255,255,255]);
<ide> var PIXEL1 = new Uint8Array([0,0,0,255]);
<add>
<add> var mac4BitSystemPalette = [
<add> [255,255,255, 255], [255,255, 0, 255], [255,102, 0, 255], [221, 0, 0, 255],
<add> [255, 0,153, 255], [ 51, 0,153, 255], [ 0, 0,204, 255], [ 0,153,255, 255],
<add> [ 0,170, 0, 255], [ 0,102, 0, 255], [102, 51, 0, 255], [153,102, 51, 255],
<add> [187,187,187, 255], [136,136,136, 255], [ 68, 68, 68, 255], [ 0, 0, 0, 255],
<add> ];
<ide>
<ide> var mac8BitSystemPalette = [
<ide> [255,255,255, 255], [255,255,204, 255], [255,255,153, 255], [255,255,102, 255], [255,255, 51, 255], [255,255, 0, 255],
<ide> ctx.putImageData(pix, 0, 0);
<ide> resource.image = {url: img.toDataURL(), width:16, height:16};
<ide> break;
<add> case 'icl4':
<add> if (resource.data.length !== 512) {
<add> console.error('icl4 resource expected to be 512 bytes, got ' + resource.data.length);
<add> break;
<add> }
<add> var img = document.createElement('CANVAS');
<add> img.width = 32;
<add> img.height = 32;
<add> var ctx = img.getContext('2d');
<add> var pix = ctx.createImageData(32, 32);
<add> for (var ibyte = 0; ibyte < 512; ibyte++) {
<add> pix.data.set(mac8BitSystemPalette[resource.data[ibyte] >> 4], ibyte*8);
<add> pix.data.set(mac8BitSystemPalette[resource.data[ibyte] & 15], ibyte*8 + 4);
<add> }
<add> ctx.putImageData(pix, 0, 0);
<add> resource.image = {url: img.toDataURL(), width:32, height:32};
<add> break;
<add> case 'ics4':
<add> if (resource.data.length !== 128) {
<add> console.error('ics4 resource expected to be 128 bytes, got ' + resource.data.length);
<add> break;
<add> }
<add> var img = document.createElement('CANVAS');
<add> img.width = 16;
<add> img.height = 16;
<add> var ctx = img.getContext('2d');
<add> var pix = ctx.createImageData(16, 16);
<add> for (var ibyte = 0; ibyte < 128; ibyte++) {
<add> pix.data.set(mac8BitSystemPalette[resource.data[ibyte] >> 4], ibyte*8);
<add> pix.data.set(mac8BitSystemPalette[resource.data[ibyte] & 15], ibyte*8 + 4);
<add> }
<add> ctx.putImageData(pix, 0, 0);
<add> resource.image = {url: img.toDataURL(), width:16, height:16};
<add> break;
<ide> }
<ide> if (resourceAttributes & 0x40) resource.loadInSystemHeap = true; // instead of application heap
<ide> if (resourceAttributes & 0x20) resource.mayBePagedOutOfMemory = true; |
|
Java | mit | b1501e10831e5ae9e9d34ddc41407086117f2276 | 0 | 0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio,0x326/academic-code-portfolio | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Course:
* Instructor:
* <p>
* Project 06
*
* @author John Meyer
*/
public class TicTacToe {
private ArrayList<BoardState> currentBoardState = new ArrayList<>(9);
private DictionaryInterface<ArrayList<BoardState>, Integer> bestMoveDictionary = new HashedDictionary2<ArrayList<BoardState>,Integer>();
public TicTacToe() {
// Initialize state
for (int i = 0; i < 9; i++) {
currentBoardState.add(null);
}
generateBoards(currentBoardState);
Iterator<ArrayList<BoardState>> bestMoveDictionaryKeyIterator = bestMoveDictionary.getKeyIterator();
while (bestMoveDictionaryKeyIterator.hasNext()) {
ArrayList<BoardState> key = bestMoveDictionaryKeyIterator.next();
System.out.println(key.toString());
System.out.println(bestMoveDictionary.getValue(key));
}
}
private void generateBoards(ArrayList<BoardState> board) {
BoardState playerToMove = getTurn(board);
for (int i = 0; i < board.size(); i++) {
if (board.get(i) == null) {
// Suppose the player were to move here
board.set(i, playerToMove);
if (findWinner(board) == null) {
OptimalMove bestMove = computeBestMove(board);
if (bestMove != null) {
//noinspection unchecked
bestMoveDictionary.add((ArrayList<BoardState>) board.clone(), bestMove.location);
}
generateBoards(board);
}
// Remove supposition
board.set(i, null);
}
}
}
private OptimalMove computeBestMove(List<BoardState> board) {
BoardState playerToOptimize = getTurn(board);
FutureGameEnd bestForeseeableGameEnd = null;
int moveThatYieldsMinimumTime = 0;
for (int i = 0; i < board.size(); i++) {
if (board.get(i) == null) {
// Suppose the player were to move here
board.set(i, playerToOptimize);
// Compute time to winning move
FutureGameEnd futureWin = predictGameEnding(board);
// Decide whether to update best estimate
if (futureWin != null &&
(bestForeseeableGameEnd == null ||
// We found a win
(futureWin.winner == playerToOptimize &&
// This is a better win than what we knew before
(futureWin.movesFromNow < bestForeseeableGameEnd.movesFromNow ||
// Or, it's a win when we thought we were doomed to lose
bestForeseeableGameEnd.winner != futureWin.winner)) ||
// We found a loss
(futureWin.winner != playerToOptimize &&
// And, we don't know of any way to win
bestForeseeableGameEnd.winner != playerToOptimize &&
// Is this loss more postponed than the one we knew about?
futureWin.movesFromNow > bestForeseeableGameEnd.movesFromNow))) {
// Update best estimate
bestForeseeableGameEnd = futureWin;
moveThatYieldsMinimumTime = i;
}
// Remove supposition
board.set(i, null);
}
}
if (bestForeseeableGameEnd != null) {
return new OptimalMove(moveThatYieldsMinimumTime, bestForeseeableGameEnd);
} else {
return null;
}
}
private FutureGameEnd predictGameEnding(List<BoardState> board) {
BoardState winner = findWinner(board);
if (winner != null) {
return new FutureGameEnd(winner, 0);
} else {
OptimalMove optimalMove = computeBestMove(board);
return optimalMove != null ? optimalMove.future : null;
}
}
private class FutureGameEnd {
BoardState winner;
int movesFromNow;
FutureGameEnd(BoardState winner, int movesFromNow) {
this.winner = winner;
this.movesFromNow = movesFromNow;
}
}
private class OptimalMove {
int location;
FutureGameEnd future;
public OptimalMove(int location, FutureGameEnd future) {
this.location = location;
this.future = future;
}
}
private static boolean isBoardFull(BoardState[] board) {
for (BoardState state:
board) {
if (state == null) {
return false;
}
}
return true;
}
private static BoardState getTurn(List<BoardState> board) {
int numberOfXs = 0;
int numberOfOs = 0;
for (BoardState state:
board) {
if (state == BoardState.X) {
numberOfXs++;
} else if (state == BoardState.O) {
numberOfOs++;
}
}
if (numberOfXs - numberOfOs != 0 && numberOfXs - numberOfOs != 1) {
throw new IllegalStateException();
}
return numberOfXs == numberOfOs ? BoardState.X : BoardState.O;
}
private Integer findWinningMove(BoardState[] board) {
// Check rows
for (int row = 0; row < 3; row++) {
if (board[3 * row + 1] != null && board[3 * row + 1] == board[3 * row + 2]) {
return 3 * row;
} else if (board[3 * row] != null && board[3 * row] == board[3 * row + 2]) {
return 3 * row + 1;
} else if (board[3 * row] != null && board[3 * row] == board[3 * row + 1]) {
return 3 * row + 2;
}
}
// Check columns
for (int column = 0; column < 3; column++) {
if (board[column + 3] != null && board[column + 3] == board[column + 6]) {
return column;
} else if (board[column] != null && board[column] == board[column + 6]) {
return column + 3;
} else if (board[column] != null && board[column] == board[column + 3]) {
return column + 6;
}
}
// Check forward diagonals
if (board[4] != null && board[4] == board[8]) {
return 0;
} else if (board[0] != null && board[0] == board[8]) {
return 4;
} else if (board[0] != null && board[0] == board[4]) {
return 8;
}
// Check backward diagonals
if (board[4] != null && board[4] == board[6]) {
return 2;
} else if (board[2] != null && board[2] == board[6]) {
return 4;
} else if (board[2] != null && board[2] == board[4]) {
return 6;
}
// There is no immediate win
return null;
}
private static BoardState findWinner(List<BoardState> board) {
// Check rows
for (int row = 0; row < 3; row++) {
if (board.get(3 * row) != null &&
board.get(3 * row) == board.get(3 * row + 1) &&
board.get(3 * row + 1) == board.get(3 * row + 2)) {
return board.get(3 * row);
}
}
// Check columns
for (int column = 0; column < 3; column++) {
if (board.get(column) != null &&
board.get(column) == board.get(column + 3) &&
board.get(column + 3) == board.get(column + 6)) {
return board.get(column);
}
}
// Check diagonals
if (board.get(0) != null &&
board.get(0) == board.get(4) &&
board.get(4) == board.get(8)) {
return board.get(4);
} else if (board.get(2) != null &&
board.get(2) == board.get(4) &&
board.get(4) == board.get(6)) {
return board.get(4);
}
return null;
}
public List<BoardState> getCurrentBoardState() {
return new ArrayList<>(currentBoardState);
}
public BoardState getWinner() {
return findWinner(currentBoardState);
}
public void placeX(int position) {
position--;
if (!(0 < position && position <= 9) || currentBoardState.get(position) != null) {
throw new IllegalArgumentException();
}
currentBoardState.set(position, BoardState.X);
}
public void makeOpponentMove() {
int bestMovePosition = bestMoveDictionary.getValue(currentBoardState);
if (currentBoardState.get(bestMovePosition) != null) {
throw new RuntimeException("Dictionary is not properly constructed");
}
currentBoardState.set(bestMovePosition, BoardState.O);
}
public int getBestMove(String board) {
if (board.length() != 9) {
throw new IllegalArgumentException("Board must have 9 spaces");
}
ArrayList<BoardState> listBoard = new ArrayList<>(9);
for (char character : board.toCharArray()) {
switch (character) {
case 'X':
listBoard.add(BoardState.X);
break;
case 'O':
listBoard.add(BoardState.O);
break;
case '-':
listBoard.add(null);
break;
default:
throw new IllegalArgumentException(String.format("Unrecognized character in string %s", character));
}
}
return bestMoveDictionary.getValue(listBoard);
}
}
| src/TicTacToe.java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Course:
* Instructor:
* <p>
* Project 06
*
* @author John Meyer
*/
public class TicTacToe {
private ArrayList<BoardState> currentBoardState = new ArrayList<>(9);
private DictionaryInterface<ArrayList<BoardState>, Integer> bestMoveDictionary = new HashedDictionary2<ArrayList<BoardState>,Integer>();
public TicTacToe() {
// Initialize state
for (int i = 0; i < 9; i++) {
currentBoardState.add(null);
}
generateBoards(currentBoardState);
Iterator<ArrayList<BoardState>> bestMoveDictionaryKeyIterator = bestMoveDictionary.getKeyIterator();
while (bestMoveDictionaryKeyIterator.hasNext()) {
ArrayList<BoardState> key = bestMoveDictionaryKeyIterator.next();
System.out.println(key.toString());
System.out.println(bestMoveDictionary.getValue(key));
}
}
private void generateBoards(ArrayList<BoardState> board) {
BoardState playerToMove = getTurn(board);
for (int i = 0; i < board.size(); i++) {
if (board.get(i) == null) {
// Suppose the player were to move here
board.set(i, playerToMove);
if (findWinner(board) == null) {
OptimalMove bestMove = computeBestMove(board);
if (bestMove != null) {
bestMoveDictionary.add(board, bestMove.location);
}
generateBoards(board);
}
// Remove supposition
board.set(i, null);
}
}
}
private OptimalMove computeBestMove(List<BoardState> board) {
BoardState playerToOptimize = getTurn(board);
FutureGameEnd bestForeseeableGameEnd = null;
int moveThatYieldsMinimumTime = 0;
for (int i = 0; i < board.size(); i++) {
if (board.get(i) == null) {
// Suppose the player were to move here
board.set(i, playerToOptimize);
// Compute time to winning move
FutureGameEnd futureWin = predictGameEnding(board);
// Decide whether to update best estimate
if (futureWin != null &&
(bestForeseeableGameEnd == null ||
// We found a win
(futureWin.winner == playerToOptimize &&
// This is a better win than what we knew before
(futureWin.movesFromNow < bestForeseeableGameEnd.movesFromNow ||
// Or, it's a win when we thought we were doomed to lose
bestForeseeableGameEnd.winner != futureWin.winner)) ||
// We found a loss
(futureWin.winner != playerToOptimize &&
// And, we don't know of any way to win
bestForeseeableGameEnd.winner != playerToOptimize &&
// Is this loss more postponed than the one we knew about?
futureWin.movesFromNow > bestForeseeableGameEnd.movesFromNow))) {
// Update best estimate
bestForeseeableGameEnd = futureWin;
moveThatYieldsMinimumTime = i;
}
// Remove supposition
board.set(i, null);
}
}
if (bestForeseeableGameEnd != null) {
return new OptimalMove(moveThatYieldsMinimumTime, bestForeseeableGameEnd);
} else {
return null;
}
}
private FutureGameEnd predictGameEnding(List<BoardState> board) {
BoardState winner = findWinner(board);
if (winner != null) {
return new FutureGameEnd(winner, 0);
} else {
OptimalMove optimalMove = computeBestMove(board);
return optimalMove != null ? optimalMove.future : null;
}
}
private class FutureGameEnd {
BoardState winner;
int movesFromNow;
FutureGameEnd(BoardState winner, int movesFromNow) {
this.winner = winner;
this.movesFromNow = movesFromNow;
}
}
private class OptimalMove {
int location;
FutureGameEnd future;
public OptimalMove(int location, FutureGameEnd future) {
this.location = location;
this.future = future;
}
}
private static boolean isBoardFull(BoardState[] board) {
for (BoardState state:
board) {
if (state == null) {
return false;
}
}
return true;
}
private static BoardState getTurn(List<BoardState> board) {
int numberOfXs = 0;
int numberOfOs = 0;
for (BoardState state:
board) {
if (state == BoardState.X) {
numberOfXs++;
} else if (state == BoardState.O) {
numberOfOs++;
}
}
if (numberOfXs - numberOfOs != 0 && numberOfXs - numberOfOs != 1) {
throw new IllegalStateException();
}
return numberOfXs == numberOfOs ? BoardState.X : BoardState.O;
}
private Integer findWinningMove(BoardState[] board) {
// Check rows
for (int row = 0; row < 3; row++) {
if (board[3 * row + 1] != null && board[3 * row + 1] == board[3 * row + 2]) {
return 3 * row;
} else if (board[3 * row] != null && board[3 * row] == board[3 * row + 2]) {
return 3 * row + 1;
} else if (board[3 * row] != null && board[3 * row] == board[3 * row + 1]) {
return 3 * row + 2;
}
}
// Check columns
for (int column = 0; column < 3; column++) {
if (board[column + 3] != null && board[column + 3] == board[column + 6]) {
return column;
} else if (board[column] != null && board[column] == board[column + 6]) {
return column + 3;
} else if (board[column] != null && board[column] == board[column + 3]) {
return column + 6;
}
}
// Check forward diagonals
if (board[4] != null && board[4] == board[8]) {
return 0;
} else if (board[0] != null && board[0] == board[8]) {
return 4;
} else if (board[0] != null && board[0] == board[4]) {
return 8;
}
// Check backward diagonals
if (board[4] != null && board[4] == board[6]) {
return 2;
} else if (board[2] != null && board[2] == board[6]) {
return 4;
} else if (board[2] != null && board[2] == board[4]) {
return 6;
}
// There is no immediate win
return null;
}
private static BoardState findWinner(List<BoardState> board) {
// Check rows
for (int row = 0; row < 3; row++) {
if (board.get(3 * row) != null &&
board.get(3 * row) == board.get(3 * row + 1) &&
board.get(3 * row + 1) == board.get(3 * row + 2)) {
return board.get(3 * row);
}
}
// Check columns
for (int column = 0; column < 3; column++) {
if (board.get(column) != null &&
board.get(column) == board.get(column + 3) &&
board.get(column + 3) == board.get(column + 6)) {
return board.get(column);
}
}
// Check diagonals
if (board.get(0) != null &&
board.get(0) == board.get(4) &&
board.get(4) == board.get(8)) {
return board.get(4);
} else if (board.get(2) != null &&
board.get(2) == board.get(4) &&
board.get(4) == board.get(6)) {
return board.get(4);
}
return null;
}
public List<BoardState> getCurrentBoardState() {
return new ArrayList<>(currentBoardState);
}
public BoardState getWinner() {
return findWinner(currentBoardState);
}
public void placeX(int position) {
position--;
if (!(0 < position && position <= 9) || currentBoardState.get(position) != null) {
throw new IllegalArgumentException();
}
currentBoardState.set(position, BoardState.X);
}
public void makeOpponentMove() {
int bestMovePosition = bestMoveDictionary.getValue(currentBoardState);
if (currentBoardState.get(bestMovePosition) != null) {
throw new RuntimeException("Dictionary is not properly constructed");
}
currentBoardState.set(bestMovePosition, BoardState.O);
}
public int getBestMove(String board) {
if (board.length() != 9) {
throw new IllegalArgumentException("Board must have 9 spaces");
}
ArrayList<BoardState> listBoard = new ArrayList<>(9);
for (char character : board.toCharArray()) {
switch (character) {
case 'X':
listBoard.add(BoardState.X);
break;
case 'O':
listBoard.add(BoardState.O);
break;
case '-':
listBoard.add(null);
break;
default:
throw new IllegalArgumentException(String.format("Unrecognized character in string %s", character));
}
}
return bestMoveDictionary.getValue(listBoard);
}
}
| Clone board before adding to dict
| src/TicTacToe.java | Clone board before adding to dict | <ide><path>rc/TicTacToe.java
<ide> if (findWinner(board) == null) {
<ide> OptimalMove bestMove = computeBestMove(board);
<ide> if (bestMove != null) {
<del> bestMoveDictionary.add(board, bestMove.location);
<add> //noinspection unchecked
<add> bestMoveDictionary.add((ArrayList<BoardState>) board.clone(), bestMove.location);
<ide> }
<ide>
<ide> generateBoards(board); |
|
Java | apache-2.0 | 7a8eeab1fa595e35e0832d8f1ef6e840ced817d3 | 0 | aniruddhas/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,vrozov/apex-core,sandeshh/incubator-apex-core,apache/incubator-apex-core,mt0803/incubator-apex-core,vrozov/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,vrozov/incubator-apex-core,tweise/incubator-apex-core,aniruddhas/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,tushargosavi/incubator-apex-core,ishark/incubator-apex-core,vrozov/incubator-apex-core,sandeshh/apex-core,tushargosavi/incubator-apex-core,simplifi-it/otterx,tushargosavi/apex-core,sandeshh/apex-core,tushargosavi/incubator-apex-core,simplifi-it/otterx,sandeshh/incubator-apex-core,amberarrow/incubator-apex-core,mattqzhang/apex-core,devtagare/incubator-apex-core,deepak-narkhede/apex-core,andyperlitch/incubator-apex-core,PramodSSImmaneni/apex-core,brightchen/apex-core,vrozov/apex-core,brightchen/incubator-apex-core,tushargosavi/apex-core,tweise/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,devtagare/incubator-apex-core,brightchen/incubator-apex-core,tweise/apex-core,brightchen/apex-core,PramodSSImmaneni/incubator-apex-core,klynchDS/incubator-apex-core,tweise/apex-core,amberarrow/incubator-apex-core,vrozov/apex-core,mattqzhang/apex-core,sandeshh/apex-core,ishark/incubator-apex-core,mattqzhang/apex-core,apache/incubator-apex-core,devtagare/incubator-apex-core,tweise/incubator-apex-core,MalharJenkins/incubator-apex-core,klynchDS/incubator-apex-core,MalharJenkins/incubator-apex-core,simplifi-it/otterx,tushargosavi/apex-core,deepak-narkhede/apex-core,chinmaykolhatkar/incubator-apex-core,deepak-narkhede/apex-core,apache/incubator-apex-core,mt0803/incubator-apex-core,PramodSSImmaneni/apex-core,PramodSSImmaneni/apex-core,sandeshh/incubator-apex-core,tweise/apex-core,brightchen/apex-core,ishark/incubator-apex-core,andyperlitch/incubator-apex-core | /*
* Copyright (c) 2012 Malhar, Inc.
* All Rights Reserved.
*/
package com.datatorrent.stram;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.FutureTask;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang.mutable.MutableLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.webapp.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.engine.OperatorStats;
import com.datatorrent.engine.OperatorStats.PortStats;
import com.datatorrent.stram.PhysicalPlan.PTContainer;
import com.datatorrent.stram.PhysicalPlan.PTInput;
import com.datatorrent.stram.PhysicalPlan.PTOperator;
import com.datatorrent.stram.PhysicalPlan.PTOutput;
import com.datatorrent.stram.PhysicalPlan.PlanContext;
import com.datatorrent.stram.PhysicalPlan.StatsHandler;
import com.datatorrent.stram.PhysicalPlan.PTOperator.State;
import com.datatorrent.stram.StramChildAgent.ContainerStartRequest;
import com.datatorrent.stram.StramChildAgent.OperatorStatus;
import com.datatorrent.stram.StramChildAgent.PortStatus;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest.RequestType;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState;
import com.datatorrent.stram.api.BaseContext;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.LogicalPlanRequest;
import com.datatorrent.stram.plan.logical.Operators;
import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta;
import com.datatorrent.stram.plan.physical.PlanModifier;
import com.datatorrent.stram.webapp.OperatorInfo;
import com.datatorrent.stram.webapp.PortInfo;
import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
import com.datatorrent.api.AttributeMap;
import com.datatorrent.api.Operator.InputPort;
import com.datatorrent.api.Operator.OutputPort;
import com.datatorrent.api.StorageAgent;
import com.datatorrent.common.util.Pair;
/**
*
* Tracks topology provisioning/allocation to containers<p>
* <br>
* The tasks include<br>
* Provisioning operators one container at a time. Each container gets assigned the operators, streams and its context<br>
* Monitors run time operations including heartbeat protocol and node status<br>
* Operator recovery and restart<br>
* <br>
*
*/
public class StreamingContainerManager extends BaseContext implements PlanContext
{
private static final long serialVersionUID = 201306061743L;
private final static Logger LOG = LoggerFactory.getLogger(StreamingContainerManager.class);
private long windowStartMillis = System.currentTimeMillis();
private int heartbeatTimeoutMillis = 30000;
private int maxWindowsBehindForStats = 100;
private int recordStatsInterval = 0;
private long lastRecordStatsTime = 0;
private HdfsStatsRecorder statsRecorder;
private final int operatorMaxAttemptCount = 5;
private final String appPath;
private final String checkpointFsPath;
private final String statsFsPath;
protected final Map<String, String> containerStopRequests = new ConcurrentHashMap<String, String>();
protected final ConcurrentLinkedQueue<ContainerStartRequest> containerStartRequests = new ConcurrentLinkedQueue<ContainerStartRequest>();
protected final ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<Runnable>();
protected String shutdownDiagnosticsMessage = "";
protected boolean forcedShutdown = false;
private long lastResourceRequest = 0;
private final Map<String, StramChildAgent> containers = new ConcurrentHashMap<String, StramChildAgent>();
private final PhysicalPlan plan;
private final List<Pair<PTOperator, Long>> purgeCheckpoints = new ArrayList<Pair<PTOperator, Long>>();
// window id to node id to end window stats
private final ConcurrentSkipListMap<Long, Map<Integer, EndWindowStats>> endWindowStatsOperatorMap = new ConcurrentSkipListMap<Long, Map<Integer, EndWindowStats>>();
private long committedWindowId;
// (operator id, port name) to timestamp
private final Map<Pair<Integer, String>, Long> lastEndWindowTimestamps = new HashMap<Pair<Integer, String>, Long>();
private static class EndWindowStats
{
long emitTimestamp = -1;
HashMap<String, Long> dequeueTimestamps = new HashMap<String, Long>(); // input port name to end window dequeue time
}
@Override
public AttributeMap getAttributes()
{
return attributes;
}
@Override
public <T> T attrValue(AttributeMap.AttributeKey<T> key, T defaultValue)
{
T retvalue = attributes.attr(key).get();
if (retvalue == null) {
return defaultValue;
}
return retvalue;
}
public StreamingContainerManager(LogicalPlan dag)
{
super(dag.getAttributes(), null);
this.plan = new PhysicalPlan(dag, this);
attributes.attr(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS).setIfAbsent(500);
// try to align to it pleases eyes.
windowStartMillis -= (windowStartMillis % 1000);
attributes.attr(LogicalPlan.APPLICATION_PATH).setIfAbsent("stram/" + System.currentTimeMillis());
this.appPath = attributes.attr(LogicalPlan.APPLICATION_PATH).get();
this.checkpointFsPath = this.appPath + "/" + LogicalPlan.SUBDIR_CHECKPOINTS;
this.statsFsPath = this.appPath + "/" + LogicalPlan.SUBDIR_STATS;
attributes.attr(LogicalPlan.CHECKPOINT_WINDOW_COUNT).setIfAbsent(30000 / attributes.attr(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS).get());
this.heartbeatTimeoutMillis = this.attrValue(LogicalPlan.HEARTBEAT_TIMEOUT_MILLIS, this.heartbeatTimeoutMillis);
attributes.attr(LogicalPlan.STATS_MAX_ALLOWABLE_WINDOWS_LAG).setIfAbsent(100);
this.maxWindowsBehindForStats = attributes.attr(LogicalPlan.STATS_MAX_ALLOWABLE_WINDOWS_LAG).get();
attributes.attr(LogicalPlan.STATS_RECORD_INTERVAL_MILLIS).setIfAbsent(0);
this.recordStatsInterval = attributes.attr(LogicalPlan.STATS_RECORD_INTERVAL_MILLIS).get();
if (this.recordStatsInterval > 0) {
statsRecorder = new HdfsStatsRecorder();
statsRecorder.setBasePath(this.statsFsPath);
statsRecorder.setup();
}
}
protected PhysicalPlan getPhysicalPlan()
{
return plan;
}
/**
* Check periodically that child containers phone home.
* This is run by the App Master thread (only accessed by one thread).
*/
public void monitorHeartbeat()
{
long currentTms = System.currentTimeMillis();
// look for resource allocation timeout
for (PTContainer c: plan.getContainers()) {
// TODO: single state for resource requested
if (c.getState() == PTContainer.State.NEW || c.getState() == PTContainer.State.KILLED) {
// look for resource allocation timeout
if (lastResourceRequest + this.attrValue(LogicalPlan.RESOURCE_ALLOCATION_TIMEOUT_MILLIS, LogicalPlan.DEFAULT_ALLOCATE_RESOURCE_TIMEOUT_MILLIS) < currentTms) {
String msg = String.format("Shutdown due to resource allocation timeout (%s ms) with container %s (state is %s)", currentTms - lastResourceRequest, c.containerId, c.getState().name());
LOG.warn(msg);
forcedShutdown = true;
shutdownAllContainers(msg);
}
else {
LOG.debug("Waiting for resource: {}m {}", c.getRequiredMemoryMB(), c);
}
}
else if (c.containerId != null) {
StramChildAgent cs = containers.get(c.containerId);
if (!cs.isComplete && cs.lastHeartbeatMillis + heartbeatTimeoutMillis < currentTms) {
// TODO: handle containers hung in deploy requests
if (cs.lastHeartbeatMillis > 0 && !cs.hasPendingWork() && !isApplicationIdle()) {
// request stop (kill) as process may still be hanging around (would have been detected by Yarn otherwise)
LOG.info("Container {}@{} heartbeat timeout ({} ms).", new Object[] {c.containerId, c.host, currentTms - cs.lastHeartbeatMillis});
containerStopRequests.put(c.containerId, c.containerId);
}
}
}
}
processEvents();
committedWindowId = updateCheckpoints();
calculateEndWindowStats();
if (recordStatsInterval > 0 && (lastRecordStatsTime + recordStatsInterval <= System.currentTimeMillis())) {
recordStats();
}
}
private void recordStats()
{
statsRecorder.recordContainers(containers);
statsRecorder.recordOperators(getOperatorInfoList());
lastRecordStatsTime = System.currentTimeMillis();
}
private void calculateEndWindowStats()
{
if (!endWindowStatsOperatorMap.isEmpty()) {
if (endWindowStatsOperatorMap.size() > maxWindowsBehindForStats) {
LOG.warn("Some operators are behind for more than {} windows! Trimming the end window stats map", maxWindowsBehindForStats);
while (endWindowStatsOperatorMap.size() > maxWindowsBehindForStats) {
endWindowStatsOperatorMap.remove(endWindowStatsOperatorMap.firstKey());
}
}
Set<Integer> allCurrentOperators = new TreeSet<Integer>();
for (PTOperator o: plan.getAllOperators()) {
allCurrentOperators.add(o.getId());
}
int numOperators = allCurrentOperators.size();
Long windowId = endWindowStatsOperatorMap.firstKey();
while (windowId != null) {
Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(windowId);
Set<Integer> endWindowStatsOperators = endWindowStatsMap.keySet();
if (allCurrentOperators.containsAll(endWindowStatsOperators)) {
if (endWindowStatsMap.size() < numOperators) {
break;
}
else {
// collected data from all operators for this window id. start latency calculation
List<OperatorMeta> rootOperatorMetas = plan.getRootOperators();
Set<PTOperator> endWindowStatsVisited = new HashSet<PTOperator>();
for (OperatorMeta root: rootOperatorMetas) {
List<PTOperator> rootOperators = plan.getOperators(root);
for (PTOperator rootOperator: rootOperators) {
// DFS for visiting the nodes for latency calculation
calculateLatency(rootOperator, endWindowStatsMap, endWindowStatsVisited);
}
}
endWindowStatsOperatorMap.remove(windowId);
}
}
else {
// the old stats contains operators that do not exist any more
// this is probably right after a partition happens.
endWindowStatsOperatorMap.remove(windowId);
}
windowId = endWindowStatsOperatorMap.higherKey(windowId);
}
}
}
private void calculateLatency(PTOperator oper, Map<Integer, EndWindowStats> endWindowStatsMap, Set<PTOperator> endWindowStatsVisited)
{
endWindowStatsVisited.add(oper);
OperatorStatus operatorStatus = getOperatorStatus(oper);
if (operatorStatus == null) {
LOG.info("Operator status for operator " + oper.getId() + " does not exist yet.");
return;
}
EndWindowStats endWindowStats = endWindowStatsMap.get(oper.getId());
if (endWindowStats == null) {
LOG.info("End window stats is null for operator {}, probably a new operator after partitioning");
return;
}
// find the maximum end window emit time from all input ports
long upstreamMaxEmitTimestamp = -1;
for (PTInput input: oper.inputs) {
if (input.source.source instanceof PTOperator) {
PTOperator upstreamOp = (PTOperator)input.source.source;
EndWindowStats upstreamEndWindowStats = endWindowStatsMap.get(upstreamOp.getId());
if (upstreamEndWindowStats == null) {
LOG.info("End window stats is null for operator {}");
return;
}
if (upstreamEndWindowStats.emitTimestamp > upstreamMaxEmitTimestamp) {
upstreamMaxEmitTimestamp = upstreamEndWindowStats.emitTimestamp;
}
}
}
if (upstreamMaxEmitTimestamp > 0) {
operatorStatus.latencyMA.add(endWindowStats.emitTimestamp - upstreamMaxEmitTimestamp);
}
for (PTOutput output: oper.outputs) {
for (PTInput input: output.sinks) {
if (input.target instanceof PTOperator) {
PTOperator downStreamOp = (PTOperator)input.target;
if (!endWindowStatsVisited.contains(downStreamOp)) {
calculateLatency(downStreamOp, endWindowStatsMap, endWindowStatsVisited);
}
}
}
}
}
private OperatorStatus getOperatorStatus(PTOperator operator)
{
StramChildAgent sca = containers.get(operator.container.containerId);
if (sca == null) {
return null;
}
return sca.operators.get(operator.getId());
}
public int processEvents()
{
int count = 0;
Runnable command;
while ((command = this.eventQueue.poll()) != null) {
try {
command.run();
count++;
}
catch (Exception e) {
// TODO: handle error
LOG.error("Failed to execute " + command, e);
}
}
return count;
}
/**
* Schedule container restart. Called by Stram after a container was terminated
* and requires recovery (killed externally, or after heartbeat timeout). <br>
* Recovery will resolve affected operators (within the container and
* everything downstream with respective recovery checkpoint states).
* Dependent operators will be undeployed and buffer server connections reset prior to
* redeploy to recovery checkpoint.
*
* @param containerId
*/
public void scheduleContainerRestart(String containerId)
{
StramChildAgent cs = getContainerAgent(containerId);
if (cs.shutdownRequested == true) {
return;
}
LOG.info("Initiating recovery for container {}@{}", containerId, cs.container.host);
cs.container.setState(PTContainer.State.KILLED);
cs.container.bufferServerAddress = null;
// building the checkpoint dependency,
// downstream operators will appear first in map
LinkedHashSet<PTOperator> checkpoints = new LinkedHashSet<PTOperator>();
MutableLong ml = new MutableLong();
for (PTOperator node: cs.container.operators) {
// TODO: traverse inline upstream operators
updateRecoveryCheckpoints(node, checkpoints, ml);
}
// redeploy cycle for all affected operators
deploy(Collections.<PTContainer>emptySet(), checkpoints, Sets.newHashSet(cs.container), checkpoints);
}
public void markComplete(String containerId)
{
StramChildAgent cs = containers.get(containerId);
if (cs == null) {
LOG.warn("Completion status for unknown container {}", containerId);
return;
}
cs.isComplete = true;
}
public static class ContainerResource
{
public final String containerId;
public final String host;
public final int memoryMB;
public final int priority;
public ContainerResource(int priority, String containerId, String host, int memoryMB)
{
this.containerId = containerId;
this.host = host;
this.memoryMB = memoryMB;
this.priority = priority;
}
/**
*
* @return String
*/
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("containerId", this.containerId)
.append("host", this.host)
.append("memoryMB", this.memoryMB)
.toString();
}
}
private PTContainer matchContainer(ContainerResource resource)
{
PTContainer match = null;
// match container waiting for resource
for (PTContainer c: plan.getContainers()) {
if (c.getState() == PTContainer.State.NEW || c.getState() == PTContainer.State.KILLED) {
if (c.getResourceRequestPriority() == resource.priority) {
return c;
}
/*
if (container.getRequiredMemoryMB() <= resource.memoryMB) {
if (match == null || match.getRequiredMemoryMB() < container.getRequiredMemoryMB()) {
match = container;
}
}
*/
}
}
return match;
}
/**
* Assign operators to allocated container resource.
*
* @param resource
* @param bufferServerAddr
* @return
*/
public StramChildAgent assignContainer(ContainerResource resource, InetSocketAddress bufferServerAddr)
{
PTContainer container = matchContainer(resource);
if (container == null) {
LOG.debug("No container matching allocated resource {}", resource);
return null;
}
container.setState(PTContainer.State.ALLOCATED);
if (container.containerId != null) {
LOG.info("Removing existing container agent {}", container.containerId);
this.containers.remove(container.containerId);
}
container.containerId = resource.containerId;
container.host = resource.host;
container.bufferServerAddress = bufferServerAddr;
container.setAllocatedMemoryMB(resource.memoryMB);
StramChildAgent sca = new StramChildAgent(container, newStreamingContainerContext());
containers.put(resource.containerId, sca);
return sca;
}
private StreamingContainerContext newStreamingContainerContext()
{
StreamingContainerContext scc = new StreamingContainerContext(attributes);
scc.startWindowMillis = this.windowStartMillis;
return scc;
}
public StramChildAgent getContainerAgent(String containerId)
{
StramChildAgent cs = containers.get(containerId);
if (cs == null) {
throw new AssertionError("Unknown container " + containerId);
}
return cs;
}
public Collection<StramChildAgent> getContainerAgents()
{
return this.containers.values();
}
/**
* process the heartbeat from each container.
* called by the RPC thread for each container. (i.e. called by multiple threads)
*
* @param heartbeat
* @return
*/
public ContainerHeartbeatResponse processHeartbeat(ContainerHeartbeat heartbeat)
{
boolean containerIdle = true;
long currentTimeMillis = System.currentTimeMillis();
StramChildAgent sca = this.containers.get(heartbeat.getContainerId());
if (sca == null) {
// could be orphaned container that was replaced and needs to terminate
LOG.error("Unknown container " + heartbeat.getContainerId());
ContainerHeartbeatResponse response = new ContainerHeartbeatResponse();
response.shutdown = true;
return response;
}
//LOG.debug("{} {} {}", new Object[]{sca.container.containerId, sca.container.bufferServerAddress, sca.container.getState()});
if (sca.container.getState() != PTContainer.State.ACTIVE) {
// capture dynamically assigned address from container
if (sca.container.bufferServerAddress == null && heartbeat.bufferServerHost != null) {
sca.container.bufferServerAddress = InetSocketAddress.createUnresolved(heartbeat.bufferServerHost, heartbeat.bufferServerPort);
LOG.info("Container {} buffer server: {}", sca.container.containerId, sca.container.bufferServerAddress);
}
sca.container.setState(PTContainer.State.ACTIVE);
sca.jvmName = heartbeat.jvmName;
}
if (heartbeat.restartRequested) {
LOG.error("Container {} restart request", sca.container.containerId);
containerStopRequests.put(sca.container.containerId, sca.container.containerId);
}
sca.memoryMBFree = heartbeat.memoryMBFree;
long elapsedMillis = currentTimeMillis - sca.lastHeartbeatMillis;
for (StreamingNodeHeartbeat shb: heartbeat.getDnodeEntries()) {
OperatorStatus status = sca.updateOperatorStatus(shb);
if (status == null) {
LOG.error("Heartbeat for unknown operator {} (container {})", shb.getNodeId(), heartbeat.getContainerId());
continue;
}
//LOG.debug("heartbeat {}/{}@{}: {} {}", new Object[] { shb.getNodeId(), status.operator.getName(), heartbeat.getContainerId(), shb.getState(),
// Codec.getStringWindowId(shb.getLastBackupWindowId()) });
StreamingNodeHeartbeat previousHeartbeat = status.lastHeartbeat;
status.lastHeartbeat = shb;
if (shb.getState().compareTo(DNodeState.FAILED.name()) == 0) {
// count failure transitions *->FAILED, applies to initialization as well as intermittent failures
if (previousHeartbeat == null || DNodeState.FAILED.name().compareTo(previousHeartbeat.getState()) != 0) {
status.operator.failureCount++;
LOG.warn("Operator failure: {} count: {}", status.operator, status.operator.failureCount);
Integer maxAttempts = status.operator.getOperatorMeta().attrValue(OperatorContext.RECOVERY_ATTEMPTS, this.operatorMaxAttemptCount);
if (status.operator.failureCount <= maxAttempts) {
// restart entire container in attempt to recover operator
// in the future a more sophisticated recovery strategy could
// involve initial redeploy attempt(s) of affected operator in
// existing container or sandbox container for just the operator
LOG.error("Issuing container stop to restart after operator failure {}", status.operator);
containerStopRequests.put(sca.container.containerId, sca.container.containerId);
}
else {
String msg = String.format("Shutdown after reaching failure threshold for %s", status.operator);
LOG.warn(msg);
forcedShutdown = true;
shutdownAllContainers(msg);
}
}
}
if (!status.isIdle()) {
containerIdle = false;
long tuplesProcessed = 0;
long tuplesEmitted = 0;
long totalCpuTimeUsed = 0;
long maxDequeueTimestamp = -1;
List<OperatorStats> statsList = shb.getWindowStats();
for (OperatorStats stats: statsList) {
/* report checkpointedWindowId status of the operator */
if (status.operator.recoveryCheckpoint < stats.checkpointedWindowId) {
addCheckpoint(status.operator, stats.checkpointedWindowId);
}
/* report all the other stuff */
// calculate the stats related to end window
EndWindowStats endWindowStats = new EndWindowStats(); // end window stats for a particular window id for a particular node
Collection<PortStats> ports = stats.inputPorts;
if (ports != null) {
for (PortStats s: ports) {
PortStatus ps = status.inputPortStatusList.get(s.portname);
if (ps == null) {
ps = sca.new PortStatus();
ps.portName = s.portname;
status.inputPortStatusList.put(s.portname, ps);
}
ps.totalTuples += s.processedCount;
tuplesProcessed += s.processedCount;
endWindowStats.dequeueTimestamps.put(s.portname, s.endWindowTimestamp);
Pair<Integer, String> operatorPortName = new Pair<Integer, String>(status.operator.getId(), s.portname);
if (lastEndWindowTimestamps.containsKey(operatorPortName) && (s.endWindowTimestamp > lastEndWindowTimestamps.get(operatorPortName))) {
ps.tuplesPSMA10.add(s.processedCount * 1000 / (s.endWindowTimestamp - lastEndWindowTimestamps.get(operatorPortName)));
}
lastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp);
if (s.endWindowTimestamp > maxDequeueTimestamp) {
maxDequeueTimestamp = s.endWindowTimestamp;
}
}
}
ports = stats.outputPorts;
if (ports != null) {
for (PortStats s: ports) {
PortStatus ps = status.outputPortStatusList.get(s.portname);
if (ps == null) {
ps = sca.new PortStatus();
ps.portName = s.portname;
status.outputPortStatusList.put(s.portname, ps);
}
ps.totalTuples += s.processedCount;
tuplesEmitted += s.processedCount;
Pair<Integer, String> operatorPortName = new Pair<Integer, String>(status.operator.getId(), s.portname);
// the second condition is needed when
// 1) the operator is redeployed and is playing back the tuples, or
// 2) the operator is catching up very fast and the endWindowTimestamp of subsequent windows is less than one millisecond
if (lastEndWindowTimestamps.containsKey(operatorPortName) &&
(s.endWindowTimestamp > lastEndWindowTimestamps.get(operatorPortName))) {
ps.tuplesPSMA10.add(s.processedCount * 1000 / (s.endWindowTimestamp - lastEndWindowTimestamps.get(operatorPortName)));
}
lastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp);
}
if (ports.size() > 0) {
endWindowStats.emitTimestamp = ports.iterator().next().endWindowTimestamp;
}
}
// for output operator, just take the maximum dequeue time for emit timestamp.
// (we don't know the latency for output operators because they don't emit tuples)
if (endWindowStats.emitTimestamp < 0) {
endWindowStats.emitTimestamp = maxDequeueTimestamp;
}
status.currentWindowId = stats.windowId;
totalCpuTimeUsed += stats.cpuTimeUsed;
Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(stats.windowId);
if (endWindowStatsMap == null) {
endWindowStatsOperatorMap.putIfAbsent(stats.windowId, new ConcurrentHashMap<Integer, EndWindowStats>());
endWindowStatsMap = endWindowStatsOperatorMap.get(stats.windowId);
}
endWindowStatsMap.put(shb.getNodeId(), endWindowStats);
}
status.totalTuplesProcessed += tuplesProcessed;
status.totalTuplesEmitted += tuplesEmitted;
if (elapsedMillis > 0) {
//status.tuplesProcessedPSMA10.add((tuplesProcessed * 1000) / elapsedMillis);
//status.tuplesEmittedPSMA10.add((tuplesEmitted * 1000) / elapsedMillis);
status.tuplesProcessedPSMA10 = 0;
status.tuplesEmittedPSMA10 = 0;
status.cpuPercentageMA10.add((double)totalCpuTimeUsed * 100 / (elapsedMillis * 1000000));
for (PortStatus ps: status.inputPortStatusList.values()) {
Long numBytes = shb.getBufferServerBytes().get(ps.portName);
if (numBytes != null) {
ps.bufferServerBytesPSMA10.add(numBytes * 1000 / elapsedMillis);
}
status.tuplesProcessedPSMA10 += ps.tuplesPSMA10.getAvg();
}
for (PortStatus ps: status.outputPortStatusList.values()) {
Long numBytes = shb.getBufferServerBytes().get(ps.portName);
if (numBytes != null) {
ps.bufferServerBytesPSMA10.add(numBytes * 1000 / elapsedMillis);
}
status.tuplesEmittedPSMA10 += ps.tuplesPSMA10.getAvg();
}
if (status.operator.statsMonitors != null) {
long tps = status.operator.inputs.isEmpty() ? status.tuplesEmittedPSMA10 : status.tuplesProcessedPSMA10;
for (StatsHandler sm: status.operator.statsMonitors) {
sm.onThroughputUpdate(status.operator, tps);
sm.onCpuPercentageUpdate(status.operator, status.cpuPercentageMA10.getAvg());
}
}
}
}
status.recordingNames = shb.getRecordingNames();
}
sca.lastHeartbeatMillis = currentTimeMillis;
ContainerHeartbeatResponse rsp = sca.pollRequest();
if (rsp == null) {
rsp = new ContainerHeartbeatResponse();
}
// below should be merged into pollRequest
if (containerIdle && isApplicationIdle()) {
LOG.info("requesting idle shutdown for container {}", heartbeat.getContainerId());
rsp.shutdown = true;
}
else {
if (sca.shutdownRequested) {
LOG.info("requesting shutdown for container {}", heartbeat.getContainerId());
rsp.shutdown = true;
}
}
List<StramToNodeRequest> requests = rsp.nodeRequests != null ? rsp.nodeRequests : new ArrayList<StramToNodeRequest>();
ConcurrentLinkedQueue<StramToNodeRequest> operatorRequests = sca.getOperatorRequests();
while (true) {
StramToNodeRequest r = operatorRequests.poll();
if (r == null) {
break;
}
requests.add(r);
}
rsp.nodeRequests = requests;
rsp.committedWindowId = committedWindowId;
return rsp;
}
private boolean isApplicationIdle()
{
for (StramChildAgent csa: this.containers.values()) {
if (!csa.isIdle()) {
return false;
}
}
return true;
}
void addCheckpoint(PTOperator node, long backupWindowId)
{
synchronized (node.checkpointWindows) {
if (!node.checkpointWindows.isEmpty()) {
Long lastCheckpoint = node.checkpointWindows.getLast();
// skip unless checkpoint moves
if (lastCheckpoint.longValue() != backupWindowId) {
if (lastCheckpoint.longValue() > backupWindowId) {
// list needs to have max windowId last
LOG.warn("Out of sequence checkpoint {} last {} (operator {})", new Object[] {backupWindowId, lastCheckpoint, node});
ListIterator<Long> li = node.checkpointWindows.listIterator();
while (li.hasNext() && li.next().longValue() < backupWindowId) {
continue;
}
if (li.previous() != backupWindowId) {
li.add(backupWindowId);
}
}
else {
node.checkpointWindows.add(backupWindowId);
}
}
}
else {
node.checkpointWindows.add(backupWindowId);
}
}
}
/**
* Compute checkpoints required for a given operator instance to be recovered.
* This is done by looking at checkpoints available for downstream dependencies first,
* and then selecting the most recent available checkpoint that is smaller than downstream.
*
* @param operator Operator instance for which to find recovery checkpoint
* @param visited Set into which to collect visited dependencies
* @param committedWindowId
* @return Checkpoint that can be used to recover (along with dependencies in visitedCheckpoints).
*/
public long updateRecoveryCheckpoints(PTOperator operator, Set<PTOperator> visited, MutableLong committedWindowId)
{
if (operator.recoveryCheckpoint < committedWindowId.longValue()) {
committedWindowId.setValue(operator.recoveryCheckpoint);
}
// checkpoint frozen until deployment complete
if (operator.getState() == State.PENDING_DEPLOY) {
return operator.recoveryCheckpoint;
}
long maxCheckpoint = operator.getRecentCheckpoint();
// find smallest of most recent subscriber checkpoints
for (PTOutput out: operator.outputs) {
for (PhysicalPlan.PTInput sink: out.sinks) {
PTOperator sinkOperator = (PTOperator)sink.target;
if (!visited.contains(sinkOperator)) {
// downstream traversal
updateRecoveryCheckpoints(sinkOperator, visited, committedWindowId);
}
// recovery window id cannot move backwards
// when dynamically adding new operators
if (sinkOperator.recoveryCheckpoint >= operator.recoveryCheckpoint) {
maxCheckpoint = Math.min(maxCheckpoint, sinkOperator.recoveryCheckpoint);
}
}
}
// find commit point for downstream dependency, remove previous checkpoints
long c1 = 0;
synchronized (operator.checkpointWindows) {
if (!operator.checkpointWindows.isEmpty()) {
if ((c1 = operator.checkpointWindows.getFirst().longValue()) <= maxCheckpoint) {
long c2 = 0;
while (operator.checkpointWindows.size() > 1 && (c2 = operator.checkpointWindows.get(1).longValue()) <= maxCheckpoint) {
operator.checkpointWindows.removeFirst();
//LOG.debug("Checkpoint to delete: operator={} windowId={}", operator.getName(), c1);
this.purgeCheckpoints.add(new Pair<PTOperator, Long>(operator, c1));
c1 = c2;
}
}
else {
c1 = 0;
}
}
}
visited.add(operator);
//LOG.debug("Operator {} checkpoints: commit {} recent {}", new Object[] {operator.getName(), c1, operator.checkpointWindows});
return operator.recoveryCheckpoint = c1;
}
/**
* Visit all operators to update current checkpoint based on updated downstream state.
* Purge older checkpoints that are no longer needed.
*/
private long updateCheckpoints()
{
MutableLong lCommittedWindowId = new MutableLong(Long.MAX_VALUE);
Set<PTOperator> visitedCheckpoints = new LinkedHashSet<PTOperator>();
for (OperatorMeta logicalOperator: plan.getRootOperators()) {
List<PTOperator> operators = plan.getOperators(logicalOperator);
if (operators != null) {
for (PTOperator operator: operators) {
updateRecoveryCheckpoints(operator, visitedCheckpoints, lCommittedWindowId);
}
}
}
purgeCheckpoints();
return lCommittedWindowId.longValue();
}
private BufferServerController getBufferServerClient(PTOperator operator)
{
BufferServerController bsc = new BufferServerController(operator.getLogicalId());
InetSocketAddress address = operator.container.bufferServerAddress;
StramChild.eventloop.connect(address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address, bsc);
return bsc;
}
private void purgeCheckpoints()
{
StorageAgent ba = new HdfsStorageAgent(new Configuration(), checkpointFsPath);
for (Pair<PTOperator, Long> p: purgeCheckpoints) {
PTOperator operator = p.getFirst();
try {
ba.delete(operator.getId(), p.getSecond());
}
catch (Exception e) {
LOG.error("Failed to purge checkpoint " + p, e);
}
// delete stream state when using buffer server
for (PTOutput out: operator.outputs) {
if (!out.isDownStreamInline()) {
// following needs to match the concat logic in StramChild
String sourceIdentifier = Integer.toString(operator.getId()).concat(StramChild.NODE_PORT_CONCAT_SEPARATOR).concat(out.portName);
// delete everything from buffer server prior to new checkpoint
BufferServerController bsc = getBufferServerClient(operator);
try {
bsc.purge(null, sourceIdentifier, operator.checkpointWindows.getFirst() - 1);
}
catch (Throwable t) {
LOG.error("Failed to purge " + bsc.addr + " " + sourceIdentifier, t);
}
}
}
}
purgeCheckpoints.clear();
}
/**
* Mark all containers for shutdown, next container heartbeat response
* will propagate the shutdown request. This is controlled soft shutdown.
* If containers don't respond, the application can be forcefully terminated
* via yarn using forceKillApplication.
*
* @param message
*/
public void shutdownAllContainers(String message)
{
this.shutdownDiagnosticsMessage = message;
LOG.info("Initiating application shutdown: " + message);
for (StramChildAgent cs: this.containers.values()) {
cs.shutdownRequested = true;
}
}
@Override
public StorageAgent getStorageAgent()
{
return new HdfsStorageAgent(new Configuration(), this.checkpointFsPath);
}
private Map<PTContainer, List<PTOperator>> groupByContainer(Collection<PTOperator> operators)
{
Map<PTContainer, List<PTOperator>> m = new HashMap<PTContainer, List<PTOperator>>();
for (PTOperator node: operators) {
List<PTOperator> nodes = m.get(node.container);
if (nodes == null) {
nodes = new ArrayList<PhysicalPlan.PTOperator>();
m.put(node.container, nodes);
}
nodes.add(node);
}
return m;
}
@Override
public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy)
{
Map<PTContainer, List<PTOperator>> undeployGroups = groupByContainer(undeploy);
// stop affected operators (exclude new/failed containers)
// order does not matter, remove all operators in each container in one sweep
for (Map.Entry<PTContainer, List<PTOperator>> e: undeployGroups.entrySet()) {
if (!startContainers.contains(e.getKey()) && !releaseContainers.contains(e.getKey())) {
e.getKey().pendingUndeploy.addAll(e.getValue());
}
}
// start new containers
for (PTContainer c: startContainers) {
ContainerStartRequest dr = new ContainerStartRequest(c);
containerStartRequests.add(dr);
lastResourceRequest = System.currentTimeMillis();
for (PTOperator operator: c.operators) {
operator.setState(PTOperator.State.INACTIVE);
}
}
// (re)deploy affected operators
// can happen in parallel after buffer server state for recovered publishers is reset
Map<PTContainer, List<PTOperator>> deployGroups = groupByContainer(deploy);
for (Map.Entry<PTContainer, List<PTOperator>> e: deployGroups.entrySet()) {
if (!startContainers.contains(e.getKey())) {
// to reset publishers, clean buffer server past checkpoint so subscribers don't read stale data (including end of stream)
for (PTOperator operator: e.getValue()) {
for (PTOutput out: operator.outputs) {
if (!out.isDownStreamInline()) {
// following needs to match the concat logic in StramChild
String sourceIdentifier = Integer.toString(operator.getId()).concat(StramChild.NODE_PORT_CONCAT_SEPARATOR).concat(out.portName);
// TODO: find way to mock this when testing rest of logic
if (operator.container.bufferServerAddress.getPort() != 0) {
BufferServerController bsc = getBufferServerClient(operator);
// reset publisher (stale operator may still write data until disconnected)
// ensures new subscriber starting to read from checkpoint will wait until publisher redeploy cycle is complete
try {
bsc.reset(null, sourceIdentifier, 0);
}
catch (Exception ex) {
LOG.error("Failed to reset buffer server {} {}", sourceIdentifier, ex);
}
}
}
}
}
}
// add to operators that we expect to deploy
LOG.debug("scheduling deploy {} {}", e.getKey(), e.getValue());
e.getKey().pendingDeploy.addAll(e.getValue());
}
// stop containers that are no longer used
for (PTContainer c: releaseContainers) {
StramChildAgent sca = containers.get(c.containerId);
if (sca != null) {
LOG.debug("Container marked for shutdown: {}", c);
// TODO: set deactivated state and monitor soft shutdown
sca.shutdownRequested = true;
}
}
}
@Override
public void dispatch(Runnable r)
{
this.eventQueue.add(r);
}
public OperatorInfo getOperatorInfo(String operatorId)
{
for (PTContainer container: this.plan.getContainers()) {
String containerId = container.containerId;
StramChildAgent sca = containerId != null ? this.containers.get(container.containerId) : null;
for (PTOperator operator: container.operators) {
if (operatorId.equals(Integer.toString(operator.getId()))) {
OperatorStatus os = (sca != null) ? sca.operators.get(operator.getId()) : null;
return fillOperatorInfo(operator, os);
}
}
}
return null;
}
public ArrayList<OperatorInfo> getOperatorInfoList()
{
ArrayList<OperatorInfo> infoList = new ArrayList<OperatorInfo>();
for (PTContainer container: this.plan.getContainers()) {
String containerId = container.containerId;
StramChildAgent sca = containerId != null ? this.containers.get(container.containerId) : null;
for (PTOperator operator: container.operators) {
OperatorStatus os = (sca != null) ? sca.operators.get(operator.getId()) : null;
infoList.add(fillOperatorInfo(operator, os));
}
}
return infoList;
}
private OperatorInfo fillOperatorInfo(PTOperator operator, OperatorStatus os)
{
OperatorInfo ni = new OperatorInfo();
ni.container = operator.container.containerId;
ni.host = operator.container.host;
ni.id = Integer.toString(operator.getId());
ni.name = operator.getName();
ni.className = operator.getOperatorMeta().getOperator().getClass().getName();
ni.status = operator.getState().toString();
if (os != null) {
ni.totalTuplesProcessed = os.totalTuplesProcessed;
ni.totalTuplesEmitted = os.totalTuplesEmitted;
ni.tuplesProcessedPSMA10 = os.tuplesProcessedPSMA10;
ni.tuplesEmittedPSMA10 = os.tuplesEmittedPSMA10;
ni.cpuPercentageMA10 = os.cpuPercentageMA10.getAvg();
ni.latencyMA = os.latencyMA.getAvg();
ni.failureCount = os.operator.failureCount;
ni.recoveryWindowId = os.operator.recoveryCheckpoint;
ni.currentWindowId = os.currentWindowId;
ni.recordingNames = os.recordingNames;
if (os.lastHeartbeat != null) {
ni.lastHeartbeat = os.lastHeartbeat.getGeneratedTms();
}
for (PortStatus ps: os.inputPortStatusList.values()) {
PortInfo pinfo = new PortInfo();
pinfo.name = ps.portName;
pinfo.type = "input";
pinfo.totalTuples = ps.totalTuples;
pinfo.tuplesPSMA10 = ps.tuplesPSMA10.getAvg();
pinfo.bufferServerBytesPSMA10 = ps.bufferServerBytesPSMA10.getAvg();
ni.addInputPort(pinfo);
}
for (PortStatus ps: os.outputPortStatusList.values()) {
PortInfo pinfo = new PortInfo();
pinfo.name = ps.portName;
pinfo.type = "output";
pinfo.totalTuples = ps.totalTuples;
pinfo.tuplesPSMA10 = ps.tuplesPSMA10.getAvg();
pinfo.bufferServerBytesPSMA10 = ps.bufferServerBytesPSMA10.getAvg();
ni.addOutputPort(pinfo);
}
}
return ni;
}
private static class RecordingRequestFilter implements Predicate<StramToNodeRequest>
{
final static Set<StramToNodeRequest.RequestType> MATCH_TYPES = Sets.newHashSet(RequestType.START_RECORDING, RequestType.STOP_RECORDING, RequestType.SYNC_RECORDING);
@Override
public boolean apply(@Nullable StramToNodeRequest input)
{
return MATCH_TYPES.contains(input.getRequestType());
}
}
private class SetOperatorPropertyRequestFilter implements Predicate<StramToNodeRequest>
{
final String propertyKey;
SetOperatorPropertyRequestFilter(String key)
{
this.propertyKey = key;
}
@Override
public boolean apply(@Nullable StramToNodeRequest input)
{
return input.getRequestType() == RequestType.SET_PROPERTY && input.setPropertyKey.equals(propertyKey);
}
}
private void updateOnDeployRequests(PTOperator p, Predicate<StramToNodeRequest> superseded, StramToNodeRequest newRequest)
{
// filter existing requests
List<StramToNodeRequest> cloneRequests = new ArrayList<StramToNodeRequest>(p.deployRequests.size());
for (StramToNodeRequest existingRequest: p.deployRequests) {
if (!superseded.apply(existingRequest)) {
cloneRequests.add(existingRequest);
}
}
// add new request, if any
if (newRequest != null) {
cloneRequests.add(newRequest);
}
p.deployRequests = Collections.unmodifiableList(cloneRequests);
}
private StramChildAgent getContainerAgentFromOperatorId(int operatorId)
{
// Thomas, please change it when you get a chance. -- David
for (StramChildAgent container: containers.values()) {
if (container.operators.containsKey(operatorId)) {
return container;
}
}
// throw exception that propagates to web client
throw new NotFoundException("Operator ID " + operatorId + " not found");
}
public void startRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.START_RECORDING);
sca.addOperatorRequest(request);
OperatorStatus os = sca.operators.get(operId);
if (os != null) {
// restart on deploy
updateOnDeployRequests(os.operator, new RecordingRequestFilter(), request);
}
}
public void stopRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.STOP_RECORDING);
sca.addOperatorRequest(request);
OperatorStatus os = sca.operators.get(operId);
if (os != null) {
// no stop on deploy, but remove existing start
updateOnDeployRequests(os.operator, new RecordingRequestFilter(), null);
}
}
public void syncRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.SYNC_RECORDING);
sca.addOperatorRequest(request);
}
public void stopContainer(String containerId)
{
this.containerStopRequests.put(containerId, containerId);
}
public void setOperatorProperty(String operatorId, String propertyName, String propertyValue)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
Map<String, String> properties = Collections.singletonMap(propertyName, propertyValue);
DAGPropertiesBuilder.setOperatorProperties(logicalOperator.getOperator(), properties);
// need to record this to a log in the future when review history is supported
List<PTOperator> operators = plan.getOperators(logicalOperator);
for (PTOperator o: operators) {
StramChildAgent sca = getContainerAgent(o.getContainer().containerId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(o.getId());
request.setPropertyKey = propertyName;
request.setPropertyValue = propertyValue;
request.setRequestType(RequestType.SET_PROPERTY);
sca.addOperatorRequest(request);
// restart on deploy
updateOnDeployRequests(o, new SetOperatorPropertyRequestFilter(propertyName), request);
}
}
public Map<String, Object> getApplicationAttributes()
{
LogicalPlan lp = getLogicalPlan();
return lp.getAttributes().valueMap();
}
public Map<String, Object> getOperatorAttributes(String operatorId)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
return logicalOperator.getAttributes().valueMap();
}
public Map<String, Object> getPortAttributes(String operatorId, String portName)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
Operators.PortMappingDescriptor portMap = new Operators.PortMappingDescriptor();
Operators.describe(logicalOperator.getOperator(), portMap);
InputPort<?> inputPort = portMap.inputPorts.get(portName);
if (inputPort != null) {
return logicalOperator.getMeta(inputPort).getAttributes().valueMap();
} else {
OutputPort<?> outputPort = portMap.outputPorts.get(portName);
if (outputPort == null) {
throw new IllegalArgumentException("Invalid port name " + portName);
}
return logicalOperator.getMeta(outputPort).getAttributes().valueMap();
}
}
public LogicalPlan getLogicalPlan()
{
return plan.getDAG();
}
/**
* Asynchronously process the logical, physical plan and execution layer changes.
* Caller can use the returned future to block until processing is complete.
* @param requests
* @return
* @throws Exception
*/
public FutureTask<Object> logicalPlanModification(List<LogicalPlanRequest> requests) throws Exception
{
// delegate processing to dispatch thread
FutureTask<Object> future = new FutureTask<Object>(new LogicalPlanChangeRunnable(requests));
dispatch(future);
//LOG.info("Scheduled plan changes: {}", requests);
return future;
}
private class LogicalPlanChangeRunnable implements java.util.concurrent.Callable<Object> {
final List<LogicalPlanRequest> requests;
private LogicalPlanChangeRunnable(List<LogicalPlanRequest> requests)
{
this.requests = requests;
}
@Override
public Object call() throws Exception {
// clone logical plan, for dry run and validation
LOG.info("Begin plan changes: {}", requests);
LogicalPlan lp = plan.getDAG();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
LogicalPlan.write(lp, bos);
bos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
lp = LogicalPlan.read(bis);
PlanModifier pm = new PlanModifier(lp);
for (LogicalPlanRequest request : requests) {
LOG.debug("Dry run plan change: {}", request);
request.execute(pm);
}
lp.validate();
// perform changes on live plan
pm = new PlanModifier(plan);
for (LogicalPlanRequest request : requests) {
request.execute(pm);
}
pm.applyChanges(StreamingContainerManager.this);
LOG.info("Plan changes applied: {}", requests);
return null;
}
}
}
| engine/src/main/java/com/datatorrent/stram/StreamingContainerManager.java | /*
* Copyright (c) 2012 Malhar, Inc.
* All Rights Reserved.
*/
package com.datatorrent.stram;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.FutureTask;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang.mutable.MutableLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.webapp.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.engine.OperatorStats;
import com.datatorrent.engine.OperatorStats.PortStats;
import com.datatorrent.stram.PhysicalPlan.PTContainer;
import com.datatorrent.stram.PhysicalPlan.PTInput;
import com.datatorrent.stram.PhysicalPlan.PTOperator;
import com.datatorrent.stram.PhysicalPlan.PTOutput;
import com.datatorrent.stram.PhysicalPlan.PlanContext;
import com.datatorrent.stram.PhysicalPlan.StatsHandler;
import com.datatorrent.stram.PhysicalPlan.PTOperator.State;
import com.datatorrent.stram.StramChildAgent.ContainerStartRequest;
import com.datatorrent.stram.StramChildAgent.OperatorStatus;
import com.datatorrent.stram.StramChildAgent.PortStatus;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest.RequestType;
import com.datatorrent.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState;
import com.datatorrent.stram.api.BaseContext;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.LogicalPlanRequest;
import com.datatorrent.stram.plan.logical.Operators;
import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta;
import com.datatorrent.stram.plan.physical.PlanModifier;
import com.datatorrent.stram.webapp.OperatorInfo;
import com.datatorrent.stram.webapp.PortInfo;
import com.google.common.base.Predicate;
import com.google.common.collect.Sets;
import com.datatorrent.api.AttributeMap;
import com.datatorrent.api.Operator.InputPort;
import com.datatorrent.api.Operator.OutputPort;
import com.datatorrent.api.StorageAgent;
import com.datatorrent.common.util.Pair;
/**
*
* Tracks topology provisioning/allocation to containers<p>
* <br>
* The tasks include<br>
* Provisioning operators one container at a time. Each container gets assigned the operators, streams and its context<br>
* Monitors run time operations including heartbeat protocol and node status<br>
* Operator recovery and restart<br>
* <br>
*
*/
public class StreamingContainerManager extends BaseContext implements PlanContext
{
private static final long serialVersionUID = 201306061743L;
private final static Logger LOG = LoggerFactory.getLogger(StreamingContainerManager.class);
private long windowStartMillis = System.currentTimeMillis();
private int heartbeatTimeoutMillis = 30000;
private int maxWindowsBehindForStats = 100;
private int recordStatsInterval = 0;
private long lastRecordStatsTime = 0;
private HdfsStatsRecorder statsRecorder;
private final int operatorMaxAttemptCount = 5;
private final String appPath;
private final String checkpointFsPath;
private final String statsFsPath;
protected final Map<String, String> containerStopRequests = new ConcurrentHashMap<String, String>();
protected final ConcurrentLinkedQueue<ContainerStartRequest> containerStartRequests = new ConcurrentLinkedQueue<ContainerStartRequest>();
protected final ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<Runnable>();
protected String shutdownDiagnosticsMessage = "";
protected boolean forcedShutdown = false;
private long lastResourceRequest = 0;
private final Map<String, StramChildAgent> containers = new ConcurrentHashMap<String, StramChildAgent>();
private final PhysicalPlan plan;
private final List<Pair<PTOperator, Long>> purgeCheckpoints = new ArrayList<Pair<PTOperator, Long>>();
// window id to node id to end window stats
private final ConcurrentSkipListMap<Long, Map<Integer, EndWindowStats>> endWindowStatsOperatorMap = new ConcurrentSkipListMap<Long, Map<Integer, EndWindowStats>>();
private long committedWindowId;
// (operator id, port name) to timestamp
private final Map<Pair<Integer, String>, Long> lastEndWindowTimestamps = new HashMap<Pair<Integer, String>, Long>();
private static class EndWindowStats
{
long emitTimestamp = -1;
HashMap<String, Long> dequeueTimestamps = new HashMap<String, Long>(); // input port name to end window dequeue time
}
@Override
public AttributeMap getAttributes()
{
return attributes;
}
@Override
public <T> T attrValue(AttributeMap.AttributeKey<T> key, T defaultValue)
{
T retvalue = attributes.attr(key).get();
if (retvalue == null) {
return defaultValue;
}
return retvalue;
}
public StreamingContainerManager(LogicalPlan dag)
{
super(dag.getAttributes(), null);
this.plan = new PhysicalPlan(dag, this);
attributes.attr(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS).setIfAbsent(500);
// try to align to it pleases eyes.
windowStartMillis -= (windowStartMillis % 1000);
attributes.attr(LogicalPlan.APPLICATION_PATH).setIfAbsent("stram/" + System.currentTimeMillis());
this.appPath = attributes.attr(LogicalPlan.APPLICATION_PATH).get();
this.checkpointFsPath = this.appPath + "/" + LogicalPlan.SUBDIR_CHECKPOINTS;
this.statsFsPath = this.appPath + "/" + LogicalPlan.SUBDIR_STATS;
attributes.attr(LogicalPlan.CHECKPOINT_WINDOW_COUNT).setIfAbsent(30000 / attributes.attr(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS).get());
this.heartbeatTimeoutMillis = this.attrValue(LogicalPlan.HEARTBEAT_TIMEOUT_MILLIS, this.heartbeatTimeoutMillis);
attributes.attr(LogicalPlan.STATS_MAX_ALLOWABLE_WINDOWS_LAG).setIfAbsent(100);
this.maxWindowsBehindForStats = attributes.attr(LogicalPlan.STATS_MAX_ALLOWABLE_WINDOWS_LAG).get();
attributes.attr(LogicalPlan.STATS_RECORD_INTERVAL_MILLIS).setIfAbsent(0);
this.recordStatsInterval = attributes.attr(LogicalPlan.STATS_RECORD_INTERVAL_MILLIS).get();
if (this.recordStatsInterval > 0) {
statsRecorder = new HdfsStatsRecorder();
statsRecorder.setBasePath(this.statsFsPath);
statsRecorder.setup();
}
}
protected PhysicalPlan getPhysicalPlan()
{
return plan;
}
/**
* Check periodically that child containers phone home.
* This is run by the App Master thread (only accessed by one thread).
*/
public void monitorHeartbeat()
{
long currentTms = System.currentTimeMillis();
// look for resource allocation timeout
for (PTContainer c: plan.getContainers()) {
// TODO: single state for resource requested
if (c.getState() == PTContainer.State.NEW || c.getState() == PTContainer.State.KILLED) {
// look for resource allocation timeout
if (lastResourceRequest + this.attrValue(LogicalPlan.RESOURCE_ALLOCATION_TIMEOUT_MILLIS, LogicalPlan.DEFAULT_ALLOCATE_RESOURCE_TIMEOUT_MILLIS) < currentTms) {
String msg = String.format("Shutdown due to resource allocation timeout (%s ms) with container %s (state is %s)", currentTms - lastResourceRequest, c.containerId, c.getState().name());
LOG.warn(msg);
forcedShutdown = true;
shutdownAllContainers(msg);
}
else {
LOG.debug("Waiting for resource: {}m {}", c.getRequiredMemoryMB(), c);
}
}
else if (c.containerId != null) {
StramChildAgent cs = containers.get(c.containerId);
if (!cs.isComplete && cs.lastHeartbeatMillis + heartbeatTimeoutMillis < currentTms) {
// TODO: handle containers hung in deploy requests
if (cs.lastHeartbeatMillis > 0 && !cs.hasPendingWork() && !isApplicationIdle()) {
// request stop (kill) as process may still be hanging around (would have been detected by Yarn otherwise)
LOG.info("Container {}@{} heartbeat timeout ({} ms).", new Object[] {c.containerId, c.host, currentTms - cs.lastHeartbeatMillis});
containerStopRequests.put(c.containerId, c.containerId);
}
}
}
}
processEvents();
committedWindowId = updateCheckpoints();
calculateEndWindowStats();
if (recordStatsInterval > 0 && (lastRecordStatsTime + recordStatsInterval <= System.currentTimeMillis())) {
recordStats();
}
}
private void recordStats()
{
statsRecorder.recordContainers(containers);
statsRecorder.recordOperators(getOperatorInfoList());
lastRecordStatsTime = System.currentTimeMillis();
}
private void calculateEndWindowStats()
{
if (!endWindowStatsOperatorMap.isEmpty()) {
if (endWindowStatsOperatorMap.size() > maxWindowsBehindForStats) {
LOG.warn("Some operators are behind for more than {} windows! Trimming the end window stats map", maxWindowsBehindForStats);
while (endWindowStatsOperatorMap.size() > maxWindowsBehindForStats) {
endWindowStatsOperatorMap.remove(endWindowStatsOperatorMap.firstKey());
}
}
Set<Integer> allCurrentOperators = new TreeSet<Integer>();
for (PTOperator o: plan.getAllOperators()) {
allCurrentOperators.add(o.getId());
}
int numOperators = allCurrentOperators.size();
Long windowId = endWindowStatsOperatorMap.firstKey();
while (windowId != null) {
Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(windowId);
Set<Integer> endWindowStatsOperators = endWindowStatsMap.keySet();
if (allCurrentOperators.containsAll(endWindowStatsOperators)) {
if (endWindowStatsMap.size() < numOperators) {
break;
}
else {
// collected data from all operators for this window id. start latency calculation
List<OperatorMeta> rootOperatorMetas = plan.getRootOperators();
Set<PTOperator> endWindowStatsVisited = new HashSet<PTOperator>();
for (OperatorMeta root: rootOperatorMetas) {
List<PTOperator> rootOperators = plan.getOperators(root);
for (PTOperator rootOperator: rootOperators) {
// DFS for visiting the nodes for latency calculation
calculateLatency(rootOperator, endWindowStatsMap, endWindowStatsVisited);
}
}
endWindowStatsOperatorMap.remove(windowId);
}
}
else {
// the old stats contains operators that do not exist any more
// this is probably right after a partition happens.
endWindowStatsOperatorMap.remove(windowId);
}
windowId = endWindowStatsOperatorMap.higherKey(windowId);
}
}
}
private void calculateLatency(PTOperator oper, Map<Integer, EndWindowStats> endWindowStatsMap, Set<PTOperator> endWindowStatsVisited)
{
endWindowStatsVisited.add(oper);
OperatorStatus operatorStatus = getOperatorStatus(oper);
if (operatorStatus == null) {
LOG.info("Operator status for operator " + oper.getId() + " does not exist yet.");
return;
}
EndWindowStats endWindowStats = endWindowStatsMap.get(oper.getId());
if (endWindowStats == null) {
LOG.info("End window stats is null for operator {}, probably a new operator after partitioning");
return;
}
// find the maximum end window emit time from all input ports
long upstreamMaxEmitTimestamp = -1;
for (PTInput input: oper.inputs) {
if (input.source.source instanceof PTOperator) {
PTOperator upstreamOp = (PTOperator)input.source.source;
EndWindowStats upstreamEndWindowStats = endWindowStatsMap.get(upstreamOp.getId());
if (upstreamEndWindowStats == null) {
LOG.info("End window stats is null for operator {}");
return;
}
if (upstreamEndWindowStats.emitTimestamp > upstreamMaxEmitTimestamp) {
upstreamMaxEmitTimestamp = upstreamEndWindowStats.emitTimestamp;
}
}
}
if (upstreamMaxEmitTimestamp > 0) {
operatorStatus.latencyMA.add(endWindowStats.emitTimestamp - upstreamMaxEmitTimestamp);
}
for (PTOutput output: oper.outputs) {
for (PTInput input: output.sinks) {
if (input.target instanceof PTOperator) {
PTOperator downStreamOp = (PTOperator)input.target;
if (!endWindowStatsVisited.contains(downStreamOp)) {
calculateLatency(downStreamOp, endWindowStatsMap, endWindowStatsVisited);
}
}
}
}
}
private OperatorStatus getOperatorStatus(PTOperator operator)
{
StramChildAgent sca = containers.get(operator.container.containerId);
if (sca == null) {
return null;
}
return sca.operators.get(operator.getId());
}
public int processEvents()
{
int count = 0;
Runnable command;
while ((command = this.eventQueue.poll()) != null) {
try {
command.run();
count++;
}
catch (Exception e) {
// TODO: handle error
LOG.error("Failed to execute " + command, e);
}
}
return count;
}
/**
* Schedule container restart. Called by Stram after a container was terminated
* and requires recovery (killed externally, or after heartbeat timeout). <br>
* Recovery will resolve affected operators (within the container and
* everything downstream with respective recovery checkpoint states).
* Dependent operators will be undeployed and buffer server connections reset prior to
* redeploy to recovery checkpoint.
*
* @param containerId
*/
public void scheduleContainerRestart(String containerId)
{
StramChildAgent cs = getContainerAgent(containerId);
if (cs.shutdownRequested == true) {
return;
}
LOG.info("Initiating recovery for container {}@{}", containerId, cs.container.host);
cs.container.setState(PTContainer.State.KILLED);
cs.container.bufferServerAddress = null;
// building the checkpoint dependency,
// downstream operators will appear first in map
LinkedHashSet<PTOperator> checkpoints = new LinkedHashSet<PTOperator>();
MutableLong ml = new MutableLong();
for (PTOperator node: cs.container.operators) {
// TODO: traverse inline upstream operators
updateRecoveryCheckpoints(node, checkpoints, ml);
}
// redeploy cycle for all affected operators
deploy(Collections.<PTContainer>emptySet(), checkpoints, Sets.newHashSet(cs.container), checkpoints);
}
public void markComplete(String containerId)
{
StramChildAgent cs = containers.get(containerId);
if (cs == null) {
LOG.warn("Completion status for unknown container {}", containerId);
return;
}
cs.isComplete = true;
}
public static class ContainerResource
{
public final String containerId;
public final String host;
public final int memoryMB;
public final int priority;
public ContainerResource(int priority, String containerId, String host, int memoryMB)
{
this.containerId = containerId;
this.host = host;
this.memoryMB = memoryMB;
this.priority = priority;
}
/**
*
* @return String
*/
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("containerId", this.containerId)
.append("host", this.host)
.append("memoryMB", this.memoryMB)
.toString();
}
}
private PTContainer matchContainer(ContainerResource resource)
{
PTContainer match = null;
// match container waiting for resource
for (PTContainer c: plan.getContainers()) {
if (c.getState() == PTContainer.State.NEW || c.getState() == PTContainer.State.KILLED) {
if (c.getResourceRequestPriority() == resource.priority) {
return c;
}
/*
if (container.getRequiredMemoryMB() <= resource.memoryMB) {
if (match == null || match.getRequiredMemoryMB() < container.getRequiredMemoryMB()) {
match = container;
}
}
*/
}
}
return match;
}
/**
* Assign operators to allocated container resource.
*
* @param resource
* @param bufferServerAddr
* @return
*/
public StramChildAgent assignContainer(ContainerResource resource, InetSocketAddress bufferServerAddr)
{
PTContainer container = matchContainer(resource);
if (container == null) {
LOG.debug("No container matching allocated resource {}", resource);
return null;
}
container.setState(PTContainer.State.ALLOCATED);
if (container.containerId != null) {
LOG.info("Removing existing container agent {}", container.containerId);
this.containers.remove(container.containerId);
}
container.containerId = resource.containerId;
container.host = resource.host;
container.bufferServerAddress = bufferServerAddr;
container.setAllocatedMemoryMB(resource.memoryMB);
StramChildAgent sca = new StramChildAgent(container, newStreamingContainerContext());
containers.put(resource.containerId, sca);
return sca;
}
private StreamingContainerContext newStreamingContainerContext()
{
StreamingContainerContext scc = new StreamingContainerContext(attributes);
scc.startWindowMillis = this.windowStartMillis;
return scc;
}
public StramChildAgent getContainerAgent(String containerId)
{
StramChildAgent cs = containers.get(containerId);
if (cs == null) {
throw new AssertionError("Unknown container " + containerId);
}
return cs;
}
public Collection<StramChildAgent> getContainerAgents()
{
return this.containers.values();
}
/**
* process the heartbeat from each container.
* called by the RPC thread for each container. (i.e. called by multiple threads)
*
* @param heartbeat
* @return
*/
public ContainerHeartbeatResponse processHeartbeat(ContainerHeartbeat heartbeat)
{
boolean containerIdle = true;
long currentTimeMillis = System.currentTimeMillis();
StramChildAgent sca = this.containers.get(heartbeat.getContainerId());
if (sca == null) {
// could be orphaned container that was replaced and needs to terminate
LOG.error("Unknown container " + heartbeat.getContainerId());
ContainerHeartbeatResponse response = new ContainerHeartbeatResponse();
response.shutdown = true;
return response;
}
//LOG.debug("{} {} {}", new Object[]{sca.container.containerId, sca.container.bufferServerAddress, sca.container.getState()});
if (sca.container.getState() != PTContainer.State.ACTIVE) {
// capture dynamically assigned address from container
if (sca.container.bufferServerAddress == null && heartbeat.bufferServerHost != null) {
sca.container.bufferServerAddress = InetSocketAddress.createUnresolved(heartbeat.bufferServerHost, heartbeat.bufferServerPort);
LOG.info("Container {} buffer server: {}", sca.container.containerId, sca.container.bufferServerAddress);
}
sca.container.setState(PTContainer.State.ACTIVE);
sca.jvmName = heartbeat.jvmName;
}
if (heartbeat.restartRequested) {
LOG.error("Container {} restart request", sca.container.containerId);
containerStopRequests.put(sca.container.containerId, sca.container.containerId);
}
sca.memoryMBFree = heartbeat.memoryMBFree;
long elapsedMillis = currentTimeMillis - sca.lastHeartbeatMillis;
for (StreamingNodeHeartbeat shb: heartbeat.getDnodeEntries()) {
OperatorStatus status = sca.updateOperatorStatus(shb);
if (status == null) {
LOG.error("Heartbeat for unknown operator {} (container {})", shb.getNodeId(), heartbeat.getContainerId());
continue;
}
//LOG.debug("heartbeat {}/{}@{}: {} {}", new Object[] { shb.getNodeId(), status.operator.getName(), heartbeat.getContainerId(), shb.getState(),
// Codec.getStringWindowId(shb.getLastBackupWindowId()) });
StreamingNodeHeartbeat previousHeartbeat = status.lastHeartbeat;
status.lastHeartbeat = shb;
if (shb.getState().compareTo(DNodeState.FAILED.name()) == 0) {
// count failure transitions *->FAILED, applies to initialization as well as intermittent failures
if (previousHeartbeat == null || DNodeState.FAILED.name().compareTo(previousHeartbeat.getState()) != 0) {
status.operator.failureCount++;
LOG.warn("Operator failure: {} count: {}", status.operator, status.operator.failureCount);
Integer maxAttempts = status.operator.getOperatorMeta().attrValue(OperatorContext.RECOVERY_ATTEMPTS, this.operatorMaxAttemptCount);
if (status.operator.failureCount <= maxAttempts) {
// restart entire container in attempt to recover operator
// in the future a more sophisticated recovery strategy could
// involve initial redeploy attempt(s) of affected operator in
// existing container or sandbox container for just the operator
LOG.error("Issuing container stop to restart after operator failure {}", status.operator);
containerStopRequests.put(sca.container.containerId, sca.container.containerId);
}
else {
String msg = String.format("Shutdown after reaching failure threshold for %s", status.operator);
LOG.warn(msg);
forcedShutdown = true;
shutdownAllContainers(msg);
}
}
}
if (!status.isIdle()) {
containerIdle = false;
long tuplesProcessed = 0;
long tuplesEmitted = 0;
long totalCpuTimeUsed = 0;
long maxDequeueTimestamp = -1;
List<OperatorStats> statsList = shb.getWindowStats();
for (OperatorStats stats: statsList) {
/* report checkpointedWindowId status of the operator */
if (status.operator.recoveryCheckpoint < stats.checkpointedWindowId) {
addCheckpoint(status.operator, stats.checkpointedWindowId);
}
/* report all the other stuff */
// calculate the stats related to end window
EndWindowStats endWindowStats = new EndWindowStats(); // end window stats for a particular window id for a particular node
Collection<PortStats> ports = stats.inputPorts;
if (ports != null) {
for (PortStats s: ports) {
PortStatus ps = status.inputPortStatusList.get(s.portname);
if (ps == null) {
ps = sca.new PortStatus();
ps.portName = s.portname;
status.inputPortStatusList.put(s.portname, ps);
}
ps.totalTuples += s.processedCount;
tuplesProcessed += s.processedCount;
endWindowStats.dequeueTimestamps.put(s.portname, s.endWindowTimestamp);
Pair<Integer, String> operatorPortName = new Pair<Integer, String>(status.operator.getId(), s.portname);
if (lastEndWindowTimestamps.containsKey(operatorPortName)) {
ps.tuplesPSMA10.add(s.processedCount * 1000 / (s.endWindowTimestamp - lastEndWindowTimestamps.get(operatorPortName)));
}
lastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp);
if (s.endWindowTimestamp > maxDequeueTimestamp) {
maxDequeueTimestamp = s.endWindowTimestamp;
}
}
}
ports = stats.outputPorts;
if (ports != null) {
for (PortStats s: ports) {
PortStatus ps = status.outputPortStatusList.get(s.portname);
if (ps == null) {
ps = sca.new PortStatus();
ps.portName = s.portname;
status.outputPortStatusList.put(s.portname, ps);
}
ps.totalTuples += s.processedCount;
tuplesEmitted += s.processedCount;
Pair<Integer, String> operatorPortName = new Pair<Integer, String>(status.operator.getId(), s.portname);
// the second condition is needed when
// 1) the operator is redeployed and is playing back the tuples, or
// 2) the operator is catching up very fast and the endWindowTimestamp of subsequent windows is less than one millisecond
if (lastEndWindowTimestamps.containsKey(operatorPortName) &&
(s.endWindowTimestamp > lastEndWindowTimestamps.get(operatorPortName))) {
ps.tuplesPSMA10.add(s.processedCount * 1000 / (s.endWindowTimestamp - lastEndWindowTimestamps.get(operatorPortName)));
}
lastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp);
}
if (ports.size() > 0) {
endWindowStats.emitTimestamp = ports.iterator().next().endWindowTimestamp;
}
}
// for output operator, just take the maximum dequeue time for emit timestamp.
// (we don't know the latency for output operators because they don't emit tuples)
if (endWindowStats.emitTimestamp < 0) {
endWindowStats.emitTimestamp = maxDequeueTimestamp;
}
status.currentWindowId = stats.windowId;
totalCpuTimeUsed += stats.cpuTimeUsed;
Map<Integer, EndWindowStats> endWindowStatsMap = endWindowStatsOperatorMap.get(stats.windowId);
if (endWindowStatsMap == null) {
endWindowStatsOperatorMap.putIfAbsent(stats.windowId, new ConcurrentHashMap<Integer, EndWindowStats>());
endWindowStatsMap = endWindowStatsOperatorMap.get(stats.windowId);
}
endWindowStatsMap.put(shb.getNodeId(), endWindowStats);
}
status.totalTuplesProcessed += tuplesProcessed;
status.totalTuplesEmitted += tuplesEmitted;
if (elapsedMillis > 0) {
//status.tuplesProcessedPSMA10.add((tuplesProcessed * 1000) / elapsedMillis);
//status.tuplesEmittedPSMA10.add((tuplesEmitted * 1000) / elapsedMillis);
status.tuplesProcessedPSMA10 = 0;
status.tuplesEmittedPSMA10 = 0;
status.cpuPercentageMA10.add((double)totalCpuTimeUsed * 100 / (elapsedMillis * 1000000));
for (PortStatus ps: status.inputPortStatusList.values()) {
Long numBytes = shb.getBufferServerBytes().get(ps.portName);
if (numBytes != null) {
ps.bufferServerBytesPSMA10.add(numBytes * 1000 / elapsedMillis);
}
status.tuplesProcessedPSMA10 += ps.tuplesPSMA10.getAvg();
}
for (PortStatus ps: status.outputPortStatusList.values()) {
Long numBytes = shb.getBufferServerBytes().get(ps.portName);
if (numBytes != null) {
ps.bufferServerBytesPSMA10.add(numBytes * 1000 / elapsedMillis);
}
status.tuplesEmittedPSMA10 += ps.tuplesPSMA10.getAvg();
}
if (status.operator.statsMonitors != null) {
long tps = status.operator.inputs.isEmpty() ? status.tuplesEmittedPSMA10 : status.tuplesProcessedPSMA10;
for (StatsHandler sm: status.operator.statsMonitors) {
sm.onThroughputUpdate(status.operator, tps);
sm.onCpuPercentageUpdate(status.operator, status.cpuPercentageMA10.getAvg());
}
}
}
}
status.recordingNames = shb.getRecordingNames();
}
sca.lastHeartbeatMillis = currentTimeMillis;
ContainerHeartbeatResponse rsp = sca.pollRequest();
if (rsp == null) {
rsp = new ContainerHeartbeatResponse();
}
// below should be merged into pollRequest
if (containerIdle && isApplicationIdle()) {
LOG.info("requesting idle shutdown for container {}", heartbeat.getContainerId());
rsp.shutdown = true;
}
else {
if (sca.shutdownRequested) {
LOG.info("requesting shutdown for container {}", heartbeat.getContainerId());
rsp.shutdown = true;
}
}
List<StramToNodeRequest> requests = rsp.nodeRequests != null ? rsp.nodeRequests : new ArrayList<StramToNodeRequest>();
ConcurrentLinkedQueue<StramToNodeRequest> operatorRequests = sca.getOperatorRequests();
while (true) {
StramToNodeRequest r = operatorRequests.poll();
if (r == null) {
break;
}
requests.add(r);
}
rsp.nodeRequests = requests;
rsp.committedWindowId = committedWindowId;
return rsp;
}
private boolean isApplicationIdle()
{
for (StramChildAgent csa: this.containers.values()) {
if (!csa.isIdle()) {
return false;
}
}
return true;
}
void addCheckpoint(PTOperator node, long backupWindowId)
{
synchronized (node.checkpointWindows) {
if (!node.checkpointWindows.isEmpty()) {
Long lastCheckpoint = node.checkpointWindows.getLast();
// skip unless checkpoint moves
if (lastCheckpoint.longValue() != backupWindowId) {
if (lastCheckpoint.longValue() > backupWindowId) {
// list needs to have max windowId last
LOG.warn("Out of sequence checkpoint {} last {} (operator {})", new Object[] {backupWindowId, lastCheckpoint, node});
ListIterator<Long> li = node.checkpointWindows.listIterator();
while (li.hasNext() && li.next().longValue() < backupWindowId) {
continue;
}
if (li.previous() != backupWindowId) {
li.add(backupWindowId);
}
}
else {
node.checkpointWindows.add(backupWindowId);
}
}
}
else {
node.checkpointWindows.add(backupWindowId);
}
}
}
/**
* Compute checkpoints required for a given operator instance to be recovered.
* This is done by looking at checkpoints available for downstream dependencies first,
* and then selecting the most recent available checkpoint that is smaller than downstream.
*
* @param operator Operator instance for which to find recovery checkpoint
* @param visited Set into which to collect visited dependencies
* @param committedWindowId
* @return Checkpoint that can be used to recover (along with dependencies in visitedCheckpoints).
*/
public long updateRecoveryCheckpoints(PTOperator operator, Set<PTOperator> visited, MutableLong committedWindowId)
{
if (operator.recoveryCheckpoint < committedWindowId.longValue()) {
committedWindowId.setValue(operator.recoveryCheckpoint);
}
// checkpoint frozen until deployment complete
if (operator.getState() == State.PENDING_DEPLOY) {
return operator.recoveryCheckpoint;
}
long maxCheckpoint = operator.getRecentCheckpoint();
// find smallest of most recent subscriber checkpoints
for (PTOutput out: operator.outputs) {
for (PhysicalPlan.PTInput sink: out.sinks) {
PTOperator sinkOperator = (PTOperator)sink.target;
if (!visited.contains(sinkOperator)) {
// downstream traversal
updateRecoveryCheckpoints(sinkOperator, visited, committedWindowId);
}
// recovery window id cannot move backwards
// when dynamically adding new operators
if (sinkOperator.recoveryCheckpoint >= operator.recoveryCheckpoint) {
maxCheckpoint = Math.min(maxCheckpoint, sinkOperator.recoveryCheckpoint);
}
}
}
// find commit point for downstream dependency, remove previous checkpoints
long c1 = 0;
synchronized (operator.checkpointWindows) {
if (!operator.checkpointWindows.isEmpty()) {
if ((c1 = operator.checkpointWindows.getFirst().longValue()) <= maxCheckpoint) {
long c2 = 0;
while (operator.checkpointWindows.size() > 1 && (c2 = operator.checkpointWindows.get(1).longValue()) <= maxCheckpoint) {
operator.checkpointWindows.removeFirst();
//LOG.debug("Checkpoint to delete: operator={} windowId={}", operator.getName(), c1);
this.purgeCheckpoints.add(new Pair<PTOperator, Long>(operator, c1));
c1 = c2;
}
}
else {
c1 = 0;
}
}
}
visited.add(operator);
//LOG.debug("Operator {} checkpoints: commit {} recent {}", new Object[] {operator.getName(), c1, operator.checkpointWindows});
return operator.recoveryCheckpoint = c1;
}
/**
* Visit all operators to update current checkpoint based on updated downstream state.
* Purge older checkpoints that are no longer needed.
*/
private long updateCheckpoints()
{
MutableLong lCommittedWindowId = new MutableLong(Long.MAX_VALUE);
Set<PTOperator> visitedCheckpoints = new LinkedHashSet<PTOperator>();
for (OperatorMeta logicalOperator: plan.getRootOperators()) {
List<PTOperator> operators = plan.getOperators(logicalOperator);
if (operators != null) {
for (PTOperator operator: operators) {
updateRecoveryCheckpoints(operator, visitedCheckpoints, lCommittedWindowId);
}
}
}
purgeCheckpoints();
return lCommittedWindowId.longValue();
}
private BufferServerController getBufferServerClient(PTOperator operator)
{
BufferServerController bsc = new BufferServerController(operator.getLogicalId());
InetSocketAddress address = operator.container.bufferServerAddress;
StramChild.eventloop.connect(address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address, bsc);
return bsc;
}
private void purgeCheckpoints()
{
StorageAgent ba = new HdfsStorageAgent(new Configuration(), checkpointFsPath);
for (Pair<PTOperator, Long> p: purgeCheckpoints) {
PTOperator operator = p.getFirst();
try {
ba.delete(operator.getId(), p.getSecond());
}
catch (Exception e) {
LOG.error("Failed to purge checkpoint " + p, e);
}
// delete stream state when using buffer server
for (PTOutput out: operator.outputs) {
if (!out.isDownStreamInline()) {
// following needs to match the concat logic in StramChild
String sourceIdentifier = Integer.toString(operator.getId()).concat(StramChild.NODE_PORT_CONCAT_SEPARATOR).concat(out.portName);
// delete everything from buffer server prior to new checkpoint
BufferServerController bsc = getBufferServerClient(operator);
try {
bsc.purge(null, sourceIdentifier, operator.checkpointWindows.getFirst() - 1);
}
catch (Throwable t) {
LOG.error("Failed to purge " + bsc.addr + " " + sourceIdentifier, t);
}
}
}
}
purgeCheckpoints.clear();
}
/**
* Mark all containers for shutdown, next container heartbeat response
* will propagate the shutdown request. This is controlled soft shutdown.
* If containers don't respond, the application can be forcefully terminated
* via yarn using forceKillApplication.
*
* @param message
*/
public void shutdownAllContainers(String message)
{
this.shutdownDiagnosticsMessage = message;
LOG.info("Initiating application shutdown: " + message);
for (StramChildAgent cs: this.containers.values()) {
cs.shutdownRequested = true;
}
}
@Override
public StorageAgent getStorageAgent()
{
return new HdfsStorageAgent(new Configuration(), this.checkpointFsPath);
}
private Map<PTContainer, List<PTOperator>> groupByContainer(Collection<PTOperator> operators)
{
Map<PTContainer, List<PTOperator>> m = new HashMap<PTContainer, List<PTOperator>>();
for (PTOperator node: operators) {
List<PTOperator> nodes = m.get(node.container);
if (nodes == null) {
nodes = new ArrayList<PhysicalPlan.PTOperator>();
m.put(node.container, nodes);
}
nodes.add(node);
}
return m;
}
@Override
public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy)
{
Map<PTContainer, List<PTOperator>> undeployGroups = groupByContainer(undeploy);
// stop affected operators (exclude new/failed containers)
// order does not matter, remove all operators in each container in one sweep
for (Map.Entry<PTContainer, List<PTOperator>> e: undeployGroups.entrySet()) {
if (!startContainers.contains(e.getKey()) && !releaseContainers.contains(e.getKey())) {
e.getKey().pendingUndeploy.addAll(e.getValue());
}
}
// start new containers
for (PTContainer c: startContainers) {
ContainerStartRequest dr = new ContainerStartRequest(c);
containerStartRequests.add(dr);
lastResourceRequest = System.currentTimeMillis();
for (PTOperator operator: c.operators) {
operator.setState(PTOperator.State.INACTIVE);
}
}
// (re)deploy affected operators
// can happen in parallel after buffer server state for recovered publishers is reset
Map<PTContainer, List<PTOperator>> deployGroups = groupByContainer(deploy);
for (Map.Entry<PTContainer, List<PTOperator>> e: deployGroups.entrySet()) {
if (!startContainers.contains(e.getKey())) {
// to reset publishers, clean buffer server past checkpoint so subscribers don't read stale data (including end of stream)
for (PTOperator operator: e.getValue()) {
for (PTOutput out: operator.outputs) {
if (!out.isDownStreamInline()) {
// following needs to match the concat logic in StramChild
String sourceIdentifier = Integer.toString(operator.getId()).concat(StramChild.NODE_PORT_CONCAT_SEPARATOR).concat(out.portName);
// TODO: find way to mock this when testing rest of logic
if (operator.container.bufferServerAddress.getPort() != 0) {
BufferServerController bsc = getBufferServerClient(operator);
// reset publisher (stale operator may still write data until disconnected)
// ensures new subscriber starting to read from checkpoint will wait until publisher redeploy cycle is complete
try {
bsc.reset(null, sourceIdentifier, 0);
}
catch (Exception ex) {
LOG.error("Failed to reset buffer server {} {}", sourceIdentifier, ex);
}
}
}
}
}
}
// add to operators that we expect to deploy
LOG.debug("scheduling deploy {} {}", e.getKey(), e.getValue());
e.getKey().pendingDeploy.addAll(e.getValue());
}
// stop containers that are no longer used
for (PTContainer c: releaseContainers) {
StramChildAgent sca = containers.get(c.containerId);
if (sca != null) {
LOG.debug("Container marked for shutdown: {}", c);
// TODO: set deactivated state and monitor soft shutdown
sca.shutdownRequested = true;
}
}
}
@Override
public void dispatch(Runnable r)
{
this.eventQueue.add(r);
}
public OperatorInfo getOperatorInfo(String operatorId)
{
for (PTContainer container: this.plan.getContainers()) {
String containerId = container.containerId;
StramChildAgent sca = containerId != null ? this.containers.get(container.containerId) : null;
for (PTOperator operator: container.operators) {
if (operatorId.equals(Integer.toString(operator.getId()))) {
OperatorStatus os = (sca != null) ? sca.operators.get(operator.getId()) : null;
return fillOperatorInfo(operator, os);
}
}
}
return null;
}
public ArrayList<OperatorInfo> getOperatorInfoList()
{
ArrayList<OperatorInfo> infoList = new ArrayList<OperatorInfo>();
for (PTContainer container: this.plan.getContainers()) {
String containerId = container.containerId;
StramChildAgent sca = containerId != null ? this.containers.get(container.containerId) : null;
for (PTOperator operator: container.operators) {
OperatorStatus os = (sca != null) ? sca.operators.get(operator.getId()) : null;
infoList.add(fillOperatorInfo(operator, os));
}
}
return infoList;
}
private OperatorInfo fillOperatorInfo(PTOperator operator, OperatorStatus os)
{
OperatorInfo ni = new OperatorInfo();
ni.container = operator.container.containerId;
ni.host = operator.container.host;
ni.id = Integer.toString(operator.getId());
ni.name = operator.getName();
ni.className = operator.getOperatorMeta().getOperator().getClass().getName();
ni.status = operator.getState().toString();
if (os != null) {
ni.totalTuplesProcessed = os.totalTuplesProcessed;
ni.totalTuplesEmitted = os.totalTuplesEmitted;
ni.tuplesProcessedPSMA10 = os.tuplesProcessedPSMA10;
ni.tuplesEmittedPSMA10 = os.tuplesEmittedPSMA10;
ni.cpuPercentageMA10 = os.cpuPercentageMA10.getAvg();
ni.latencyMA = os.latencyMA.getAvg();
ni.failureCount = os.operator.failureCount;
ni.recoveryWindowId = os.operator.recoveryCheckpoint;
ni.currentWindowId = os.currentWindowId;
ni.recordingNames = os.recordingNames;
if (os.lastHeartbeat != null) {
ni.lastHeartbeat = os.lastHeartbeat.getGeneratedTms();
}
for (PortStatus ps: os.inputPortStatusList.values()) {
PortInfo pinfo = new PortInfo();
pinfo.name = ps.portName;
pinfo.type = "input";
pinfo.totalTuples = ps.totalTuples;
pinfo.tuplesPSMA10 = ps.tuplesPSMA10.getAvg();
pinfo.bufferServerBytesPSMA10 = ps.bufferServerBytesPSMA10.getAvg();
ni.addInputPort(pinfo);
}
for (PortStatus ps: os.outputPortStatusList.values()) {
PortInfo pinfo = new PortInfo();
pinfo.name = ps.portName;
pinfo.type = "output";
pinfo.totalTuples = ps.totalTuples;
pinfo.tuplesPSMA10 = ps.tuplesPSMA10.getAvg();
pinfo.bufferServerBytesPSMA10 = ps.bufferServerBytesPSMA10.getAvg();
ni.addOutputPort(pinfo);
}
}
return ni;
}
private static class RecordingRequestFilter implements Predicate<StramToNodeRequest>
{
final static Set<StramToNodeRequest.RequestType> MATCH_TYPES = Sets.newHashSet(RequestType.START_RECORDING, RequestType.STOP_RECORDING, RequestType.SYNC_RECORDING);
@Override
public boolean apply(@Nullable StramToNodeRequest input)
{
return MATCH_TYPES.contains(input.getRequestType());
}
}
private class SetOperatorPropertyRequestFilter implements Predicate<StramToNodeRequest>
{
final String propertyKey;
SetOperatorPropertyRequestFilter(String key)
{
this.propertyKey = key;
}
@Override
public boolean apply(@Nullable StramToNodeRequest input)
{
return input.getRequestType() == RequestType.SET_PROPERTY && input.setPropertyKey.equals(propertyKey);
}
}
private void updateOnDeployRequests(PTOperator p, Predicate<StramToNodeRequest> superseded, StramToNodeRequest newRequest)
{
// filter existing requests
List<StramToNodeRequest> cloneRequests = new ArrayList<StramToNodeRequest>(p.deployRequests.size());
for (StramToNodeRequest existingRequest: p.deployRequests) {
if (!superseded.apply(existingRequest)) {
cloneRequests.add(existingRequest);
}
}
// add new request, if any
if (newRequest != null) {
cloneRequests.add(newRequest);
}
p.deployRequests = Collections.unmodifiableList(cloneRequests);
}
private StramChildAgent getContainerAgentFromOperatorId(int operatorId)
{
// Thomas, please change it when you get a chance. -- David
for (StramChildAgent container: containers.values()) {
if (container.operators.containsKey(operatorId)) {
return container;
}
}
// throw exception that propagates to web client
throw new NotFoundException("Operator ID " + operatorId + " not found");
}
public void startRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.START_RECORDING);
sca.addOperatorRequest(request);
OperatorStatus os = sca.operators.get(operId);
if (os != null) {
// restart on deploy
updateOnDeployRequests(os.operator, new RecordingRequestFilter(), request);
}
}
public void stopRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.STOP_RECORDING);
sca.addOperatorRequest(request);
OperatorStatus os = sca.operators.get(operId);
if (os != null) {
// no stop on deploy, but remove existing start
updateOnDeployRequests(os.operator, new RecordingRequestFilter(), null);
}
}
public void syncRecording(int operId, String portName)
{
StramChildAgent sca = getContainerAgentFromOperatorId(operId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(operId);
if (!StringUtils.isBlank(portName)) {
request.setPortName(portName);
}
request.setRequestType(RequestType.SYNC_RECORDING);
sca.addOperatorRequest(request);
}
public void stopContainer(String containerId)
{
this.containerStopRequests.put(containerId, containerId);
}
public void setOperatorProperty(String operatorId, String propertyName, String propertyValue)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
Map<String, String> properties = Collections.singletonMap(propertyName, propertyValue);
DAGPropertiesBuilder.setOperatorProperties(logicalOperator.getOperator(), properties);
// need to record this to a log in the future when review history is supported
List<PTOperator> operators = plan.getOperators(logicalOperator);
for (PTOperator o: operators) {
StramChildAgent sca = getContainerAgent(o.getContainer().containerId);
StramToNodeRequest request = new StramToNodeRequest();
request.setOperatorId(o.getId());
request.setPropertyKey = propertyName;
request.setPropertyValue = propertyValue;
request.setRequestType(RequestType.SET_PROPERTY);
sca.addOperatorRequest(request);
// restart on deploy
updateOnDeployRequests(o, new SetOperatorPropertyRequestFilter(propertyName), request);
}
}
public Map<String, Object> getApplicationAttributes()
{
LogicalPlan lp = getLogicalPlan();
return lp.getAttributes().valueMap();
}
public Map<String, Object> getOperatorAttributes(String operatorId)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
return logicalOperator.getAttributes().valueMap();
}
public Map<String, Object> getPortAttributes(String operatorId, String portName)
{
OperatorMeta logicalOperator = plan.getDAG().getOperatorMeta(operatorId);
if (logicalOperator == null) {
throw new IllegalArgumentException("Invalid operatorId " + operatorId);
}
Operators.PortMappingDescriptor portMap = new Operators.PortMappingDescriptor();
Operators.describe(logicalOperator.getOperator(), portMap);
InputPort<?> inputPort = portMap.inputPorts.get(portName);
if (inputPort != null) {
return logicalOperator.getMeta(inputPort).getAttributes().valueMap();
} else {
OutputPort<?> outputPort = portMap.outputPorts.get(portName);
if (outputPort == null) {
throw new IllegalArgumentException("Invalid port name " + portName);
}
return logicalOperator.getMeta(outputPort).getAttributes().valueMap();
}
}
public LogicalPlan getLogicalPlan()
{
return plan.getDAG();
}
/**
* Asynchronously process the logical, physical plan and execution layer changes.
* Caller can use the returned future to block until processing is complete.
* @param requests
* @return
* @throws Exception
*/
public FutureTask<Object> logicalPlanModification(List<LogicalPlanRequest> requests) throws Exception
{
// delegate processing to dispatch thread
FutureTask<Object> future = new FutureTask<Object>(new LogicalPlanChangeRunnable(requests));
dispatch(future);
//LOG.info("Scheduled plan changes: {}", requests);
return future;
}
private class LogicalPlanChangeRunnable implements java.util.concurrent.Callable<Object> {
final List<LogicalPlanRequest> requests;
private LogicalPlanChangeRunnable(List<LogicalPlanRequest> requests)
{
this.requests = requests;
}
@Override
public Object call() throws Exception {
// clone logical plan, for dry run and validation
LOG.info("Begin plan changes: {}", requests);
LogicalPlan lp = plan.getDAG();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
LogicalPlan.write(lp, bos);
bos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
lp = LogicalPlan.read(bis);
PlanModifier pm = new PlanModifier(lp);
for (LogicalPlanRequest request : requests) {
LOG.debug("Dry run plan change: {}", request);
request.execute(pm);
}
lp.validate();
// perform changes on live plan
pm = new PlanModifier(plan);
for (LogicalPlanRequest request : requests) {
request.execute(pm);
}
pm.applyChanges(StreamingContainerManager.this);
LOG.info("Plan changes applied: {}", requests);
return null;
}
}
}
| fixed division by zero in throughput calculation
| engine/src/main/java/com/datatorrent/stram/StreamingContainerManager.java | fixed division by zero in throughput calculation | <ide><path>ngine/src/main/java/com/datatorrent/stram/StreamingContainerManager.java
<ide> endWindowStats.dequeueTimestamps.put(s.portname, s.endWindowTimestamp);
<ide>
<ide> Pair<Integer, String> operatorPortName = new Pair<Integer, String>(status.operator.getId(), s.portname);
<del> if (lastEndWindowTimestamps.containsKey(operatorPortName)) {
<add> if (lastEndWindowTimestamps.containsKey(operatorPortName) && (s.endWindowTimestamp > lastEndWindowTimestamps.get(operatorPortName))) {
<ide> ps.tuplesPSMA10.add(s.processedCount * 1000 / (s.endWindowTimestamp - lastEndWindowTimestamps.get(operatorPortName)));
<ide> }
<ide> lastEndWindowTimestamps.put(operatorPortName, s.endWindowTimestamp); |
|
Java | apache-2.0 | 05f73d037f54dd4324e3ddbada857f25d09b4e64 | 0 | uronce-cc/alluxio,Reidddddd/mo-alluxio,WilliamZapata/alluxio,Alluxio/alluxio,riversand963/alluxio,maobaolong/alluxio,ShailShah/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,Reidddddd/mo-alluxio,maboelhassan/alluxio,madanadit/alluxio,wwjiang007/alluxio,calvinjia/tachyon,maboelhassan/alluxio,aaudiber/alluxio,calvinjia/tachyon,jsimsa/alluxio,yuluo-ding/alluxio,jswudi/alluxio,jswudi/alluxio,maobaolong/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,ShailShah/alluxio,maobaolong/alluxio,apc999/alluxio,riversand963/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,uronce-cc/alluxio,uronce-cc/alluxio,PasaLab/tachyon,Reidddddd/alluxio,wwjiang007/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,yuluo-ding/alluxio,apc999/alluxio,wwjiang007/alluxio,riversand963/alluxio,riversand963/alluxio,aaudiber/alluxio,wwjiang007/alluxio,ShailShah/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,WilliamZapata/alluxio,madanadit/alluxio,jsimsa/alluxio,maboelhassan/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,apc999/alluxio,Alluxio/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,bf8086/alluxio,madanadit/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,jsimsa/alluxio,ShailShah/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,Alluxio/alluxio,ShailShah/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,jsimsa/alluxio,Reidddddd/alluxio,PasaLab/tachyon,Alluxio/alluxio,ShailShah/alluxio,riversand963/alluxio,madanadit/alluxio,Reidddddd/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,maobaolong/alluxio,aaudiber/alluxio,calvinjia/tachyon,wwjiang007/alluxio,uronce-cc/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,WilliamZapata/alluxio,jswudi/alluxio,PasaLab/tachyon,bf8086/alluxio,jswudi/alluxio,bf8086/alluxio,madanadit/alluxio,maobaolong/alluxio,jswudi/alluxio,bf8086/alluxio,bf8086/alluxio,madanadit/alluxio,Alluxio/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,jsimsa/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,PasaLab/tachyon,wwjiang007/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,jsimsa/alluxio,jswudi/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,bf8086/alluxio,Alluxio/alluxio,madanadit/alluxio,maboelhassan/alluxio,apc999/alluxio,aaudiber/alluxio,bf8086/alluxio,calvinjia/tachyon,Reidddddd/alluxio,PasaLab/tachyon,Alluxio/alluxio,riversand963/alluxio,PasaLab/tachyon,Alluxio/alluxio,yuluo-ding/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.RuntimeConstants;
import alluxio.Server;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.FileSystemMaster;
import alluxio.master.journal.ReadWriteJournal;
import alluxio.master.lineage.LineageMaster;
import alluxio.metrics.MetricsSystem;
import alluxio.metrics.sink.MetricsServlet;
import alluxio.security.authentication.TransportProvider;
import alluxio.underfs.UnderFileSystem;
import alluxio.util.CommonUtils;
import alluxio.util.ConfigurationUtils;
import alluxio.util.LineageUtils;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.util.network.NetworkAddressUtils.ServiceType;
import alluxio.web.MasterUIWebServer;
import alluxio.web.UIWebServer;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;
/**
* Entry point for the Alluxio master program.
*/
@NotThreadSafe
public class AlluxioMaster implements Server {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
/**
* Starts the Alluxio master.
*
* @param args command line arguments, should be empty
*/
public static void main(String[] args) {
if (args.length != 0) {
LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR,
AlluxioMaster.class.getCanonicalName());
System.exit(-1);
}
// validate the configuration
if (!ConfigurationUtils.validateConf()) {
LOG.error("Invalid configuration found");
System.exit(-1);
}
AlluxioMaster master = Factory.create();
try {
master.start();
} catch (Exception e) {
LOG.error("Uncaught exception while running Alluxio master, stopping it and exiting.", e);
try {
master.stop();
} catch (Exception e2) {
// continue to exit
LOG.error("Uncaught exception while stopping Alluxio master, simply exiting.", e2);
}
System.exit(-1);
}
}
/** Maximum number of threads to serve the rpc server. */
private final int mMaxWorkerThreads;
/** Minimum number of threads to serve the rpc server. */
private final int mMinWorkerThreads;
/** The port for the RPC server. */
private final int mPort;
/** The socket for thrift rpc server. */
private final TServerSocket mTServerSocket;
/** The transport provider to create thrift server transport. */
private final TransportProvider mTransportProvider;
/** The address for the rpc server. */
private final InetSocketAddress mMasterAddress;
private final MetricsServlet mMetricsServlet = new MetricsServlet(MetricsSystem.METRIC_REGISTRY);
/** The master managing all block metadata. */
protected BlockMaster mBlockMaster;
/** The master managing all file system related metadata. */
protected FileSystemMaster mFileSystemMaster;
/** The master managing all lineage related metadata. */
protected LineageMaster mLineageMaster;
/** A list of extra masters to launch based on service loader. */
protected List<Master> mAdditionalMasters;
/** The journal for the block master. */
protected final ReadWriteJournal mBlockMasterJournal;
/** The journal for the file system master. */
protected final ReadWriteJournal mFileSystemMasterJournal;
/** The journal for the lineage master. */
protected final ReadWriteJournal mLineageMasterJournal;
/** The web ui server. */
private UIWebServer mWebServer = null;
/** The RPC server. */
private TServer mMasterServiceServer = null;
/** is true if the master is serving the RPC server. */
private boolean mIsServing = false;
/** The start time for when the master started serving the RPC server. */
private long mStartTimeMs = -1;
/** The master services' names. */
private static List<String> sServiceNames;
/** The master service loaders. */
private static ServiceLoader<MasterFactory> sServiceLoader;
/**
* @return the (cached) master service loader
*/
private static ServiceLoader<MasterFactory> getServiceLoader() {
if (sServiceLoader != null) {
return sServiceLoader;
}
// Discover and register the available factories.
// NOTE: ClassLoader is explicitly specified so we don't need to set ContextClassLoader.
sServiceLoader = ServiceLoader.load(MasterFactory.class, MasterFactory.class.getClassLoader());
return sServiceLoader;
}
/**
* @return the (cached) list of the enabled master services' names
*/
public static List<String> getServiceNames() {
if (sServiceNames != null) {
return sServiceNames;
}
sServiceNames = new ArrayList<>();
sServiceNames.add(Constants.BLOCK_MASTER_NAME);
sServiceNames.add(Constants.FILE_SYSTEM_MASTER_NAME);
sServiceNames.add(Constants.LINEAGE_MASTER_NAME);
for (MasterFactory factory : getServiceLoader()) {
if (factory.isEnabled()) {
sServiceNames.add(factory.getName());
}
}
return sServiceNames;
}
/**
* Factory for creating {@link AlluxioMaster} or {@link FaultTolerantAlluxioMaster} based on
* {@link Configuration}.
*/
@ThreadSafe
public static final class Factory {
/**
* @return {@link FaultTolerantAlluxioMaster} if Alluxio configuration is set to use zookeeper,
* otherwise, return {@link AlluxioMaster}.
*/
public static AlluxioMaster create() {
if (Configuration.getBoolean(PropertyKey.ZOOKEEPER_ENABLED)) {
return new FaultTolerantAlluxioMaster();
}
return new AlluxioMaster();
}
private Factory() {} // prevent instantiation.
}
protected AlluxioMaster() {
mMinWorkerThreads = Configuration.getInt(PropertyKey.MASTER_WORKER_THREADS_MIN);
mMaxWorkerThreads = Configuration.getInt(PropertyKey.MASTER_WORKER_THREADS_MAX);
Preconditions.checkArgument(mMaxWorkerThreads >= mMinWorkerThreads,
PropertyKey.MASTER_WORKER_THREADS_MAX + " can not be less than "
+ PropertyKey.MASTER_WORKER_THREADS_MIN);
try {
// Extract the port from the generated socket.
// When running tests, it is fine to use port '0' so the system will figure out what port to
// use (any random free port).
// In a production or any real deployment setup, port '0' should not be used as it will make
// deployment more complicated.
if (!Configuration.getBoolean(PropertyKey.TEST_MODE)) {
Preconditions.checkState(Configuration.getInt(PropertyKey.MASTER_RPC_PORT) > 0,
"Alluxio master rpc port is only allowed to be zero in test mode.");
Preconditions.checkState(Configuration.getInt(PropertyKey.MASTER_WEB_PORT) > 0,
"Alluxio master web port is only allowed to be zero in test mode.");
}
mTransportProvider = TransportProvider.Factory.create();
mTServerSocket =
new TServerSocket(NetworkAddressUtils.getBindAddress(ServiceType.MASTER_RPC));
mPort = NetworkAddressUtils.getThriftPort(mTServerSocket);
// reset master rpc port
Configuration.set(PropertyKey.MASTER_RPC_PORT, Integer.toString(mPort));
mMasterAddress = NetworkAddressUtils.getConnectAddress(ServiceType.MASTER_RPC);
// Check the journal directory
String journalDirectory = Configuration.get(PropertyKey.MASTER_JOURNAL_FOLDER);
if (!journalDirectory.endsWith(AlluxioURI.SEPARATOR)) {
journalDirectory += AlluxioURI.SEPARATOR;
}
Preconditions.checkState(isJournalFormatted(journalDirectory),
"Alluxio master was not formatted! The journal folder is " + journalDirectory);
// Create the journals.
mBlockMasterJournal = new ReadWriteJournal(BlockMaster.getJournalDirectory(journalDirectory));
mFileSystemMasterJournal =
new ReadWriteJournal(FileSystemMaster.getJournalDirectory(journalDirectory));
mLineageMasterJournal =
new ReadWriteJournal(LineageMaster.getJournalDirectory(journalDirectory));
mBlockMaster = new BlockMaster(mBlockMasterJournal);
mFileSystemMaster = new FileSystemMaster(mBlockMaster, mFileSystemMasterJournal);
if (LineageUtils.isLineageEnabled()) {
mLineageMaster = new LineageMaster(mFileSystemMaster, mLineageMasterJournal);
}
mAdditionalMasters = new ArrayList<>();
List<? extends Master> masters = Lists.newArrayList(mBlockMaster, mFileSystemMaster);
for (MasterFactory factory : getServiceLoader()) {
Master master = factory.create(masters, journalDirectory);
if (master != null) {
mAdditionalMasters.add(master);
}
}
// The web server needs to be created at the end of the constructor because it needs a
// reference to this class.
mWebServer = new MasterUIWebServer(ServiceType.MASTER_WEB.getServiceName(),
NetworkAddressUtils.getBindAddress(ServiceType.MASTER_WEB), this);
// reset master web port
Configuration.set(PropertyKey.MASTER_WEB_PORT, Integer.toString(mWebServer.getLocalPort()));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
/**
* @return the externally resolvable address of this master
*/
public InetSocketAddress getMasterAddress() {
return mMasterAddress;
}
/**
* @return the actual bind hostname on RPC service (used by unit test only)
*/
public String getRPCBindHost() {
return NetworkAddressUtils.getThriftSocket(mTServerSocket).getInetAddress().getHostAddress();
}
/**
* @return the actual port that the RPC service is listening on (used by unit test only)
*/
public int getRPCLocalPort() {
return mPort;
}
/**
* @return the actual bind hostname on web service (used by unit test only)
*/
public String getWebBindHost() {
if (mWebServer != null) {
return mWebServer.getBindHost();
}
return "";
}
/**
* @return the actual port that the web service is listening on (used by unit test only)
*/
public int getWebLocalPort() {
if (mWebServer != null) {
return mWebServer.getLocalPort();
}
return -1;
}
/**
* @return internal {@link BlockMaster}
*/
public BlockMaster getBlockMaster() {
return mBlockMaster;
}
/**
* @return other additional {@link Master}s
*/
public List<Master> getAdditionalMasters() {
return Collections.unmodifiableList(mAdditionalMasters);
}
/**
* @return internal {@link FileSystemMaster}
*/
public FileSystemMaster getFileSystemMaster() {
return mFileSystemMaster;
}
/**
* @return internal {@link LineageMaster}
*/
public LineageMaster getLineageMaster() {
return mLineageMaster;
}
/**
* @return the start time of the master in milliseconds
*/
public long getStartTimeMs() {
return mStartTimeMs;
}
/**
* @return the uptime of the master in milliseconds
*/
public long getUptimeMs() {
return System.currentTimeMillis() - mStartTimeMs;
}
/**
* @return true if the system is the leader (serving the rpc server), false otherwise
*/
boolean isServing() {
return mIsServing;
}
@Override
public void start() throws Exception {
startMasters(true);
startServing();
}
@Override
public void stop() throws Exception {
if (mIsServing) {
LOG.info("Stopping RPC server on Alluxio master @ {}", mMasterAddress);
stopServing();
stopMasters();
mTServerSocket.close();
mIsServing = false;
} else {
LOG.info("Stopping Alluxio master @ {}", mMasterAddress);
}
}
protected void startMasters(boolean isLeader) {
try {
connectToUFS();
mBlockMaster.start(isLeader);
mFileSystemMaster.start(isLeader);
if (LineageUtils.isLineageEnabled()) {
mLineageMaster.start(isLeader);
}
// start additional masters
for (Master master : mAdditionalMasters) {
master.start(isLeader);
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
protected void stopMasters() {
try {
if (LineageUtils.isLineageEnabled()) {
mLineageMaster.stop();
}
// stop additional masters
for (Master master : mAdditionalMasters) {
master.stop();
}
mBlockMaster.stop();
mFileSystemMaster.stop();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
private void startServing() {
startServing("", "");
}
protected void startServing(String startMessage, String stopMessage) {
MetricsSystem.startSinks();
startServingWebServer();
LOG.info("Alluxio master version {} started @ {} {}", RuntimeConstants.VERSION, mMasterAddress,
startMessage);
startServingRPCServer();
LOG.info("Alluxio master version {} ended @ {} {}", RuntimeConstants.VERSION, mMasterAddress,
stopMessage);
}
protected void startServingWebServer() {
// Add the metrics servlet to the web server.
mWebServer.addHandler(mMetricsServlet.getHandler());
// start web ui
mWebServer.startWebServer();
}
private void registerServices(TMultiplexedProcessor processor, Map<String, TProcessor> services) {
for (Map.Entry<String, TProcessor> service : services.entrySet()) {
processor.registerProcessor(service.getKey(), service.getValue());
}
}
protected void startServingRPCServer() {
// set up multiplexed thrift processors
TMultiplexedProcessor processor = new TMultiplexedProcessor();
registerServices(processor, mBlockMaster.getServices());
registerServices(processor, mFileSystemMaster.getServices());
if (LineageUtils.isLineageEnabled()) {
registerServices(processor, mLineageMaster.getServices());
}
// register additional masters for RPC service
for (Master master : mAdditionalMasters) {
registerServices(processor, master.getServices());
}
// Return a TTransportFactory based on the authentication type
TTransportFactory transportFactory;
try {
transportFactory = mTransportProvider.getServerTransportFactory();
} catch (IOException e) {
throw Throwables.propagate(e);
}
// create master thrift service with the multiplexed processor.
Args args = new TThreadPoolServer.Args(mTServerSocket).maxWorkerThreads(mMaxWorkerThreads)
.minWorkerThreads(mMinWorkerThreads).processor(processor).transportFactory(transportFactory)
.protocolFactory(new TBinaryProtocol.Factory(true, true));
if (Configuration.getBoolean(PropertyKey.TEST_MODE)) {
args.stopTimeoutVal = 0;
} else {
args.stopTimeoutVal = Constants.THRIFT_STOP_TIMEOUT_SECONDS;
}
mMasterServiceServer = new TThreadPoolServer(args);
// start thrift rpc server
mIsServing = true;
mStartTimeMs = System.currentTimeMillis();
mMasterServiceServer.serve();
}
protected void stopServing() throws Exception {
if (mMasterServiceServer != null) {
mMasterServiceServer.stop();
mMasterServiceServer = null;
}
if (mWebServer != null) {
mWebServer.shutdownWebServer();
mWebServer = null;
}
MetricsSystem.stopSinks();
mIsServing = false;
}
/**
* Checks to see if the journal directory is formatted.
*
* @param journalDirectory the journal directory to check
* @return true if the journal directory was formatted previously, false otherwise
* @throws IOException if an I/O error occurs
*/
private boolean isJournalFormatted(String journalDirectory) throws IOException {
UnderFileSystem ufs = UnderFileSystem.get(journalDirectory);
if (!ufs.providesStorage()) {
// TODO(gene): Should the journal really be allowed on a ufs without storage?
// This ufs doesn't provide storage. Allow the master to use this ufs for the journal.
LOG.info("Journal directory doesn't provide storage: {}", journalDirectory);
return true;
}
String[] files = ufs.list(journalDirectory);
if (files == null) {
return false;
}
// Search for the format file.
String formatFilePrefix = Configuration.get(PropertyKey.MASTER_FORMAT_FILE_PREFIX);
for (String file : files) {
if (file.startsWith(formatFilePrefix)) {
return true;
}
}
return false;
}
private void connectToUFS() throws IOException {
String ufsAddress = Configuration.get(PropertyKey.UNDERFS_ADDRESS);
UnderFileSystem ufs = UnderFileSystem.get(ufsAddress);
ufs.connectFromMaster(NetworkAddressUtils.getConnectHost(ServiceType.MASTER_RPC));
}
/**
* Blocks until the master is ready to serve requests.
*/
public void waitForReady() {
while (true) {
if (mMasterServiceServer != null && mMasterServiceServer.isServing()
&& mWebServer != null && mWebServer.getServer().isRunning()) {
return;
}
CommonUtils.sleepMs(10);
}
}
}
| core/server/src/main/java/alluxio/master/AlluxioMaster.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.RuntimeConstants;
import alluxio.Server;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.FileSystemMaster;
import alluxio.master.journal.ReadWriteJournal;
import alluxio.master.lineage.LineageMaster;
import alluxio.metrics.MetricsSystem;
import alluxio.metrics.sink.MetricsServlet;
import alluxio.security.authentication.TransportProvider;
import alluxio.underfs.UnderFileSystem;
import alluxio.util.CommonUtils;
import alluxio.util.ConfigurationUtils;
import alluxio.util.LineageUtils;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.util.network.NetworkAddressUtils.ServiceType;
import alluxio.web.MasterUIWebServer;
import alluxio.web.UIWebServer;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;
/**
* Entry point for the Alluxio master program.
*/
@NotThreadSafe
public class AlluxioMaster implements Server {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
/**
* Starts the Alluxio master.
*
* @param args command line arguments, should be empty
*/
public static void main(String[] args) {
if (args.length != 0) {
LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR,
AlluxioMaster.class.getCanonicalName());
System.exit(-1);
}
// validate the configuration
if (!ConfigurationUtils.validateConf()) {
LOG.error("Invalid configuration found");
System.exit(-1);
}
AlluxioMaster master = new AlluxioMaster();
try {
master.start();
} catch (Exception e) {
LOG.error("Uncaught exception while running Alluxio master, stopping it and exiting.", e);
try {
master.stop();
} catch (Exception e2) {
// continue to exit
LOG.error("Uncaught exception while stopping Alluxio master, simply exiting.", e2);
}
System.exit(-1);
}
}
/** Maximum number of threads to serve the rpc server. */
private final int mMaxWorkerThreads;
/** Minimum number of threads to serve the rpc server. */
private final int mMinWorkerThreads;
/** The port for the RPC server. */
private final int mPort;
/** The socket for thrift rpc server. */
private final TServerSocket mTServerSocket;
/** The transport provider to create thrift server transport. */
private final TransportProvider mTransportProvider;
/** The address for the rpc server. */
private final InetSocketAddress mMasterAddress;
private final MetricsServlet mMetricsServlet = new MetricsServlet(MetricsSystem.METRIC_REGISTRY);
/** The master managing all block metadata. */
protected BlockMaster mBlockMaster;
/** The master managing all file system related metadata. */
protected FileSystemMaster mFileSystemMaster;
/** The master managing all lineage related metadata. */
protected LineageMaster mLineageMaster;
/** A list of extra masters to launch based on service loader. */
protected List<Master> mAdditionalMasters;
/** The journal for the block master. */
protected final ReadWriteJournal mBlockMasterJournal;
/** The journal for the file system master. */
protected final ReadWriteJournal mFileSystemMasterJournal;
/** The journal for the lineage master. */
protected final ReadWriteJournal mLineageMasterJournal;
/** The web ui server. */
private UIWebServer mWebServer = null;
/** The RPC server. */
private TServer mMasterServiceServer = null;
/** is true if the master is serving the RPC server. */
private boolean mIsServing = false;
/** The start time for when the master started serving the RPC server. */
private long mStartTimeMs = -1;
/** The master services' names. */
private static List<String> sServiceNames;
/** The master service loaders. */
private static ServiceLoader<MasterFactory> sServiceLoader;
/**
* @return the (cached) master service loader
*/
private static ServiceLoader<MasterFactory> getServiceLoader() {
if (sServiceLoader != null) {
return sServiceLoader;
}
// Discover and register the available factories.
// NOTE: ClassLoader is explicitly specified so we don't need to set ContextClassLoader.
sServiceLoader = ServiceLoader.load(MasterFactory.class, MasterFactory.class.getClassLoader());
return sServiceLoader;
}
/**
* @return the (cached) list of the enabled master services' names
*/
public static List<String> getServiceNames() {
if (sServiceNames != null) {
return sServiceNames;
}
sServiceNames = new ArrayList<>();
sServiceNames.add(Constants.BLOCK_MASTER_NAME);
sServiceNames.add(Constants.FILE_SYSTEM_MASTER_NAME);
sServiceNames.add(Constants.LINEAGE_MASTER_NAME);
for (MasterFactory factory : getServiceLoader()) {
if (factory.isEnabled()) {
sServiceNames.add(factory.getName());
}
}
return sServiceNames;
}
/**
* Factory for creating {@link AlluxioMaster} or {@link FaultTolerantAlluxioMaster} based on
* {@link Configuration}.
*/
@ThreadSafe
public static final class Factory {
/**
* @return {@link FaultTolerantAlluxioMaster} if Alluxio configuration is set to use zookeeper,
* otherwise, return {@link AlluxioMaster}.
*/
public static AlluxioMaster create() {
if (Configuration.getBoolean(PropertyKey.ZOOKEEPER_ENABLED)) {
return new FaultTolerantAlluxioMaster();
}
return new AlluxioMaster();
}
private Factory() {} // prevent instantiation.
}
protected AlluxioMaster() {
mMinWorkerThreads = Configuration.getInt(PropertyKey.MASTER_WORKER_THREADS_MIN);
mMaxWorkerThreads = Configuration.getInt(PropertyKey.MASTER_WORKER_THREADS_MAX);
Preconditions.checkArgument(mMaxWorkerThreads >= mMinWorkerThreads,
PropertyKey.MASTER_WORKER_THREADS_MAX + " can not be less than "
+ PropertyKey.MASTER_WORKER_THREADS_MIN);
try {
// Extract the port from the generated socket.
// When running tests, it is fine to use port '0' so the system will figure out what port to
// use (any random free port).
// In a production or any real deployment setup, port '0' should not be used as it will make
// deployment more complicated.
if (!Configuration.getBoolean(PropertyKey.TEST_MODE)) {
Preconditions.checkState(Configuration.getInt(PropertyKey.MASTER_RPC_PORT) > 0,
"Alluxio master rpc port is only allowed to be zero in test mode.");
Preconditions.checkState(Configuration.getInt(PropertyKey.MASTER_WEB_PORT) > 0,
"Alluxio master web port is only allowed to be zero in test mode.");
}
mTransportProvider = TransportProvider.Factory.create();
mTServerSocket =
new TServerSocket(NetworkAddressUtils.getBindAddress(ServiceType.MASTER_RPC));
mPort = NetworkAddressUtils.getThriftPort(mTServerSocket);
// reset master rpc port
Configuration.set(PropertyKey.MASTER_RPC_PORT, Integer.toString(mPort));
mMasterAddress = NetworkAddressUtils.getConnectAddress(ServiceType.MASTER_RPC);
// Check the journal directory
String journalDirectory = Configuration.get(PropertyKey.MASTER_JOURNAL_FOLDER);
if (!journalDirectory.endsWith(AlluxioURI.SEPARATOR)) {
journalDirectory += AlluxioURI.SEPARATOR;
}
Preconditions.checkState(isJournalFormatted(journalDirectory),
"Alluxio master was not formatted! The journal folder is " + journalDirectory);
// Create the journals.
mBlockMasterJournal = new ReadWriteJournal(BlockMaster.getJournalDirectory(journalDirectory));
mFileSystemMasterJournal =
new ReadWriteJournal(FileSystemMaster.getJournalDirectory(journalDirectory));
mLineageMasterJournal =
new ReadWriteJournal(LineageMaster.getJournalDirectory(journalDirectory));
mBlockMaster = new BlockMaster(mBlockMasterJournal);
mFileSystemMaster = new FileSystemMaster(mBlockMaster, mFileSystemMasterJournal);
if (LineageUtils.isLineageEnabled()) {
mLineageMaster = new LineageMaster(mFileSystemMaster, mLineageMasterJournal);
}
mAdditionalMasters = new ArrayList<>();
List<? extends Master> masters = Lists.newArrayList(mBlockMaster, mFileSystemMaster);
for (MasterFactory factory : getServiceLoader()) {
Master master = factory.create(masters, journalDirectory);
if (master != null) {
mAdditionalMasters.add(master);
}
}
// The web server needs to be created at the end of the constructor because it needs a
// reference to this class.
mWebServer = new MasterUIWebServer(ServiceType.MASTER_WEB.getServiceName(),
NetworkAddressUtils.getBindAddress(ServiceType.MASTER_WEB), this);
// reset master web port
Configuration.set(PropertyKey.MASTER_WEB_PORT, Integer.toString(mWebServer.getLocalPort()));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
/**
* @return the externally resolvable address of this master
*/
public InetSocketAddress getMasterAddress() {
return mMasterAddress;
}
/**
* @return the actual bind hostname on RPC service (used by unit test only)
*/
public String getRPCBindHost() {
return NetworkAddressUtils.getThriftSocket(mTServerSocket).getInetAddress().getHostAddress();
}
/**
* @return the actual port that the RPC service is listening on (used by unit test only)
*/
public int getRPCLocalPort() {
return mPort;
}
/**
* @return the actual bind hostname on web service (used by unit test only)
*/
public String getWebBindHost() {
if (mWebServer != null) {
return mWebServer.getBindHost();
}
return "";
}
/**
* @return the actual port that the web service is listening on (used by unit test only)
*/
public int getWebLocalPort() {
if (mWebServer != null) {
return mWebServer.getLocalPort();
}
return -1;
}
/**
* @return internal {@link BlockMaster}
*/
public BlockMaster getBlockMaster() {
return mBlockMaster;
}
/**
* @return other additional {@link Master}s
*/
public List<Master> getAdditionalMasters() {
return Collections.unmodifiableList(mAdditionalMasters);
}
/**
* @return internal {@link FileSystemMaster}
*/
public FileSystemMaster getFileSystemMaster() {
return mFileSystemMaster;
}
/**
* @return internal {@link LineageMaster}
*/
public LineageMaster getLineageMaster() {
return mLineageMaster;
}
/**
* @return the start time of the master in milliseconds
*/
public long getStartTimeMs() {
return mStartTimeMs;
}
/**
* @return the uptime of the master in milliseconds
*/
public long getUptimeMs() {
return System.currentTimeMillis() - mStartTimeMs;
}
/**
* @return true if the system is the leader (serving the rpc server), false otherwise
*/
boolean isServing() {
return mIsServing;
}
@Override
public void start() throws Exception {
startMasters(true);
startServing();
}
@Override
public void stop() throws Exception {
if (mIsServing) {
LOG.info("Stopping RPC server on Alluxio master @ {}", mMasterAddress);
stopServing();
stopMasters();
mTServerSocket.close();
mIsServing = false;
} else {
LOG.info("Stopping Alluxio master @ {}", mMasterAddress);
}
}
protected void startMasters(boolean isLeader) {
try {
connectToUFS();
mBlockMaster.start(isLeader);
mFileSystemMaster.start(isLeader);
if (LineageUtils.isLineageEnabled()) {
mLineageMaster.start(isLeader);
}
// start additional masters
for (Master master : mAdditionalMasters) {
master.start(isLeader);
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
protected void stopMasters() {
try {
if (LineageUtils.isLineageEnabled()) {
mLineageMaster.stop();
}
// stop additional masters
for (Master master : mAdditionalMasters) {
master.stop();
}
mBlockMaster.stop();
mFileSystemMaster.stop();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
private void startServing() {
startServing("", "");
}
protected void startServing(String startMessage, String stopMessage) {
MetricsSystem.startSinks();
startServingWebServer();
LOG.info("Alluxio master version {} started @ {} {}", RuntimeConstants.VERSION, mMasterAddress,
startMessage);
startServingRPCServer();
LOG.info("Alluxio master version {} ended @ {} {}", RuntimeConstants.VERSION, mMasterAddress,
stopMessage);
}
protected void startServingWebServer() {
// Add the metrics servlet to the web server.
mWebServer.addHandler(mMetricsServlet.getHandler());
// start web ui
mWebServer.startWebServer();
}
private void registerServices(TMultiplexedProcessor processor, Map<String, TProcessor> services) {
for (Map.Entry<String, TProcessor> service : services.entrySet()) {
processor.registerProcessor(service.getKey(), service.getValue());
}
}
protected void startServingRPCServer() {
// set up multiplexed thrift processors
TMultiplexedProcessor processor = new TMultiplexedProcessor();
registerServices(processor, mBlockMaster.getServices());
registerServices(processor, mFileSystemMaster.getServices());
if (LineageUtils.isLineageEnabled()) {
registerServices(processor, mLineageMaster.getServices());
}
// register additional masters for RPC service
for (Master master : mAdditionalMasters) {
registerServices(processor, master.getServices());
}
// Return a TTransportFactory based on the authentication type
TTransportFactory transportFactory;
try {
transportFactory = mTransportProvider.getServerTransportFactory();
} catch (IOException e) {
throw Throwables.propagate(e);
}
// create master thrift service with the multiplexed processor.
Args args = new TThreadPoolServer.Args(mTServerSocket).maxWorkerThreads(mMaxWorkerThreads)
.minWorkerThreads(mMinWorkerThreads).processor(processor).transportFactory(transportFactory)
.protocolFactory(new TBinaryProtocol.Factory(true, true));
if (Configuration.getBoolean(PropertyKey.TEST_MODE)) {
args.stopTimeoutVal = 0;
} else {
args.stopTimeoutVal = Constants.THRIFT_STOP_TIMEOUT_SECONDS;
}
mMasterServiceServer = new TThreadPoolServer(args);
// start thrift rpc server
mIsServing = true;
mStartTimeMs = System.currentTimeMillis();
mMasterServiceServer.serve();
}
protected void stopServing() throws Exception {
if (mMasterServiceServer != null) {
mMasterServiceServer.stop();
mMasterServiceServer = null;
}
if (mWebServer != null) {
mWebServer.shutdownWebServer();
mWebServer = null;
}
MetricsSystem.stopSinks();
mIsServing = false;
}
/**
* Checks to see if the journal directory is formatted.
*
* @param journalDirectory the journal directory to check
* @return true if the journal directory was formatted previously, false otherwise
* @throws IOException if an I/O error occurs
*/
private boolean isJournalFormatted(String journalDirectory) throws IOException {
UnderFileSystem ufs = UnderFileSystem.get(journalDirectory);
if (!ufs.providesStorage()) {
// TODO(gene): Should the journal really be allowed on a ufs without storage?
// This ufs doesn't provide storage. Allow the master to use this ufs for the journal.
LOG.info("Journal directory doesn't provide storage: {}", journalDirectory);
return true;
}
String[] files = ufs.list(journalDirectory);
if (files == null) {
return false;
}
// Search for the format file.
String formatFilePrefix = Configuration.get(PropertyKey.MASTER_FORMAT_FILE_PREFIX);
for (String file : files) {
if (file.startsWith(formatFilePrefix)) {
return true;
}
}
return false;
}
private void connectToUFS() throws IOException {
String ufsAddress = Configuration.get(PropertyKey.UNDERFS_ADDRESS);
UnderFileSystem ufs = UnderFileSystem.get(ufsAddress);
ufs.connectFromMaster(NetworkAddressUtils.getConnectHost(ServiceType.MASTER_RPC));
}
/**
* Blocks until the master is ready to serve requests.
*/
public void waitForReady() {
while (true) {
if (mMasterServiceServer != null && mMasterServiceServer.isServing()
&& mWebServer != null && mWebServer.getServer().isRunning()) {
return;
}
CommonUtils.sleepMs(10);
}
}
}
| [SMALLFIX] Use factory method to create master
| core/server/src/main/java/alluxio/master/AlluxioMaster.java | [SMALLFIX] Use factory method to create master | <ide><path>ore/server/src/main/java/alluxio/master/AlluxioMaster.java
<ide> System.exit(-1);
<ide> }
<ide>
<del> AlluxioMaster master = new AlluxioMaster();
<add> AlluxioMaster master = Factory.create();
<ide> try {
<ide> master.start();
<ide> } catch (Exception e) { |
|
Java | apache-2.0 | 029df7f8a3694f2b8909e1c91f0908a6d070d256 | 0 | jameBoy/spring-rest-exception-handler,merikan/spring-rest-exception-handler,jirutka/spring-rest-exception-handler,veiset/spring-rest-exception-handler,lokinell/spring-rest-exception-handler,jirutka/spring-rest-exception-handler | /*
* Copyright 2014-2015 Jakub Jirutka <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cz.jirutka.spring.exhandler;
import cz.jirutka.spring.exhandler.handlers.RestExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.FixedContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static cz.jirutka.spring.exhandler.support.HttpMessageConverterUtils.getDefaultHttpMessageConverters;
import static org.springframework.http.MediaType.APPLICATION_XML;
import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
/**
* A {@link org.springframework.web.servlet.HandlerExceptionResolver HandlerExceptionResolver}
* for RESTful APIs that resolves exceptions through the provided {@link RestExceptionHandler
* RestExceptionHandlers}.
*
* @see #builder()
* @see RestHandlerExceptionResolverBuilder
* @see RestHandlerExceptionResolverFactoryBean
*/
public class RestHandlerExceptionResolver extends AbstractHandlerExceptionResolver implements InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(RestHandlerExceptionResolver.class);
private final MethodParameter returnTypeMethodParam;
private List<HttpMessageConverter<?>> messageConverters = getDefaultHttpMessageConverters();
private Map<Class<? extends Exception>, RestExceptionHandler> handlers = new LinkedHashMap<>();
private MediaType defaultContentType = APPLICATION_XML;
private ContentNegotiationManager contentNegotiationManager;
// package visibility for tests
HandlerMethodReturnValueHandler responseProcessor;
// package visibility for tests
HandlerMethodReturnValueHandler fallbackResponseProcessor;
/**
* Returns a builder to build and configure instance of {@code RestHandlerExceptionResolver}.
*/
public static RestHandlerExceptionResolverBuilder builder() {
return new RestHandlerExceptionResolverBuilder();
}
public RestHandlerExceptionResolver() {
Method method = ClassUtils.getMethod(
RestExceptionHandler.class, "handleException", Exception.class, HttpServletRequest.class);
returnTypeMethodParam = new MethodParameter(method, -1);
// This method caches the resolved value, so it's convenient to initialize it
// only once here.
returnTypeMethodParam.getGenericParameterType();
}
@Override
public void afterPropertiesSet() {
if (contentNegotiationManager == null) {
contentNegotiationManager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(defaultContentType));
}
responseProcessor = new HttpEntityMethodProcessor(messageConverters, contentNegotiationManager);
fallbackResponseProcessor = new HttpEntityMethodProcessor(messageConverters,
new ContentNegotiationManager(new FixedContentNegotiationStrategy(defaultContentType)));
}
@Override
protected ModelAndView doResolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
ResponseEntity<?> entity;
try {
entity = handleException(exception, request);
} catch (NoExceptionHandlerFoundException ex) {
LOG.warn("No exception handler found to handle exception: {}", exception.getClass().getName());
return null;
}
try {
processResponse(entity, new ServletWebRequest(request, response));
} catch (Exception ex) {
LOG.error("Failed to process error response: {}", entity, ex);
return null;
}
return new ModelAndView();
}
protected ResponseEntity<?> handleException(Exception exception, HttpServletRequest request) {
// See http://stackoverflow.com/a/12979543/2217862
// This attribute is never set in MockMvc, so it's not covered in integration test.
request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
RestExceptionHandler<Exception, ?> handler = resolveExceptionHandler(exception.getClass());
LOG.debug("Handling exception {} with response factory: {}", exception.getClass().getName(), handler);
return handler.handleException(exception, request);
}
@SuppressWarnings("unchecked")
protected RestExceptionHandler<Exception, ?> resolveExceptionHandler(Class<? extends Exception> exceptionClass) {
for (Class clazz = exceptionClass; clazz != Throwable.class; clazz = clazz.getSuperclass()) {
if (handlers.containsKey(clazz)) {
return handlers.get(clazz);
}
}
throw new NoExceptionHandlerFoundException();
}
protected void processResponse(ResponseEntity<?> entity, NativeWebRequest webRequest) throws Exception {
// XXX: Create MethodParameter from the actually used subclass of RestExceptionHandler?
MethodParameter methodParameter = new MethodParameter(returnTypeMethodParam);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
responseProcessor.handleReturnValue(entity, methodParameter, mavContainer, webRequest);
} catch (HttpMediaTypeNotAcceptableException ex) {
LOG.debug("Requested media type is not supported, falling back to default one");
fallbackResponseProcessor.handleReturnValue(entity, methodParameter, mavContainer, webRequest);
}
}
//////// Accessors ////////
// Note: We're not using Lombok in this class to make it clear for debugging.
public List<HttpMessageConverter<?>> getMessageConverters() {
return messageConverters;
}
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
Assert.notNull(messageConverters, "messageConverters must not be null");
this.messageConverters = messageConverters;
}
public ContentNegotiationManager getContentNegotiationManager() {
return this.contentNegotiationManager;
}
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
this.contentNegotiationManager = contentNegotiationManager != null
? contentNegotiationManager : new ContentNegotiationManager();
}
public MediaType getDefaultContentType() {
return defaultContentType;
}
public void setDefaultContentType(MediaType defaultContentType) {
this.defaultContentType = defaultContentType;
}
public Map<Class<? extends Exception>, RestExceptionHandler> getExceptionHandlers() {
return handlers;
}
public void setExceptionHandlers(Map<Class<? extends Exception>, RestExceptionHandler> handlers) {
this.handlers = handlers;
}
//////// Inner classes ////////
public static class NoExceptionHandlerFoundException extends RuntimeException {}
}
| src/main/java/cz/jirutka/spring/exhandler/RestHandlerExceptionResolver.java | /*
* Copyright 2014 Jakub Jirutka <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cz.jirutka.spring.exhandler;
import cz.jirutka.spring.exhandler.handlers.RestExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.FixedContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static cz.jirutka.spring.exhandler.support.HttpMessageConverterUtils.getDefaultHttpMessageConverters;
import static org.springframework.http.MediaType.APPLICATION_XML;
import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
/**
* A {@link org.springframework.web.servlet.HandlerExceptionResolver HandlerExceptionResolver}
* for RESTful APIs that resolves exceptions through the provided {@link RestExceptionHandler
* RestExceptionHandlers}.
*
* @see #builder()
* @see RestHandlerExceptionResolverBuilder
* @see RestHandlerExceptionResolverFactoryBean
*/
public class RestHandlerExceptionResolver extends AbstractHandlerExceptionResolver implements InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(RestHandlerExceptionResolver.class);
private List<HttpMessageConverter<?>> messageConverters = getDefaultHttpMessageConverters();
private Map<Class<? extends Exception>, RestExceptionHandler> handlers = new LinkedHashMap<>();
private MediaType defaultContentType = APPLICATION_XML;
private ContentNegotiationManager contentNegotiationManager;
// package visibility for tests
HandlerMethodReturnValueHandler responseProcessor;
// package visibility for tests
HandlerMethodReturnValueHandler fallbackResponseProcessor;
/**
* Returns a builder to build and configure instance of {@code RestHandlerExceptionResolver}.
*/
public static RestHandlerExceptionResolverBuilder builder() {
return new RestHandlerExceptionResolverBuilder();
}
@Override
public void afterPropertiesSet() {
if (contentNegotiationManager == null) {
contentNegotiationManager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(defaultContentType));
}
responseProcessor = new HttpEntityMethodProcessor(messageConverters, contentNegotiationManager);
fallbackResponseProcessor = new HttpEntityMethodProcessor(messageConverters,
new ContentNegotiationManager(new FixedContentNegotiationStrategy(defaultContentType)));
}
@Override
protected ModelAndView doResolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
ResponseEntity<?> entity;
try {
entity = handleException(exception, request);
} catch (NoExceptionHandlerFoundException ex) {
LOG.warn("No exception handler found to handle exception: {}", exception.getClass().getName());
return null;
}
try {
processResponse(entity, new ServletWebRequest(request, response));
} catch (Exception ex) {
LOG.error("Failed to process error response: {}", entity, ex);
return null;
}
return new ModelAndView();
}
protected ResponseEntity<?> handleException(Exception exception, HttpServletRequest request) {
// See http://stackoverflow.com/a/12979543/2217862
// This attribute is never set in MockMvc, so it's not covered in integration test.
request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
RestExceptionHandler<Exception, ?> handler = resolveExceptionHandler(exception.getClass());
LOG.debug("Handling exception {} with response factory: {}", exception.getClass().getName(), handler);
return handler.handleException(exception, request);
}
@SuppressWarnings("unchecked")
protected RestExceptionHandler<Exception, ?> resolveExceptionHandler(Class<? extends Exception> exceptionClass) {
for (Class clazz = exceptionClass; clazz != Throwable.class; clazz = clazz.getSuperclass()) {
if (handlers.containsKey(clazz)) {
return handlers.get(clazz);
}
}
throw new NoExceptionHandlerFoundException();
}
protected void processResponse(ResponseEntity<?> entity, NativeWebRequest webRequest) throws Exception {
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
try {
responseProcessor.handleReturnValue(entity, null, mavContainer, webRequest);
} catch (HttpMediaTypeNotAcceptableException ex) {
LOG.debug("Requested media type is not supported, falling back to default one");
fallbackResponseProcessor.handleReturnValue(entity, null, mavContainer, webRequest);
}
}
//////// Accessors ////////
// Note: We're not using Lombok in this class to make it clear for debugging.
public List<HttpMessageConverter<?>> getMessageConverters() {
return messageConverters;
}
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
Assert.notNull(messageConverters, "messageConverters must not be null");
this.messageConverters = messageConverters;
}
public ContentNegotiationManager getContentNegotiationManager() {
return this.contentNegotiationManager;
}
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
this.contentNegotiationManager = contentNegotiationManager != null
? contentNegotiationManager : new ContentNegotiationManager();
}
public MediaType getDefaultContentType() {
return defaultContentType;
}
public void setDefaultContentType(MediaType defaultContentType) {
this.defaultContentType = defaultContentType;
}
public Map<Class<? extends Exception>, RestExceptionHandler> getExceptionHandlers() {
return handlers;
}
public void setExceptionHandlers(Map<Class<? extends Exception>, RestExceptionHandler> handlers) {
this.handlers = handlers;
}
//////// Inner classes ////////
public static class NoExceptionHandlerFoundException extends RuntimeException {}
}
| Fix NPE due to null returnType when using spring-webmvc >= 4.2.0
The returnType parameter in HandlerMethodReturnValueHandler.handleReturnValue()
is no longer ignored in Spring WebMVC 4.2.0.
Closes #9. Thanks to @jervi for the warning and suggestion of fix.
| src/main/java/cz/jirutka/spring/exhandler/RestHandlerExceptionResolver.java | Fix NPE due to null returnType when using spring-webmvc >= 4.2.0 | <ide><path>rc/main/java/cz/jirutka/spring/exhandler/RestHandlerExceptionResolver.java
<ide> /*
<del> * Copyright 2014 Jakub Jirutka <[email protected]>.
<add> * Copyright 2014-2015 Jakub Jirutka <[email protected]>.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide> import org.springframework.beans.factory.InitializingBean;
<add>import org.springframework.core.MethodParameter;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.web.HttpMediaTypeNotAcceptableException;
<ide> import org.springframework.web.accept.ContentNegotiationManager;
<ide> import org.springframework.web.accept.FixedContentNegotiationStrategy;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<add>import java.lang.reflect.Method;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> private static final Logger LOG = LoggerFactory.getLogger(RestHandlerExceptionResolver.class);
<ide>
<add> private final MethodParameter returnTypeMethodParam;
<add>
<ide> private List<HttpMessageConverter<?>> messageConverters = getDefaultHttpMessageConverters();
<ide>
<ide> private Map<Class<? extends Exception>, RestExceptionHandler> handlers = new LinkedHashMap<>();
<ide> */
<ide> public static RestHandlerExceptionResolverBuilder builder() {
<ide> return new RestHandlerExceptionResolverBuilder();
<add> }
<add>
<add>
<add> public RestHandlerExceptionResolver() {
<add>
<add> Method method = ClassUtils.getMethod(
<add> RestExceptionHandler.class, "handleException", Exception.class, HttpServletRequest.class);
<add>
<add> returnTypeMethodParam = new MethodParameter(method, -1);
<add> // This method caches the resolved value, so it's convenient to initialize it
<add> // only once here.
<add> returnTypeMethodParam.getGenericParameterType();
<ide> }
<ide>
<ide>
<ide>
<ide> protected void processResponse(ResponseEntity<?> entity, NativeWebRequest webRequest) throws Exception {
<ide>
<add> // XXX: Create MethodParameter from the actually used subclass of RestExceptionHandler?
<add> MethodParameter methodParameter = new MethodParameter(returnTypeMethodParam);
<ide> ModelAndViewContainer mavContainer = new ModelAndViewContainer();
<add>
<ide> try {
<del> responseProcessor.handleReturnValue(entity, null, mavContainer, webRequest);
<add> responseProcessor.handleReturnValue(entity, methodParameter, mavContainer, webRequest);
<ide>
<ide> } catch (HttpMediaTypeNotAcceptableException ex) {
<ide> LOG.debug("Requested media type is not supported, falling back to default one");
<del> fallbackResponseProcessor.handleReturnValue(entity, null, mavContainer, webRequest);
<add> fallbackResponseProcessor.handleReturnValue(entity, methodParameter, mavContainer, webRequest);
<ide> }
<ide> }
<ide> |
|
JavaScript | bsd-2-clause | 53015d32dbf6f324aaaaa4eeeebb9f5bc58f371a | 0 | macbre/phantomas,macbre/phantomas,macbre/phantomas | /**
* Defines phantomas global API mock
*/
/* istanbul ignore file */
const assert = require("assert"),
debug = require("debug"),
noop = () => {},
{ test } = require("@jest/globals");
var phantomas = function (name) {
this.emitter = new (require("events").EventEmitter)();
this.wasEmitted = {};
this.metrics = {};
this.offenders = {};
this.log = debug("phantomas:test:" + name);
};
phantomas.prototype = {
require: function (name) {
return require(name);
},
getParam: noop,
// events
emit: function (/* eventName, arg1, arg2, ... */) {
//console.log('emit: ' + arguments[0]);
try {
this.log("emit: %j", Array.prototype.slice.apply(arguments));
this.emitter.emit.apply(this.emitter, arguments);
} catch (ex) {
console.log(ex);
}
this.wasEmitted[arguments[0]] = true;
return this;
},
emitInternal: function () {
this.emit.apply(this, arguments);
},
on: function (ev, fn) {
//console.log('on: ' + ev);
this.emitter.on(ev, fn);
},
once: function (ev, fn) {
this.emitter.once(ev, fn);
},
emitted: function (ev) {
return this.wasEmitted[ev] === true;
},
// metrics
setMetric: function (name, value) {
this.metrics[name] = typeof value !== "undefined" ? value : 0;
},
setMetricEvaluate: noop,
incrMetric: function (name, incr /* =1 */) {
this.metrics[name] = (this.metrics[name] || 0) + (incr || 1);
},
getMetric: function (name) {
return this.metrics[name];
},
hasValue: function (name, val) {
return this.getMetric(name) === val;
},
addOffender: function (name, value) {
this.offenders[name] = this.offenders[name] || [];
this.offenders[name].push(value);
},
getOffenders: function (name) {
return this.offenders[name];
},
// mock core phantomas events
sendRequest: function (req) {
req = req || {};
req._requestId = req._requestId || 1;
req.method = req.method || "GET";
req.url = req.url || "http://example.com";
req.headers = req.headers || [];
req.timing = {};
req.headersText = "";
this.log("sendRequest: %j", req);
try {
this.emitter.emit("request", req);
this.emitter.emit("response", req);
} catch (ex) {
console.log(ex);
}
return this;
},
recvRequest: function (req) {
req = req || {};
req.stage = req.stage || "end";
req.id = req.id || 1;
req.method = req.method || "GET";
req.url = req.url || "http://example.com";
req.headers = req.headers || [];
this.log("recvRequest: %j", req);
try {
this.emitter.emit("onResourceRequested", req);
this.emitter.emit("onResourceReceived", req);
} catch (ex) {
console.log(ex);
}
return this;
},
// phantomas-specific events
send: function (entry, res) {
return this.emit("send", entry || {}, res || {});
},
recv: function (entry, res) {
return this.emit("recv", entry || {}, res || {});
},
responseEnd: function (entry, res) {
return this.emit("responseEnd", entry || {}, res || {});
},
report: function () {
this.emit("report");
this.log("metrics: %j", this.metrics);
return this;
},
// noop mocks
log: noop,
echo: noop,
evaluate: noop,
injectJs: noop,
};
function initModule(name, isCore) {
var instance, def;
try {
instance = new phantomas(name);
def = require("../../" +
(isCore ? "core/modules" : "modules") +
"/" +
name +
"/" +
name +
".js");
new def(instance);
} catch (ex) {
console.log(ex);
}
return instance;
}
function assertMetric(name, value) {
return function (phantomas) {
assert.strictEqual(phantomas.getMetric(name), value);
};
}
module.exports = {
initModule: function (name) {
return initModule(name);
},
initCoreModule: function (name) {
return initModule(name, true /* core */);
},
assertMetric: assertMetric,
getContext: function (moduleName, topic, metricsCheck, offendersCheck) {
// mock phantomas with just a single module loaded
const phantomas = initModule(moduleName);
// execute mocked phantomas with mocked requests (as defined by the test case)
topic(phantomas);
Object.keys(metricsCheck || {}).forEach(function (name) {
test(`sets "${name}" metric correctly`, () => {
assert.strictEqual(phantomas.getMetric(name), metricsCheck[name]);
});
});
Object.keys(offendersCheck || {}).forEach(function (name) {
test(`sets "${name}" offender(s) correctly`, () => {
assert.deepStrictEqual(
phantomas.getOffenders(name),
offendersCheck[name]
);
});
});
},
};
| test/modules/mock.js | /**
* Defines phantomas global API mock
*/
/* istanbul ignore file */
const assert = require("assert"),
debug = require("debug"),
noop = () => {},
{ test } = require("@jest/globals");
var phantomas = function (name) {
this.emitter = new (require("events").EventEmitter)();
this.wasEmitted = {};
this.metrics = {};
this.offenders = {};
this.log = debug("phantomas:test:" + name);
};
phantomas.prototype = {
require: function (name) {
return require(name);
},
getParam: noop,
// events
emit: function (/* eventName, arg1, arg2, ... */) {
//console.log('emit: ' + arguments[0]);
try {
this.log("emit: %j", Array.prototype.slice.apply(arguments));
this.emitter.emit.apply(this.emitter, arguments);
} catch (ex) {
console.log(ex);
}
this.wasEmitted[arguments[0]] = true;
return this;
},
emitInternal: function () {
this.emit.apply(this, arguments);
},
on: function (ev, fn) {
//console.log('on: ' + ev);
this.emitter.on(ev, fn);
},
once: function (ev, fn) {
this.emitter.once(ev, fn);
},
emitted: function (ev) {
return this.wasEmitted[ev] === true;
},
// metrics
setMetric: function (name, value) {
this.metrics[name] = typeof value !== "undefined" ? value : 0;
},
setMetricEvaluate: noop,
incrMetric: function (name, incr /* =1 */) {
this.metrics[name] = (this.metrics[name] || 0) + (incr || 1);
},
getMetric: function (name) {
return this.metrics[name];
},
hasValue: function (name, val) {
return this.getMetric(name) === val;
},
addOffender: function (name, value) {
this.offenders[name] = this.offenders[name] || [];
this.offenders[name].push(value);
},
getOffenders: function (name) {
return this.offenders[name];
},
// mock core phantomas events
sendRequest: function (req) {
req = req || {};
req._requestId = req._requestId || 1;
req.method = req.method || "GET";
req.url = req.url || "http://example.com";
req.headers = req.headers || [];
req.timing = {};
req.headersText = "";
this.log("sendRequest: %j", req);
try {
this.emitter.emit("request", req);
this.emitter.emit("response", req);
} catch (ex) {
console.log(ex);
}
return this;
},
recvRequest: function (req) {
req = req || {};
req.stage = req.stage || "end";
req.id = req.id || 1;
req.method = req.method || "GET";
req.url = req.url || "http://example.com";
req.headers = req.headers || [];
this.log("recvRequest: %j", req);
try {
this.emitter.emit("onResourceRequested", req);
this.emitter.emit("onResourceReceived", req);
} catch (ex) {
console.log(ex);
}
return this;
},
// phantomas-specific events
send: function (entry, res) {
return this.emit("send", entry || {}, res || {});
},
recv: function (entry, res) {
return this.emit("recv", entry || {}, res || {});
},
responseEnd: function (entry, res) {
return this.emit("responseEnd", entry || {}, res || {});
},
report: function () {
this.emit("report");
this.log("metrics: %j", this.metrics);
return this;
},
// noop mocks
log: noop,
echo: noop,
evaluate: noop,
injectJs: noop,
};
function initModule(name, isCore) {
var instance, def;
try {
instance = new phantomas(name);
def = require("../../" +
(isCore ? "core/modules" : "modules") +
"/" +
name +
"/" +
name +
".js");
new def(instance);
} catch (ex) {
console.log(ex);
}
return instance;
}
function assertMetric(name, value) {
return function (phantomas) {
assert.strictEqual(phantomas.getMetric(name), value);
};
}
function assertOffender(name, value) {
return function (phantomas) {
assert.deepStrictEqual(phantomas.getOffenders(name), value);
};
}
module.exports = {
initModule: function (name) {
return initModule(name);
},
initCoreModule: function (name) {
return initModule(name, true /* core */);
},
assertMetric: assertMetric,
getContext: function (moduleName, topic, metricsCheck, offendersCheck) {
// mock phantomas with just a single module loaded
const phantomas = initModule(moduleName);
// execute mocked phantomas with mocked requests (as defined by the test case)
topic(phantomas);
Object.keys(metricsCheck || {}).forEach(function (name) {
test(`sets "${name}" metric correctly`, () => {
assertMetric(name, metricsCheck[name]);
});
});
Object.keys(offendersCheck || {}).forEach(function (name) {
test(`sets "${name}" offender(s) correctly`, () => {
assertOffender(name, offendersCheck[name]);
});
});
},
};
| test/modules/mock.js: improve metrics and offenders assertions when testing mocked modules
| test/modules/mock.js | test/modules/mock.js: improve metrics and offenders assertions when testing mocked modules | <ide><path>est/modules/mock.js
<ide> };
<ide> }
<ide>
<del>function assertOffender(name, value) {
<del> return function (phantomas) {
<del> assert.deepStrictEqual(phantomas.getOffenders(name), value);
<del> };
<del>}
<del>
<ide> module.exports = {
<ide> initModule: function (name) {
<ide> return initModule(name);
<ide>
<ide> Object.keys(metricsCheck || {}).forEach(function (name) {
<ide> test(`sets "${name}" metric correctly`, () => {
<del> assertMetric(name, metricsCheck[name]);
<add> assert.strictEqual(phantomas.getMetric(name), metricsCheck[name]);
<ide> });
<ide> });
<ide>
<ide> Object.keys(offendersCheck || {}).forEach(function (name) {
<ide> test(`sets "${name}" offender(s) correctly`, () => {
<del> assertOffender(name, offendersCheck[name]);
<add> assert.deepStrictEqual(
<add> phantomas.getOffenders(name),
<add> offendersCheck[name]
<add> );
<ide> });
<ide> });
<ide> }, |
|
Java | apache-2.0 | error: pathspec 'chapter_007/src/test/java/ru/job4j/additional_test/CheckTest.java' did not match any file(s) known to git
| b08a4f6440b416751e2cdcf7dfc4f73b9e15da6d | 1 | AVBaranov/abaranov,AVBaranov/abaranov | package ru.job4j.additional_test;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by Андрей on 12.10.2017.
*/
public class CheckTest {
@Test
public void whenTwoStringEqualsThenReturnTrue() {
boolean expectation = new Check().contains("string", "gsrtin");
assertThat(true, is(expectation));
}
}
| chapter_007/src/test/java/ru/job4j/additional_test/CheckTest.java | additional test
| chapter_007/src/test/java/ru/job4j/additional_test/CheckTest.java | additional test | <ide><path>hapter_007/src/test/java/ru/job4j/additional_test/CheckTest.java
<add>package ru.job4j.additional_test;
<add>
<add>import org.junit.Test;
<add>import static org.hamcrest.core.Is.is;
<add>import static org.junit.Assert.assertThat;
<add>
<add>/**
<add> * Created by Андрей on 12.10.2017.
<add> */
<add>public class CheckTest {
<add> @Test
<add> public void whenTwoStringEqualsThenReturnTrue() {
<add> boolean expectation = new Check().contains("string", "gsrtin");
<add> assertThat(true, is(expectation));
<add> }
<add>} |
|
Java | mit | 4ef6212854c71e9d3b286362880b64a683afe19c | 0 | Gongxl/cs290bHw3,PeterCappello/cs290bHw3 | /*
* The MIT License
*
* Copyright 2015 peter.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package system;
import api.*;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* An implementation of the Remote Computer interface.
* @author Peter Cappello
*/
public class ComputerImpl extends UnicastRemoteObject implements Computer
{
public ComputerImpl() throws RemoteException {}
/**
* Execute a Task.
* @param task to be executed.
* @return the return-value of the Task call method.
* @throws RemoteException
*/
@Override
public Return execute( Task task ) throws RemoteException
{
final long startTime = System.nanoTime();
final Return returnValue = task.call();
final long runTime = ( System.nanoTime() - startTime ) / 1000000; // milliseconds
returnValue.taskRunTime( runTime );
return returnValue;
}
public static void main( String[] args ) throws Exception
{
System.setSecurityManager( new SecurityManager() );
final String domainName = "localhost";
final String url = "rmi://" + domainName + ":" + Space.PORT + "/" + Space.SERVICE_NAME;
final Space space = (Space) Naming.lookup( url );
space.register( new ComputerImpl() );
System.out.println( "Computer running." );
}
/**
* Terminate the JVM.
* @throws RemoteException - always!
*/
@Override
public void exit() throws RemoteException
{
System.out.println("Computer: exiting." ); /*System.exit( 0 ); */
}
}
| cs290bHw3/src/system/ComputerImpl.java | /*
* The MIT License
*
* Copyright 2015 peter.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package system;
import api.*;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* An implementation of the Remote Computer interface.
* @author Peter Cappello
*/
public class ComputerImpl extends UnicastRemoteObject implements Computer
{
public int numTasks = 0;
public ComputerImpl() throws RemoteException {}
/**
* Execute a Task.
* @param task to be executed.
* @return the return-value of the Task call method.
* @throws RemoteException
*/
@Override
public Return execute( Task task ) throws RemoteException
{
numTasks++;
final long startTime = System.nanoTime();
final Return returnValue = task.call();
final long runTime = ( System.nanoTime() - startTime ) / 1000000; // milliseconds
returnValue.taskRunTime( runTime );
return returnValue;
}
public static void main( String[] args ) throws Exception
{
System.setSecurityManager( new SecurityManager() );
final String domainName = "localhost";
final String url = "rmi://" + domainName + ":" + Space.PORT + "/" + Space.SERVICE_NAME;
final Space space = (Space) Naming.lookup( url );
space.register( new ComputerImpl() );
System.out.println( "Computer running." );
}
/**
* Terminate the JVM.
* @throws RemoteException - always!
*/
@Override
public void exit() throws RemoteException
{
System.out.println("Computer.exit: # tasks complete:" + numTasks ); /*System.exit( 0 ); */
}
}
| Stopped counting completed tasks in ComputerImpl. | cs290bHw3/src/system/ComputerImpl.java | Stopped counting completed tasks in ComputerImpl. | <ide><path>s290bHw3/src/system/ComputerImpl.java
<ide> */
<ide> public class ComputerImpl extends UnicastRemoteObject implements Computer
<ide> {
<del> public int numTasks = 0;
<del>
<ide> public ComputerImpl() throws RemoteException {}
<ide>
<ide> /**
<ide> @Override
<ide> public Return execute( Task task ) throws RemoteException
<ide> {
<del> numTasks++;
<ide> final long startTime = System.nanoTime();
<ide> final Return returnValue = task.call();
<ide> final long runTime = ( System.nanoTime() - startTime ) / 1000000; // milliseconds
<ide> @Override
<ide> public void exit() throws RemoteException
<ide> {
<del> System.out.println("Computer.exit: # tasks complete:" + numTasks ); /*System.exit( 0 ); */
<add> System.out.println("Computer: exiting." ); /*System.exit( 0 ); */
<ide> }
<ide> } |
|
Java | apache-2.0 | 4aa586644612ea4e5b6f99bed891d00b6966caa2 | 0 | danc86/jena-core,danc86/jena-core | /*****************************************************************************
* Source code metadata
*
* Original author ijd
* Package Jena2
* Created 4 Dec 2007
* File TestOntTools.java
*
* (c) Copyright 2007, 2008, 2009 Hewlett-Packard Development Company, LP
* (see footer for full conditions)
*****************************************************************************/
// Package
///////////////
package com.hp.hpl.jena.ontology.impl.test;
// Imports
///////////////
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.vocabulary.OWL;
/**
* <p>
* Unit tests for experimental ontology tools class.
* </p>
*
* @author Ian Dickinson, HP Labs (<a href="mailto:[email protected]">email</a>)
*/
public class TestOntTools
extends TestCase
{
// Constants
//////////////////////////////////
String NS = "http://example.com/test#";
// Static variables
//////////////////////////////////
// Instance variables
//////////////////////////////////
OntModel m_model;
OntClass m_a;
OntClass m_b;
OntClass m_c;
OntClass m_d;
OntClass m_e;
OntClass m_f;
OntClass m_g;
OntClass m_top;
// Constructors
//////////////////////////////////
// External signature methods
//////////////////////////////////
/**
* @throws java.lang.Exception
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
m_model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF );
m_a = m_model.createClass( NS + "A" );
m_b = m_model.createClass( NS + "B" );
m_c = m_model.createClass( NS + "C" );
m_d = m_model.createClass( NS + "D" );
m_e = m_model.createClass( NS + "E" );
m_f = m_model.createClass( NS + "F" );
m_g = m_model.createClass( NS + "G" );
m_top = m_model.createClass( OWL.Thing.getURI() );
}
/**
* Test method for <code>com.hp.hpl.jena.ontology.OntTools#indexLCA</code>
*/
public void testIndexLCA0() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_c ) );
}
public void testIndexLCA1() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_b ) );
}
public void testIndexLCA2() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_a, m_c ) );
}
public void testIndexLCA3() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_a ) );
}
public void testIndexLCA4() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
assertEquals( m_a, OntTools.getLCA( m_model, m_d, m_c ) );
}
public void testIndexLCA5() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_d ) );
}
public void testIndexLCA6() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_c.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_d, m_e ) );
}
public void testIndexLCA7() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_c.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_e, m_d ) );
}
public void testIndexLCA8() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_d.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_e ) );
}
public void testIndexLCA9() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_d.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_c ) );
}
public void testIndexLCA10() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_e ) );
}
public void testIndexLCA11() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_f ) );
}
public void testIndexLCA12() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_d.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_d, OntTools.getLCA( m_model, m_f, m_e ) );
}
public void testIndexLCA13() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_d, OntTools.getLCA( m_model, m_f, m_e ) );
}
/** Disconnected trees */
public void testIndexLCA14() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_b, m_e ) );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_c, m_e ) );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_a, m_e ) );
}
/** Shortest path tests */
static final Filter<Statement> ANY = Filter.any();
public void testShortestPath0() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_b );
testPath( OntTools.findShortestPath( m_model, m_a, m_b, ANY ),
new Property[] {p} );
}
public void testShortestPath1() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, ANY ),
new Property[] {p,p} );
}
public void testShortestPath2() {
Property p = m_model.createProperty( NS + "p" );
// a - b - c
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
// a - d - e - f
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, ANY ),
new Property[] {p,p} );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, ANY ),
new Property[] {p,p,p} );
}
public void testShortestPath3() {
Property p = m_model.createProperty( NS + "p" );
// a - b - c
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
// a - d - e - f
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p} );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p,p} );
}
public void testShortestPath4() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - b - c by q
m_a.addProperty( q, m_b );
m_b.addProperty( q, m_c );
// a - d - e - f by p
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
assertNull( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( p ) ) );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p,p} );
}
/** Reflexive loop is allowed */
public void testShortestPath5() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_a );
testPath( OntTools.findShortestPath( m_model, m_a, m_a, ANY ),
new Property[] {p} );
}
public void testShortestPath6() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - b - a by q
// tests loop detection
m_a.addProperty( q, m_b );
m_b.addProperty( q, m_a );
assertNull( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( new Property[] {p,q} ) ) );
}
public void testShortestPath7() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - d - e - f by p and q
m_a.addProperty( p, m_d );
m_d.addProperty( q, m_e );
m_d.addProperty( q, m_b );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( new Property[] {p,q} ) ),
new Property[] {p,q,p} );
}
/** Find a literal target */
public void testShortestPath8() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - d - e - f by p and q
m_a.addProperty( p, m_d );
m_d.addProperty( q, m_e );
m_d.addProperty( q, "bluff" );
m_d.addProperty( q, m_b );
m_e.addProperty( p, m_f );
m_f.addProperty( q, "arnie" );
testPath( OntTools.findShortestPath( m_model, m_a, ResourceFactory.createPlainLiteral( "arnie" ),
new OntTools.PredicatesFilter( new Property[] {p,q} ) ),
new Property[] {p,q,p,q} );
}
/** Tests on {@link OntTools#namedHierarchyRoots(OntModel)} */
public void testNamedHierarchyRoots0() {
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
public void testNamedHierarchyRoots1() {
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
OntClass anon0 = m_model.createClass();
anon0.addSubClass( m_a );
anon0.addSubClass( m_e );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
public void testNamedHierarchyRoots2() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon0.addSubClass( m_e );
anon0.addSubClass( anon1 );
anon1.addSubClass( m_g );
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
/** Test for no dups in the returned list */
public void testNamedHierarchyRoots3() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon1.addSubClass( m_a );
// only a is root
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_a.addSubClass( m_e );
m_a.addSubClass( m_f );
m_a.addSubClass( m_g );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 1, nhr.size() );
assertTrue( nhr.contains( m_a ));
}
/** Test for indirect route to a non-root node */
public void testNamedHierarchyRoots4() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon1.addSubClass( m_b );
// only a is root, because b is a subclass of a
// even though b is a sub-class of an anon root
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_a.addSubClass( m_e );
m_a.addSubClass( m_f );
m_a.addSubClass( m_g );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 1, nhr.size() );
assertTrue( nhr.contains( m_a ));
}
// Internal implementation methods
//////////////////////////////////
private void testPath( OntTools.Path path, Property[] expected ) {
assertEquals( expected.length, path.size() );
int i = 0;
Iterator j = path.iterator();
while (j.hasNext()) {
assertEquals( "path position: " + i, expected[i], ((Statement) j.next()).getPredicate() );
i++;
}
}
//==============================================================================
// Inner class definitions
//==============================================================================
}
/*
(c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| src/com/hp/hpl/jena/ontology/impl/test/TestOntTools.java | /*****************************************************************************
* Source code metadata
*
* Original author ijd
* Package Jena2
* Created 4 Dec 2007
* File TestOntTools.java
*
* (c) Copyright 2007, 2008, 2009 Hewlett-Packard Development Company, LP
* (see footer for full conditions)
*****************************************************************************/
// Package
///////////////
package com.hp.hpl.jena.ontology.impl.test;
// Imports
///////////////
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.vocabulary.OWL;
/**
* <p>
* Unit tests for experimental ontology tools class.
* </p>
*
* @author Ian Dickinson, HP Labs (<a href="mailto:[email protected]">email</a>)
*/
public class TestOntTools
extends TestCase
{
// Constants
//////////////////////////////////
String NS = "http://example.com/test#";
// Static variables
//////////////////////////////////
// Instance variables
//////////////////////////////////
OntModel m_model;
OntClass m_a;
OntClass m_b;
OntClass m_c;
OntClass m_d;
OntClass m_e;
OntClass m_f;
OntClass m_g;
OntClass m_top;
// Constructors
//////////////////////////////////
// External signature methods
//////////////////////////////////
/**
* @throws java.lang.Exception
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
m_model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF );
m_a = m_model.createClass( NS + "A" );
m_b = m_model.createClass( NS + "B" );
m_c = m_model.createClass( NS + "C" );
m_d = m_model.createClass( NS + "D" );
m_e = m_model.createClass( NS + "E" );
m_f = m_model.createClass( NS + "F" );
m_g = m_model.createClass( NS + "G" );
m_top = m_model.createClass( OWL.Thing.getURI() );
}
/**
* Test method for <code>com.hp.hpl.jena.ontology.OntTools#indexLCA</code>
*/
public void testIndexLCA0() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_c ) );
}
public void testIndexLCA1() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_b ) );
}
public void testIndexLCA2() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_a, m_c ) );
}
public void testIndexLCA3() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_a ) );
}
public void testIndexLCA4() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
assertEquals( m_a, OntTools.getLCA( m_model, m_d, m_c ) );
}
public void testIndexLCA5() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_d ) );
}
public void testIndexLCA6() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_c.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_d, m_e ) );
}
public void testIndexLCA7() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_c.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_e, m_d ) );
}
public void testIndexLCA8() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_d.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_c, m_e ) );
}
public void testIndexLCA9() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_b.addSubClass( m_d );
m_d.addSubClass( m_e );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_c ) );
}
public void testIndexLCA10() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_e ) );
}
public void testIndexLCA11() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_a, OntTools.getLCA( m_model, m_b, m_f ) );
}
public void testIndexLCA12() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_d.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_d, OntTools.getLCA( m_model, m_f, m_e ) );
}
public void testIndexLCA13() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_c.addSubClass( m_e );
m_d.addSubClass( m_e );
m_d.addSubClass( m_f );
assertEquals( m_d, OntTools.getLCA( m_model, m_f, m_e ) );
}
/** Disconnected trees */
public void testIndexLCA14() {
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_b, m_e ) );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_c, m_e ) );
assertEquals( OWL.Thing, OntTools.getLCA( m_model, m_a, m_e ) );
}
/** Shortest path tests */
public void testShortestPath0() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_b );
testPath( OntTools.findShortestPath( m_model, m_a, m_b, Filter.any ),
new Property[] {p} );
}
public void testShortestPath1() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, Filter.any ),
new Property[] {p,p} );
}
public void testShortestPath2() {
Property p = m_model.createProperty( NS + "p" );
// a - b - c
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
// a - d - e - f
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, Filter.any ),
new Property[] {p,p} );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, Filter.any ),
new Property[] {p,p,p} );
}
public void testShortestPath3() {
Property p = m_model.createProperty( NS + "p" );
// a - b - c
m_a.addProperty( p, m_b );
m_b.addProperty( p, m_c );
// a - d - e - f
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p} );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p,p} );
}
public void testShortestPath4() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - b - c by q
m_a.addProperty( q, m_b );
m_b.addProperty( q, m_c );
// a - d - e - f by p
m_a.addProperty( p, m_d );
m_d.addProperty( p, m_e );
m_e.addProperty( p, m_f );
assertNull( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( p ) ) );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( p ) ),
new Property[] {p,p,p} );
}
/** Reflexive loop is allowed */
public void testShortestPath5() {
Property p = m_model.createProperty( NS + "p" );
m_a.addProperty( p, m_a );
testPath( OntTools.findShortestPath( m_model, m_a, m_a, Filter.any ),
new Property[] {p} );
}
public void testShortestPath6() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - b - a by q
// tests loop detection
m_a.addProperty( q, m_b );
m_b.addProperty( q, m_a );
assertNull( OntTools.findShortestPath( m_model, m_a, m_c, new OntTools.PredicatesFilter( new Property[] {p,q} ) ) );
}
public void testShortestPath7() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - d - e - f by p and q
m_a.addProperty( p, m_d );
m_d.addProperty( q, m_e );
m_d.addProperty( q, m_b );
m_e.addProperty( p, m_f );
testPath( OntTools.findShortestPath( m_model, m_a, m_f, new OntTools.PredicatesFilter( new Property[] {p,q} ) ),
new Property[] {p,q,p} );
}
/** Find a literal target */
public void testShortestPath8() {
Property p = m_model.createProperty( NS + "p" );
Property q = m_model.createProperty( NS + "q" );
// a - d - e - f by p and q
m_a.addProperty( p, m_d );
m_d.addProperty( q, m_e );
m_d.addProperty( q, "bluff" );
m_d.addProperty( q, m_b );
m_e.addProperty( p, m_f );
m_f.addProperty( q, "arnie" );
testPath( OntTools.findShortestPath( m_model, m_a, ResourceFactory.createPlainLiteral( "arnie" ),
new OntTools.PredicatesFilter( new Property[] {p,q} ) ),
new Property[] {p,q,p,q} );
}
/** Tests on {@link OntTools#namedHierarchyRoots(OntModel)} */
public void testNamedHierarchyRoots0() {
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
public void testNamedHierarchyRoots1() {
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
OntClass anon0 = m_model.createClass();
anon0.addSubClass( m_a );
anon0.addSubClass( m_e );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
public void testNamedHierarchyRoots2() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon0.addSubClass( m_e );
anon0.addSubClass( anon1 );
anon1.addSubClass( m_g );
m_a.addSubClass( m_b );
m_b.addSubClass( m_c );
m_c.addSubClass( m_d );
m_e.addSubClass( m_e );
m_e.addSubClass( m_f );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 3, nhr.size() );
assertTrue( nhr.contains( m_a ));
assertTrue( nhr.contains( m_e ));
assertTrue( nhr.contains( m_g ));
}
/** Test for no dups in the returned list */
public void testNamedHierarchyRoots3() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon1.addSubClass( m_a );
// only a is root
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_a.addSubClass( m_e );
m_a.addSubClass( m_f );
m_a.addSubClass( m_g );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 1, nhr.size() );
assertTrue( nhr.contains( m_a ));
}
/** Test for indirect route to a non-root node */
public void testNamedHierarchyRoots4() {
OntClass anon0 = m_model.createClass();
OntClass anon1 = m_model.createClass();
anon0.addSubClass( m_a );
anon1.addSubClass( m_b );
// only a is root, because b is a subclass of a
// even though b is a sub-class of an anon root
m_a.addSubClass( m_b );
m_a.addSubClass( m_c );
m_a.addSubClass( m_d );
m_a.addSubClass( m_e );
m_a.addSubClass( m_f );
m_a.addSubClass( m_g );
List nhr = OntTools.namedHierarchyRoots( m_model );
assertEquals( 1, nhr.size() );
assertTrue( nhr.contains( m_a ));
}
// Internal implementation methods
//////////////////////////////////
private void testPath( OntTools.Path path, Property[] expected ) {
assertEquals( expected.length, path.size() );
int i = 0;
Iterator j = path.iterator();
while (j.hasNext()) {
assertEquals( "path position: " + i, expected[i], ((Statement) j.next()).getPredicate() );
i++;
}
}
//==============================================================================
// Inner class definitions
//==============================================================================
}
/*
(c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| Filter.any has been deprecated in favour of Filter.any() which can do some type inference.
Consequent changes in the code.
git-svn-id: 227c23bb629cf7bef445105b977924772e49ae4f@1113657 13f79535-47bb-0310-9956-ffa450edef68
| src/com/hp/hpl/jena/ontology/impl/test/TestOntTools.java | Filter.any has been deprecated in favour of Filter.any() which can do some type inference. | <ide><path>rc/com/hp/hpl/jena/ontology/impl/test/TestOntTools.java
<ide> }
<ide>
<ide> /** Shortest path tests */
<add>
<add> static final Filter<Statement> ANY = Filter.any();
<ide>
<ide> public void testShortestPath0() {
<ide> Property p = m_model.createProperty( NS + "p" );
<ide> m_a.addProperty( p, m_b );
<ide>
<del> testPath( OntTools.findShortestPath( m_model, m_a, m_b, Filter.any ),
<add> testPath( OntTools.findShortestPath( m_model, m_a, m_b, ANY ),
<ide> new Property[] {p} );
<ide> }
<ide>
<ide> m_a.addProperty( p, m_b );
<ide> m_b.addProperty( p, m_c );
<ide>
<del> testPath( OntTools.findShortestPath( m_model, m_a, m_c, Filter.any ),
<add> testPath( OntTools.findShortestPath( m_model, m_a, m_c, ANY ),
<ide> new Property[] {p,p} );
<ide> }
<ide>
<ide> m_d.addProperty( p, m_e );
<ide> m_e.addProperty( p, m_f );
<ide>
<del> testPath( OntTools.findShortestPath( m_model, m_a, m_c, Filter.any ),
<add> testPath( OntTools.findShortestPath( m_model, m_a, m_c, ANY ),
<ide> new Property[] {p,p} );
<del> testPath( OntTools.findShortestPath( m_model, m_a, m_f, Filter.any ),
<add> testPath( OntTools.findShortestPath( m_model, m_a, m_f, ANY ),
<ide> new Property[] {p,p,p} );
<ide> }
<ide>
<ide> Property p = m_model.createProperty( NS + "p" );
<ide> m_a.addProperty( p, m_a );
<ide>
<del> testPath( OntTools.findShortestPath( m_model, m_a, m_a, Filter.any ),
<add> testPath( OntTools.findShortestPath( m_model, m_a, m_a, ANY ),
<ide> new Property[] {p} );
<ide> }
<ide> |
|
Java | agpl-3.0 | a4b078480b23518b8211fc776ce257e4c6d421ef | 0 | ProtocolSupport/ProtocolSupport | package protocolsupport.protocol.packet.middle.clientbound.play;
import io.netty.buffer.ByteBuf;
import protocolsupport.api.chat.ChatAPI;
import protocolsupport.api.chat.components.BaseComponent;
import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket;
import protocolsupport.protocol.serializer.StringSerializer;
import protocolsupport.protocol.typeremapper.basic.GenericIdSkipper;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupport.protocol.utils.types.WindowType;
import protocolsupport.utils.Utils;
import protocolsupport.zplatform.ServerPlatform;
public abstract class MiddleInventoryOpen extends ClientBoundMiddlePacket {
public MiddleInventoryOpen(ConnectionImpl connection) {
super(connection);
}
protected int windowId;
protected WindowType type;
protected BaseComponent title;
protected int slots;
protected int horseId;
@Override
public void readFromServerData(ByteBuf serverdata) {
windowId = serverdata.readUnsignedByte();
type = WindowType.getById(StringSerializer.readString(serverdata, ProtocolVersionsHelper.LATEST_PC, 32));
title = ChatAPI.fromJSON(StringSerializer.readString(serverdata, ProtocolVersionsHelper.LATEST_PC));
slots = serverdata.readUnsignedByte();
if (type == WindowType.HORSE) {
horseId = serverdata.readInt();
}
}
@Override
public boolean postFromServerRead() {
cache.getWindowCache().setOpenedWindow(type);
if (GenericIdSkipper.INVENTORY.getTable(connection.getVersion()).shouldSkip(type)) {
connection.receivePacket(ServerPlatform.get().getPacketFactory().createInboundInventoryClosePacket());
return false;
} else {
return true;
}
}
protected String getLegacyTitle() {
return Utils.clampString(title.toLegacyText(cache.getAttributesCache().getLocale()), 32);
}
}
| src/protocolsupport/protocol/packet/middle/clientbound/play/MiddleInventoryOpen.java | package protocolsupport.protocol.packet.middle.clientbound.play;
import io.netty.buffer.ByteBuf;
import protocolsupport.api.chat.ChatAPI;
import protocolsupport.api.chat.components.BaseComponent;
import protocolsupport.protocol.ConnectionImpl;
import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket;
import protocolsupport.protocol.serializer.StringSerializer;
import protocolsupport.protocol.typeremapper.basic.GenericIdSkipper;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupport.protocol.utils.types.WindowType;
import protocolsupport.utils.Utils;
import protocolsupport.zplatform.ServerPlatform;
public abstract class MiddleInventoryOpen extends ClientBoundMiddlePacket {
public MiddleInventoryOpen(ConnectionImpl connection) {
super(connection);
}
protected int windowId;
protected WindowType type;
protected BaseComponent title;
protected int slots;
protected int horseId;
@Override
public void readFromServerData(ByteBuf serverdata) {
windowId = serverdata.readUnsignedByte();
type = WindowType.getById(StringSerializer.readString(serverdata, ProtocolVersionsHelper.LATEST_PC, 32));
title = ChatAPI.fromJSON(StringSerializer.readString(serverdata, ProtocolVersionsHelper.LATEST_PC));
slots = serverdata.readUnsignedByte();
if (type == WindowType.HORSE) {
horseId = serverdata.readInt();
}
}
@Override
public boolean postFromServerRead() {
cache.getWindowCache().setOpenedWindow(type);
if (GenericIdSkipper.INVENTORY.getTable(connection.getVersion()).shouldSkip(type)) {
connection.receivePacket(ServerPlatform.get().getPacketFactory().createInboundInventoryClosePacket());
return false;
} else {
return true;
}
}
protected String getLegacyTitle() {
switch (type) {
// Title users
case CHEST:
case FURNACE:
case DISPENSER:
case BREWING:
case VILLAGER:
case BEACON:
case HOPPER:
return Utils.clampString(title.toLegacyText(cache.getAttributesCache().getLocale()), 32);
default:
return "";
}
}
}
| Makes just clamping
| src/protocolsupport/protocol/packet/middle/clientbound/play/MiddleInventoryOpen.java | Makes just clamping | <ide><path>rc/protocolsupport/protocol/packet/middle/clientbound/play/MiddleInventoryOpen.java
<ide> }
<ide>
<ide> protected String getLegacyTitle() {
<del> switch (type) {
<del> // Title users
<del> case CHEST:
<del> case FURNACE:
<del> case DISPENSER:
<del> case BREWING:
<del> case VILLAGER:
<del> case BEACON:
<del> case HOPPER:
<del> return Utils.clampString(title.toLegacyText(cache.getAttributesCache().getLocale()), 32);
<del> default:
<del> return "";
<del> }
<add> return Utils.clampString(title.toLegacyText(cache.getAttributesCache().getLocale()), 32);
<ide> }
<ide> } |
|
Java | mit | error: pathspec 'ifs-web-service/ifs-application-service/src/main/java/com/worth/ifs/alert/AlertController.java' did not match any file(s) known to git
| b7a5f4405b95e3a6a2c9006c80ec136113de12a3 | 1 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package com.worth.ifs.alert;
import com.worth.ifs.alert.resource.AlertResource;
import com.worth.ifs.alert.resource.AlertType;
import com.worth.ifs.application.service.AlertService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rvanrumpt on 18/05/16.
*/
@Controller
@RequestMapping("/alert")
public class AlertController {
@Autowired
AlertService alertService;
private static Log LOG = LogFactory.getLog(AlertController.class);
@RequestMapping(value = "/findAllVisibleByType/{type}", method = RequestMethod.GET)
public @ResponseBody
List<AlertResource> getAlertByTypeJSON(@PathVariable("type") String type) {
List<AlertResource> alerts = new ArrayList();
try {
AlertType alertType = AlertType.valueOf(type.toUpperCase());
alerts = alertService.findAllVisibleByType(alertType);
} catch (IllegalArgumentException e) {
LOG.debug(e.getMessage());
}
return alerts;
}
}
| ifs-web-service/ifs-application-service/src/main/java/com/worth/ifs/alert/AlertController.java | INFUND-2901 Controller that returns AlertMessages in JSON via the weblayer
| ifs-web-service/ifs-application-service/src/main/java/com/worth/ifs/alert/AlertController.java | INFUND-2901 Controller that returns AlertMessages in JSON via the weblayer | <ide><path>fs-web-service/ifs-application-service/src/main/java/com/worth/ifs/alert/AlertController.java
<add>package com.worth.ifs.alert;
<add>
<add>import com.worth.ifs.alert.resource.AlertResource;
<add>import com.worth.ifs.alert.resource.AlertType;
<add>import com.worth.ifs.application.service.AlertService;
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.stereotype.Controller;
<add>import org.springframework.web.bind.annotation.PathVariable;
<add>import org.springframework.web.bind.annotation.RequestMapping;
<add>import org.springframework.web.bind.annotation.RequestMethod;
<add>import org.springframework.web.bind.annotation.ResponseBody;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Created by rvanrumpt on 18/05/16.
<add> */
<add>
<add>
<add>@Controller
<add>@RequestMapping("/alert")
<add>public class AlertController {
<add>
<add> @Autowired
<add> AlertService alertService;
<add>
<add> private static Log LOG = LogFactory.getLog(AlertController.class);
<add>
<add> @RequestMapping(value = "/findAllVisibleByType/{type}", method = RequestMethod.GET)
<add> public @ResponseBody
<add> List<AlertResource> getAlertByTypeJSON(@PathVariable("type") String type) {
<add> List<AlertResource> alerts = new ArrayList();
<add>
<add> try {
<add> AlertType alertType = AlertType.valueOf(type.toUpperCase());
<add> alerts = alertService.findAllVisibleByType(alertType);
<add> } catch (IllegalArgumentException e) {
<add> LOG.debug(e.getMessage());
<add> }
<add>
<add> return alerts;
<add> }
<add>} |
|
Java | apache-2.0 | 9d7e6d20a6fd1ce89fc3d7cf4d443a59e7716f0c | 0 | nikeshmhr/unitime,maciej-zygmunt/unitime,maciej-zygmunt/unitime,rafati/unitime,rafati/unitime,sktoo/timetabling-system-,nikeshmhr/unitime,UniTime/unitime,maciej-zygmunt/unitime,sktoo/timetabling-system-,zuzanamullerova/unitime,zuzanamullerova/unitime,rafati/unitime,UniTime/unitime,nikeshmhr/unitime,zuzanamullerova/unitime,sktoo/timetabling-system-,UniTime/unitime | /**
*
*/
package org.unitime.timetable.util;
import java.io.StringReader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Properties;
import net.sf.cpsolver.ifs.util.ToolBox;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.hibernate.engine.SessionFactoryImplementor;
import org.unitime.commons.Debug;
import org.unitime.commons.hibernate.util.HibernateUtil;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.dataexchange.DataExchangeHelper;
import org.unitime.timetable.model.dao._RootDAO;
/**
* @author says
*
*/
public class ImportXmlFromDB {
public static void importXml(String baseFileName){
Debug.info("filename = " + baseFileName);
try {
String fileReceiveSql =
ApplicationProperties.getProperty("tmtbl.data.exchange.receive.file","{?= call timetable.receive_xml_file.receive_file(?, ?)}");
String exchangeDir =
ApplicationProperties.getProperty("tmtbl.data.exchange.directory", "LOAD_SMASDEV");
SessionFactoryImplementor hibSessionFactory = (SessionFactoryImplementor)new _RootDAO().getSession().getSessionFactory();
Connection connection = hibSessionFactory.getConnectionProvider().getConnection();
CallableStatement call = connection.prepareCall(fileReceiveSql);
call.registerOutParameter(1, java.sql.Types.CLOB);
call.setString(2, exchangeDir);
call.setString(3, baseFileName);
call.execute();
String response = call.getString(1);
call.close();
hibSessionFactory.getConnectionProvider().closeConnection(connection);
if (response==null || response.length()==0) return;
StringReader reader = new StringReader(response);
Document document = (new SAXReader()).read(reader);
reader.close();
DataExchangeHelper.importDocument(document, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args){
try{
ToolBox.configureLogging();
if (args[0].length() == 0){
throw(new Exception("Please specify a base file name to which '.xml' and '.ready' can be appended."));
}
Properties properties = new Properties();
properties.put("connection.url", args[1]);
HibernateUtil.configureHibernate(properties);
importXml(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| JavaSource/org/unitime/timetable/util/ImportXmlFromDB.java | /**
*
*/
package org.unitime.timetable.util;
import java.io.FileInputStream;
import java.io.StringReader;
import java.net.URL;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Iterator;
import java.util.Properties;
import net.sf.cpsolver.ifs.util.ToolBox;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.hibernate.engine.SessionFactoryImplementor;
import org.unitime.commons.Debug;
import org.unitime.commons.hibernate.util.HibernateUtil;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.dataexchange.DataExchangeHelper;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.solver.remote.core.RemoteSolverServer;
/**
* @author says
*
*/
public class ImportXmlFromDB {
public static void importXml(String baseFileName){
Debug.info("filename = " + baseFileName);
try {
String fileReceiveSql =
ApplicationProperties.getProperty("tmtbl.data.exchange.receive.file","{?= call timetable.receive_xml_file.receive_file(?, ?)}");
String exchangeDir =
ApplicationProperties.getProperty("tmtbl.data.exchange.directory", "LOAD_SMASDEV");
SessionFactoryImplementor hibSessionFactory = (SessionFactoryImplementor)new _RootDAO().getSession().getSessionFactory();
Connection connection = hibSessionFactory.getConnectionProvider().getConnection();
CallableStatement call = connection.prepareCall(fileReceiveSql);
call.registerOutParameter(1, java.sql.Types.CLOB);
call.setString(2, exchangeDir);
call.setString(3, baseFileName);
call.execute();
String response = call.getString(1);
call.close();
hibSessionFactory.getConnectionProvider().closeConnection(connection);
if (response==null || response.length()==0) return;
StringReader reader = new StringReader(response);
Document document = (new SAXReader()).read(reader);
reader.close();
DataExchangeHelper.importDocument(document, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args){
try{
ToolBox.configureLogging();
if (args[0].length() == 0){
throw(new Exception("Please specify a base file name to which '.xml' and '.ready' can be appended."));
}
Properties properties = new Properties();
properties.put("connection.url", args[1]);
HibernateUtil.configureHibernate(properties);
importXml(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| removed unused imports
| JavaSource/org/unitime/timetable/util/ImportXmlFromDB.java | removed unused imports | <ide><path>avaSource/org/unitime/timetable/util/ImportXmlFromDB.java
<ide> */
<ide> package org.unitime.timetable.util;
<ide>
<del>import java.io.FileInputStream;
<ide> import java.io.StringReader;
<del>import java.net.URL;
<ide> import java.sql.CallableStatement;
<ide> import java.sql.Connection;
<del>import java.util.Iterator;
<ide> import java.util.Properties;
<ide>
<ide> import net.sf.cpsolver.ifs.util.ToolBox;
<ide> import org.unitime.timetable.ApplicationProperties;
<ide> import org.unitime.timetable.dataexchange.DataExchangeHelper;
<ide> import org.unitime.timetable.model.dao._RootDAO;
<del>import org.unitime.timetable.solver.remote.core.RemoteSolverServer;
<ide>
<ide>
<ide> |
|
Java | apache-2.0 | 9640c5ca165bb1d51b6af408e5b90bb572f32a8c | 0 | wyzssw/orientdb,allanmoso/orientdb,allanmoso/orientdb,joansmith/orientdb,orientechnologies/orientdb,alonsod86/orientdb,tempbottle/orientdb,rprabhat/orientdb,cstamas/orientdb,cstamas/orientdb,intfrr/orientdb,tempbottle/orientdb,joansmith/orientdb,orientechnologies/orientdb,intfrr/orientdb,mmacfadden/orientdb,alonsod86/orientdb,tempbottle/orientdb,joansmith/orientdb,intfrr/orientdb,mmacfadden/orientdb,allanmoso/orientdb,jdillon/orientdb,orientechnologies/orientdb,sanyaade-g2g-repos/orientdb,wouterv/orientdb,alonsod86/orientdb,mmacfadden/orientdb,mbhulin/orientdb,giastfader/orientdb,giastfader/orientdb,cstamas/orientdb,mbhulin/orientdb,mbhulin/orientdb,intfrr/orientdb,wouterv/orientdb,joansmith/orientdb,jdillon/orientdb,wyzssw/orientdb,jdillon/orientdb,giastfader/orientdb,rprabhat/orientdb,wouterv/orientdb,allanmoso/orientdb,wouterv/orientdb,alonsod86/orientdb,tempbottle/orientdb,rprabhat/orientdb,mbhulin/orientdb,rprabhat/orientdb,wyzssw/orientdb,giastfader/orientdb,sanyaade-g2g-repos/orientdb,sanyaade-g2g-repos/orientdb,wyzssw/orientdb,cstamas/orientdb,sanyaade-g2g-repos/orientdb,orientechnologies/orientdb,mmacfadden/orientdb | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.object.db;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyObject;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.object.ODatabaseObject;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.entity.OEntityManager;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.security.ODatabaseSecurityResources;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.tx.OTransactionNoTx;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.object.dictionary.ODictionaryWrapper;
import com.orientechnologies.orient.object.enhancement.OObjectEntityEnhancer;
import com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer;
import com.orientechnologies.orient.object.enhancement.OObjectMethodFilter;
import com.orientechnologies.orient.object.enhancement.OObjectProxyMethodHandler;
import com.orientechnologies.orient.object.entity.OObjectEntityClassHandler;
import com.orientechnologies.orient.object.iterator.OObjectIteratorClass;
import com.orientechnologies.orient.object.iterator.OObjectIteratorCluster;
import com.orientechnologies.orient.object.serialization.OObjectSerializerHelper;
/**
* Object Database instance. It's a wrapper to the class ODatabaseDocumentTx that handles conversion between ODocument instances and
* POJOs using javassist APIs.
*
* @see ODatabaseDocumentTx
* @author Luca Molino
*/
@SuppressWarnings("unchecked")
public class OObjectDatabaseTx extends ODatabasePojoAbstract<Object> implements ODatabaseObject, OUserObject2RecordHandler {
public static final String TYPE = "object";
protected ODictionary<Object> dictionary;
protected OEntityManager entityManager;
protected boolean saveOnlyDirty;
protected boolean lazyLoading;
public OObjectDatabaseTx(final String iURL) {
super(new ODatabaseDocumentTx(iURL));
underlying.setDatabaseOwner(this);
init();
}
public <T> T newInstance(final Class<T> iType) {
return (T) newInstance(iType.getSimpleName(), null, new Object[0]);
}
public <T> T newInstance(final Class<T> iType, Object... iArgs) {
return (T) newInstance(iType.getSimpleName(), null, iArgs);
}
public <RET> RET newInstance(String iClassName) {
return (RET) newInstance(iClassName, null, new Object[0]);
}
@Override
public <THISDB extends ODatabase> THISDB open(String iUserName, String iUserPassword) {
super.open(iUserName, iUserPassword);
entityManager.registerEntityClass(OUser.class);
entityManager.registerEntityClass(ORole.class);
return (THISDB) this;
}
/**
* Create a new POJO by its class name. Assure to have called the registerEntityClasses() declaring the packages that are part of
* entity classes.
*
* @see OEntityManager#registerEntityClasses(String)
*/
public <RET extends Object> RET newInstance(final String iClassName, final Object iEnclosingClass, Object... iArgs) {
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName);
try {
RET enhanced = (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(entityManager.getEntityClass(iClassName),
iEnclosingClass, underlying.newInstance(iClassName), null, iArgs);
return (RET) enhanced;
} catch (Exception e) {
OLogManager.instance().error(this, "Error on creating object of class " + iClassName, e, ODatabaseException.class);
}
return null;
}
/**
* Create a new POJO by its class name. Assure to have called the registerEntityClasses() declaring the packages that are part of
* entity classes.
*
* @see OEntityManager#registerEntityClasses(String)
*/
public <RET extends Object> RET newInstance(final String iClassName, final Object iEnclosingClass, ODocument iDocument,
Object... iArgs) {
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName);
try {
RET enhanced = (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(entityManager.getEntityClass(iClassName),
iEnclosingClass, iDocument, null, iArgs);
return (RET) enhanced;
} catch (Exception e) {
OLogManager.instance().error(this, "Error on creating object of class " + iClassName, e, ODatabaseException.class);
}
return null;
}
public <RET> OObjectIteratorClass<RET> browseClass(final Class<RET> iClusterClass) {
return browseClass(iClusterClass, true);
}
public <RET> OObjectIteratorClass<RET> browseClass(final Class<RET> iClusterClass, final boolean iPolymorphic) {
if (iClusterClass == null)
return null;
return browseClass(iClusterClass.getSimpleName(), iPolymorphic);
}
public <RET> OObjectIteratorClass<RET> browseClass(final String iClassName) {
return browseClass(iClassName, true);
}
public <RET> OObjectIteratorClass<RET> browseClass(final String iClassName, final boolean iPolymorphic) {
checkOpeness();
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_READ, iClassName);
return new OObjectIteratorClass<RET>(this, (ODatabaseRecordAbstract) getUnderlying().getUnderlying(), iClassName, iPolymorphic);
}
public <RET> OObjectIteratorCluster<RET> browseCluster(final String iClusterName) {
checkOpeness();
checkSecurity(ODatabaseSecurityResources.CLUSTER, ORole.PERMISSION_READ, iClusterName);
return (OObjectIteratorCluster<RET>) new OObjectIteratorCluster<Object>(this, (ODatabaseRecordAbstract) getUnderlying()
.getUnderlying(), getClusterIdByName(iClusterName));
}
public <RET> RET load(final Object iPojo) {
return (RET) load(iPojo, null);
}
public <RET> RET reload(final Object iPojo) {
return (RET) reload(iPojo, null, true);
}
public <RET> RET reload(final Object iPojo, final boolean iIgnoreCache) {
return (RET) reload(iPojo, null, iIgnoreCache);
}
public <RET> RET reload(Object iPojo, final String iFetchPlan, final boolean iIgnoreCache) {
checkOpeness();
if (iPojo == null)
return null;
// GET THE ASSOCIATED DOCUMENT
final ODocument record = getRecordByUserObject(iPojo, true);
underlying.reload(record, iFetchPlan, iIgnoreCache);
iPojo = stream2pojo(record, iPojo, iFetchPlan, true);
return (RET) iPojo;
}
public <RET> RET load(final Object iPojo, final String iFetchPlan) {
return (RET) load(iPojo, iFetchPlan, false);
}
@Override
public void attach(final Object iPojo) {
OObjectEntitySerializer.attach(iPojo, this);
}
public <RET> RET attachAndSave(final Object iPojo) {
attach(iPojo);
return (RET) save(iPojo);
}
@Override
/**
* Method that detaches all fields contained in the document to the given object. It returns by default a proxied instance. To get
* a detached non proxied instance @see {@link OObjectEntitySerializer.detach(T o, ODatabaseObject db, boolean
* returnNonProxiedInstance)}
*
* @param <T>
* @param o
* :- the object to detach
* @return the detached object
*/
public <RET> RET detach(final Object iPojo) {
return (RET) OObjectEntitySerializer.detach(iPojo, this);
}
/**
* Method that detaches all fields contained in the document to the given object.
*
* @param <RET>
* @param iPojo
* :- the object to detach
* @param returnNonProxiedInstance
* :- defines if the return object will be a proxied instance or not. If set to TRUE and the object does not contains @Id
* and @Version fields it could procude data replication
* @return the object serialized or with detached data
*/
public <RET> RET detach(final Object iPojo, boolean returnNonProxiedInstance) {
return (RET) OObjectEntitySerializer.detach(iPojo, this, returnNonProxiedInstance);
}
/**
* Method that detaches all fields contained in the document to the given object and recursively all object tree. This may throw a
* {@link StackOverflowError} with big objects tree. To avoid it set the stack size with -Xss java option
*
* @param <RET>
* @param iPojo
* :- the object to detach
* @param returnNonProxiedInstance
* :- defines if the return object will be a proxied instance or not. If set to TRUE and the object does not contains @Id
* and @Version fields it could procude data replication
* @return the object serialized or with detached data
*/
public <RET> RET detachAll(final Object iPojo, boolean returnNonProxiedInstance) {
return (RET) OObjectEntitySerializer.detachAll(iPojo, this, returnNonProxiedInstance);
}
public <RET> RET load(final Object iPojo, final String iFetchPlan, final boolean iIgnoreCache) {
return (RET) load(iPojo, iFetchPlan, iIgnoreCache, false);
}
@Override
public <RET> RET load(Object iPojo, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
checkOpeness();
if (iPojo == null)
return null;
// GET THE ASSOCIATED DOCUMENT
ODocument record = getRecordByUserObject(iPojo, true);
try {
record.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
record = underlying.load(record, iFetchPlan, iIgnoreCache, loadTombstone);
return (RET) stream2pojo(record, iPojo, iFetchPlan);
} finally {
record.setInternalStatus(ORecordElement.STATUS.LOADED);
}
}
public <RET> RET load(final ORID iRecordId) {
return (RET) load(iRecordId, null);
}
public <RET> RET load(final ORID iRecordId, final String iFetchPlan) {
return (RET) load(iRecordId, iFetchPlan, false);
}
public <RET> RET load(final ORID iRecordId, final String iFetchPlan, final boolean iIgnoreCache) {
return (RET) load(iRecordId, iFetchPlan, iIgnoreCache, false);
}
@Override
public <RET> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
checkOpeness();
if (iRecordId == null)
return null;
// GET THE ASSOCIATED DOCUMENT
final ODocument record = (ODocument) underlying.load(iRecordId, iFetchPlan, iIgnoreCache, loadTombstone);
if (record == null)
return null;
return (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(record.getClassName(), entityManager, record, null);
}
/**
* Saves an object to the databasein synchronous mode . First checks if the object is new or not. In case it's new a new ODocument
* is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is introspected using the Java
* Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*/
public <RET> RET save(final Object iContent) {
return (RET) save(iContent, (String) null, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
/**
* Saves an object to the database specifying the mode. First checks if the object is new or not. In case it's new a new ODocument
* is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is introspected using the Java
* Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*/
public <RET> RET save(final Object iContent, OPERATION_MODE iMode, boolean iForceCreate,
final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
return (RET) save(iContent, null, iMode, false, iRecordCreatedCallback, iRecordUpdatedCallback);
}
/**
* Saves an object in synchronous mode to the database forcing a record cluster where to store it. First checks if the object is
* new or not. In case it's new a new ODocument is created and bound to the object, otherwise the ODocument is retrieved and
* updated. The object is introspected using the Java Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*
* Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
* following the constraints declared in the schema.
*
* @see ORecordSchemaAware#validate()
*/
public <RET> RET save(final Object iPojo, final String iClusterName) {
return (RET) save(iPojo, iClusterName, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
@Override
public boolean updatedReplica(Object iPojo) {
OSerializationThreadLocal.INSTANCE.get().clear();
// GET THE ASSOCIATED DOCUMENT
final Object proxiedObject = OObjectEntitySerializer.serializeObject(iPojo, this);
final ODocument record = getRecordByUserObject(proxiedObject, true);
boolean result;
try {
record.setInternalStatus(com.orientechnologies.orient.core.db.record.ORecordElement.STATUS.MARSHALLING);
result = underlying.updatedReplica(record);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).updateLoadedFieldMap(proxiedObject);
// RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
registerUserObject(proxiedObject, record);
} finally {
record.setInternalStatus(com.orientechnologies.orient.core.db.record.ORecordElement.STATUS.LOADED);
}
return result;
}
/**
* Saves an object to the database forcing a record cluster where to store it. First checks if the object is new or not. In case
* it's new a new ODocument is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is
* introspected using the Java Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*
* Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
* following the constraints declared in the schema.
*
* @see ORecordSchemaAware#validate()
*/
public <RET> RET save(final Object iPojo, final String iClusterName, OPERATION_MODE iMode, boolean iForceCreate,
final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
checkOpeness();
if (iPojo == null)
return (RET) iPojo;
else if (OMultiValue.isMultiValue(iPojo)) {
// MULTI VALUE OBJECT: STORE SINGLE POJOS
for (Object pojo : OMultiValue.getMultiValueIterable(iPojo)) {
save(pojo, iClusterName);
}
return (RET) iPojo;
} else {
OSerializationThreadLocal.INSTANCE.get().clear();
// GET THE ASSOCIATED DOCUMENT
final Object proxiedObject = OObjectEntitySerializer.serializeObject(iPojo, this);
final ODocument record = getRecordByUserObject(proxiedObject, true);
try {
record.setInternalStatus(ORecordElement.STATUS.MARSHALLING);
if (!saveOnlyDirty || record.isDirty()) {
// REGISTER BEFORE TO SERIALIZE TO AVOID PROBLEMS WITH CIRCULAR DEPENDENCY
// registerUserObject(iPojo, record);
deleteOrphans((((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler())));
ODocument savedRecord = underlying.save(record, iClusterName, iMode, iForceCreate, iRecordCreatedCallback,
iRecordUpdatedCallback);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).setDoc(savedRecord);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).updateLoadedFieldMap(proxiedObject);
// RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
registerUserObject(proxiedObject, record);
}
} finally {
record.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return (RET) proxiedObject;
}
}
public ODatabaseObject delete(final Object iPojo) {
checkOpeness();
if (iPojo == null)
return this;
ODocument record = getRecordByUserObject(iPojo, false);
if (record == null) {
final ORecordId rid = OObjectSerializerHelper.getObjectID(this, iPojo);
if (rid == null)
throw new OObjectNotDetachedException("Cannot retrieve the object's ID for '" + iPojo + "' because has not been detached");
record = (ODocument) underlying.load(rid);
}
deleteCascade(record);
underlying.delete(record);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, record);
return this;
}
@Override
public ODatabaseObject delete(final ORID iRID) {
checkOpeness();
if (iRID == null)
return this;
final ORecordInternal<?> record = iRID.getRecord();
if (record instanceof ODocument) {
Object iPojo = getUserObjectByRecord(record, null);
deleteCascade((ODocument) record);
underlying.delete(record);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, (ODocument) record);
}
return this;
}
@Override
public ODatabaseObject delete(final ORID iRID, final ORecordVersion iVersion) {
deleteRecord(iRID, iVersion, false);
return this;
}
@Override
public ODatabaseComplex<Object> cleanOutRecord(ORID iRID, ORecordVersion iVersion) {
deleteRecord(iRID, iVersion, true);
return this;
}
private boolean deleteRecord(ORID iRID, ORecordVersion iVersion, boolean prohibitTombstones) {
checkOpeness();
if (iRID == null)
return true;
ODocument record = iRID.getRecord();
if (record != null) {
Object iPojo = getUserObjectByRecord(record, null);
deleteCascade(record);
if (prohibitTombstones)
underlying.cleanOutRecord(iRID, iVersion);
else
underlying.delete(iRID, iVersion);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, record);
}
return false;
}
protected void deleteCascade(final ODocument record) {
if (record == null)
return;
List<String> toDeleteCascade = OObjectEntitySerializer.getCascadeDeleteFields(record.getClassName());
if (toDeleteCascade != null) {
for (String field : toDeleteCascade) {
Object toDelete = record.field(field);
if (toDelete instanceof OIdentifiable) {
if (toDelete != null)
delete(((OIdentifiable) toDelete).getIdentity());
} else if (toDelete instanceof Collection) {
for (OIdentifiable cascadeRecord : ((Collection<OIdentifiable>) toDelete)) {
if (cascadeRecord != null)
delete(((OIdentifiable) cascadeRecord).getIdentity());
}
} else if (toDelete instanceof Map) {
for (OIdentifiable cascadeRecord : ((Map<Object, OIdentifiable>) toDelete).values()) {
if (cascadeRecord != null)
delete(((OIdentifiable) cascadeRecord).getIdentity());
}
}
}
}
}
public long countClass(final String iClassName) {
checkOpeness();
return underlying.countClass(iClassName);
}
public long countClass(final Class<?> iClass) {
checkOpeness();
return underlying.countClass(iClass.getSimpleName());
}
public ODictionary<Object> getDictionary() {
checkOpeness();
if (dictionary == null)
dictionary = new ODictionaryWrapper(this, underlying.getDictionary().getIndex());
return dictionary;
}
@Override
public ODatabasePojoAbstract<Object> commit() {
try {
// BY PASS DOCUMENT DB
((ODatabaseRecordTx) underlying.getUnderlying()).commit();
if (getTransaction().getAllRecordEntries() != null) {
// UPDATE ID & VERSION FOR ALL THE RECORDS
Object pojo = null;
for (ORecordOperation entry : getTransaction().getAllRecordEntries()) {
switch (entry.type) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
break;
case ORecordOperation.DELETED:
final ORecordInternal<?> rec = entry.getRecord();
if (rec instanceof ODocument)
unregisterPojo(pojo, (ODocument) rec);
break;
}
}
}
} finally {
getTransaction().close();
}
return this;
}
@Override
public ODatabasePojoAbstract<Object> rollback() {
try {
// COPY ALL TX ENTRIES
final List<ORecordOperation> newEntries;
if (getTransaction().getCurrentRecordEntries() != null) {
newEntries = new ArrayList<ORecordOperation>();
for (ORecordOperation entry : getTransaction().getCurrentRecordEntries())
if (entry.type == ORecordOperation.CREATED)
newEntries.add(entry);
} else
newEntries = null;
// BY PASS DOCUMENT DB
((ODatabaseRecordTx) underlying.getUnderlying()).rollback();
} finally {
getTransaction().close();
}
return this;
}
public OEntityManager getEntityManager() {
return entityManager;
}
@Override
public ODatabaseDocument getUnderlying() {
return underlying;
}
/**
* Returns the version number of the object. Version starts from 0 assigned on creation.
*
* @param iPojo
* User object
*/
@Override
public ORecordVersion getVersion(final Object iPojo) {
checkOpeness();
final ODocument record = getRecordByUserObject(iPojo, false);
if (record != null)
return record.getRecordVersion();
return OObjectSerializerHelper.getObjectVersion(iPojo);
}
/**
* Returns the object unique identity.
*
* @param iPojo
* User object
*/
@Override
public ORID getIdentity(final Object iPojo) {
checkOpeness();
if (iPojo instanceof OIdentifiable)
return ((OIdentifiable) iPojo).getIdentity();
final ODocument record = getRecordByUserObject(iPojo, false);
if (record != null)
return record.getIdentity();
return OObjectSerializerHelper.getObjectID(this, iPojo);
}
public boolean isSaveOnlyDirty() {
return saveOnlyDirty;
}
public void setSaveOnlyDirty(boolean saveOnlyDirty) {
this.saveOnlyDirty = saveOnlyDirty;
}
public Object newInstance() {
checkOpeness();
return new ODocument();
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final byte iOperation) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation);
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final int iOperation, Object iResourceSpecific) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation, iResourceSpecific);
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final int iOperation, Object... iResourcesSpecific) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation, iResourcesSpecific);
}
@Override
public ODocument pojo2Stream(final Object iPojo, final ODocument iRecord) {
if (iPojo instanceof ProxyObject) {
return ((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).getDoc();
}
return OObjectSerializerHelper.toStream(iPojo, iRecord, getEntityManager(),
getMetadata().getSchema().getClass(iPojo.getClass().getSimpleName()), this, this, saveOnlyDirty);
}
@Override
public Object stream2pojo(ODocument iRecord, final Object iPojo, final String iFetchPlan) {
return stream2pojo(iRecord, iPojo, iFetchPlan, false);
}
public Object stream2pojo(ODocument iRecord, final Object iPojo, final String iFetchPlan, boolean iReload) {
if (iRecord.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED)
iRecord = (ODocument) iRecord.load();
if (iReload) {
if (iPojo != null) {
if (iPojo instanceof Proxy) {
((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).setDoc(iRecord);
((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).updateLoadedFieldMap(iPojo);
return iPojo;
} else
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iPojo.getClass(), iRecord);
} else
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iRecord.getClassName(), entityManager, iRecord, null);
} else if (!(iPojo instanceof Proxy))
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iPojo.getClass(), iRecord);
else
return iPojo;
}
public boolean isLazyLoading() {
return lazyLoading;
}
public void setLazyLoading(final boolean lazyLoading) {
this.lazyLoading = lazyLoading;
}
public String getType() {
return TYPE;
}
@Override
public ODocument getRecordByUserObject(Object iPojo, boolean iCreateIfNotAvailable) {
if (iPojo instanceof Proxy)
return OObjectEntitySerializer.getDocument((Proxy) iPojo);
return OObjectEntitySerializer.getDocument((Proxy) OObjectEntitySerializer.serializeObject(iPojo, this));
}
@Override
public Object getUserObjectByRecord(final OIdentifiable iRecord, final String iFetchPlan, final boolean iCreate) {
final ODocument document = iRecord.getRecord();
return OObjectEntityEnhancer.getInstance().getProxiedInstance(document.getClassName(), getEntityManager(), document, null);
}
@Override
public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) {
}
public void registerUserObjectAfterLinkSave(ORecordInternal<?> iRecord) {
}
@Override
public void unregisterPojo(final Object iObject, final ODocument iRecord) {
}
public void registerClassMethodFilter(Class<?> iClass, OObjectMethodFilter iMethodFilter) {
OObjectEntityEnhancer.getInstance().registerClassMethodFilter(iClass, iMethodFilter);
}
public void deregisterClassMethodFilter(final Class<?> iClass) {
OObjectEntityEnhancer.getInstance().deregisterClassMethodFilter(iClass);
}
protected void init() {
entityManager = OEntityManager.getEntityManagerByDatabaseURL(getURL());
entityManager.setClassHandler(OObjectEntityClassHandler.getInstance());
saveOnlyDirty = OGlobalConfiguration.OBJECT_SAVE_ONLY_DIRTY.getValueAsBoolean();
OObjectSerializerHelper.register();
lazyLoading = true;
if (!isClosed() && entityManager.getEntityClass(OUser.class.getSimpleName()) == null) {
entityManager.registerEntityClass(OUser.class);
entityManager.registerEntityClass(ORole.class);
}
}
protected void deleteOrphans(final OObjectProxyMethodHandler handler) {
for (ORID orphan : handler.getOrphans()) {
final ODocument doc = orphan.getRecord();
deleteCascade(doc);
underlying.delete(doc);
}
handler.getOrphans().clear();
}
}
| object/src/main/java/com/orientechnologies/orient/object/db/OObjectDatabaseTx.java | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.object.db;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyObject;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.object.ODatabaseObject;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.entity.OEntityManager;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.security.ODatabaseSecurityResources;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.tx.OTransactionNoTx;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.object.dictionary.ODictionaryWrapper;
import com.orientechnologies.orient.object.enhancement.OObjectEntityEnhancer;
import com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer;
import com.orientechnologies.orient.object.enhancement.OObjectMethodFilter;
import com.orientechnologies.orient.object.enhancement.OObjectProxyMethodHandler;
import com.orientechnologies.orient.object.entity.OObjectEntityClassHandler;
import com.orientechnologies.orient.object.iterator.OObjectIteratorClass;
import com.orientechnologies.orient.object.iterator.OObjectIteratorCluster;
import com.orientechnologies.orient.object.serialization.OObjectSerializerHelper;
/**
* Object Database instance. It's a wrapper to the class ODatabaseDocumentTx that handles conversion between ODocument instances and
* POJOs using javassist APIs.
*
* @see ODatabaseDocumentTx
* @author Luca Molino
*/
@SuppressWarnings("unchecked")
public class OObjectDatabaseTx extends ODatabasePojoAbstract<Object> implements ODatabaseObject, OUserObject2RecordHandler {
public static final String TYPE = "object";
protected ODictionary<Object> dictionary;
protected OEntityManager entityManager;
protected boolean saveOnlyDirty;
protected boolean lazyLoading;
public OObjectDatabaseTx(final String iURL) {
super(new ODatabaseDocumentTx(iURL));
underlying.setDatabaseOwner(this);
init();
}
public <T> T newInstance(final Class<T> iType) {
return (T) newInstance(iType.getSimpleName(), null, new Object[0]);
}
public <T> T newInstance(final Class<T> iType, Object... iArgs) {
return (T) newInstance(iType.getSimpleName(), null, iArgs);
}
public <RET> RET newInstance(String iClassName) {
return (RET) newInstance(iClassName, null, new Object[0]);
}
@Override
public <THISDB extends ODatabase> THISDB open(String iUserName, String iUserPassword) {
super.open(iUserName, iUserPassword);
entityManager.registerEntityClass(OUser.class);
entityManager.registerEntityClass(ORole.class);
return (THISDB) this;
}
/**
* Create a new POJO by its class name. Assure to have called the registerEntityClasses() declaring the packages that are part of
* entity classes.
*
* @see OEntityManager#registerEntityClasses(String)
*/
public <RET extends Object> RET newInstance(final String iClassName, final Object iEnclosingClass, Object... iArgs) {
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName);
try {
RET enhanced = (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(entityManager.getEntityClass(iClassName),
iEnclosingClass, underlying.newInstance(iClassName), null, iArgs);
return (RET) enhanced;
} catch (Exception e) {
OLogManager.instance().error(this, "Error on creating object of class " + iClassName, e, ODatabaseException.class);
}
return null;
}
/**
* Create a new POJO by its class name. Assure to have called the registerEntityClasses() declaring the packages that are part of
* entity classes.
*
* @see OEntityManager#registerEntityClasses(String)
*/
public <RET extends Object> RET newInstance(final String iClassName, final Object iEnclosingClass, ODocument iDocument,
Object... iArgs) {
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName);
try {
RET enhanced = (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(entityManager.getEntityClass(iClassName),
iEnclosingClass, iDocument, null, iArgs);
return (RET) enhanced;
} catch (Exception e) {
OLogManager.instance().error(this, "Error on creating object of class " + iClassName, e, ODatabaseException.class);
}
return null;
}
public <RET> OObjectIteratorClass<RET> browseClass(final Class<RET> iClusterClass) {
return browseClass(iClusterClass, true);
}
public <RET> OObjectIteratorClass<RET> browseClass(final Class<RET> iClusterClass, final boolean iPolymorphic) {
if (iClusterClass == null)
return null;
return browseClass(iClusterClass.getSimpleName(), iPolymorphic);
}
public <RET> OObjectIteratorClass<RET> browseClass(final String iClassName) {
return browseClass(iClassName, true);
}
public <RET> OObjectIteratorClass<RET> browseClass(final String iClassName, final boolean iPolymorphic) {
checkOpeness();
checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_READ, iClassName);
return new OObjectIteratorClass<RET>(this, (ODatabaseRecordAbstract) getUnderlying().getUnderlying(), iClassName, iPolymorphic);
}
public <RET> OObjectIteratorCluster<RET> browseCluster(final String iClusterName) {
checkOpeness();
checkSecurity(ODatabaseSecurityResources.CLUSTER, ORole.PERMISSION_READ, iClusterName);
return (OObjectIteratorCluster<RET>) new OObjectIteratorCluster<Object>(this, (ODatabaseRecordAbstract) getUnderlying()
.getUnderlying(), getClusterIdByName(iClusterName));
}
public <RET> RET load(final Object iPojo) {
return (RET) load(iPojo, null);
}
public <RET> RET reload(final Object iPojo) {
return (RET) reload(iPojo, null, true);
}
public <RET> RET reload(final Object iPojo, final boolean iIgnoreCache) {
return (RET) reload(iPojo, null, iIgnoreCache);
}
public <RET> RET reload(Object iPojo, final String iFetchPlan, final boolean iIgnoreCache) {
checkOpeness();
if (iPojo == null)
return null;
// GET THE ASSOCIATED DOCUMENT
final ODocument record = getRecordByUserObject(iPojo, true);
underlying.reload(record, iFetchPlan, iIgnoreCache);
iPojo = stream2pojo(record, iPojo, iFetchPlan, true);
return (RET) iPojo;
}
public <RET> RET load(final Object iPojo, final String iFetchPlan) {
return (RET) load(iPojo, iFetchPlan, false);
}
@Override
public void attach(final Object iPojo) {
OObjectEntitySerializer.attach(iPojo, this);
}
public <RET> RET attachAndSave(final Object iPojo) {
attach(iPojo);
return (RET) save(iPojo);
}
@Override
/**
* Method that detaches all fields contained in the document to the given object. It returns by default a proxied instance. To get
* a detached non proxied instance @see {@link OObjectEntitySerializer.detach(T o, ODatabaseObject db, boolean
* returnNonProxiedInstance)}
*
* @param <T>
* @param o
* :- the object to detach
* @return the detached object
*/
public <RET> RET detach(final Object iPojo) {
return (RET) OObjectEntitySerializer.detach(iPojo, this);
}
/**
* Method that detaches all fields contained in the document to the given object.
*
* @param <RET>
* @param iPojo
* :- the object to detach
* @param returnNonProxiedInstance
* :- defines if the return object will be a proxied instance or not. If set to TRUE and the object does not contains @Id
* and @Version fields it could procude data replication
* @return the object serialized or with detached data
*/
public <RET> RET detach(final Object iPojo, boolean returnNonProxiedInstance) {
return (RET) OObjectEntitySerializer.detach(iPojo, this, returnNonProxiedInstance);
}
/**
* Method that detaches all fields contained in the document to the given object and recursively all object tree. This may throw a
* {@link StackOverflowError} with big objects tree. To avoid it set the stack size with -Xss java option
*
* @param <RET>
* @param iPojo
* :- the object to detach
* @param returnNonProxiedInstance
* :- defines if the return object will be a proxied instance or not. If set to TRUE and the object does not contains @Id
* and @Version fields it could procude data replication
* @return the object serialized or with detached data
*/
public <RET> RET detachAll(final Object iPojo, boolean returnNonProxiedInstance) {
return (RET) OObjectEntitySerializer.detachAll(iPojo, this, returnNonProxiedInstance);
}
public <RET> RET load(final Object iPojo, final String iFetchPlan, final boolean iIgnoreCache) {
return (RET) load(iPojo, iFetchPlan, iIgnoreCache, false);
}
@Override
public <RET> RET load(Object iPojo, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
checkOpeness();
if (iPojo == null)
return null;
// GET THE ASSOCIATED DOCUMENT
ODocument record = getRecordByUserObject(iPojo, true);
try {
record.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
record = underlying.load(record, iFetchPlan, iIgnoreCache, loadTombstone);
return (RET) stream2pojo(record, iPojo, iFetchPlan);
} finally {
record.setInternalStatus(ORecordElement.STATUS.LOADED);
}
}
public <RET> RET load(final ORID iRecordId) {
return (RET) load(iRecordId, null);
}
public <RET> RET load(final ORID iRecordId, final String iFetchPlan) {
return (RET) load(iRecordId, iFetchPlan, false);
}
public <RET> RET load(final ORID iRecordId, final String iFetchPlan, final boolean iIgnoreCache) {
return (RET) load(iRecordId, iFetchPlan, iIgnoreCache, false);
}
@Override
public <RET> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
checkOpeness();
if (iRecordId == null)
return null;
// GET THE ASSOCIATED DOCUMENT
final ODocument record = (ODocument) underlying.load(iRecordId, iFetchPlan, iIgnoreCache, loadTombstone);
if (record == null)
return null;
return (RET) OObjectEntityEnhancer.getInstance().getProxiedInstance(record.getClassName(), entityManager, record, null);
}
/**
* Saves an object to the databasein synchronous mode . First checks if the object is new or not. In case it's new a new ODocument
* is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is introspected using the Java
* Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*/
public <RET> RET save(final Object iContent) {
return (RET) save(iContent, (String) null, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
/**
* Saves an object to the database specifying the mode. First checks if the object is new or not. In case it's new a new ODocument
* is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is introspected using the Java
* Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*/
public <RET> RET save(final Object iContent, OPERATION_MODE iMode, boolean iForceCreate,
final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
return (RET) save(iContent, null, iMode, false, iRecordCreatedCallback, iRecordUpdatedCallback);
}
/**
* Saves an object in synchronous mode to the database forcing a record cluster where to store it. First checks if the object is
* new or not. In case it's new a new ODocument is created and bound to the object, otherwise the ODocument is retrieved and
* updated. The object is introspected using the Java Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*
* Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
* following the constraints declared in the schema.
*
* @see ORecordSchemaAware#validate()
*/
public <RET> RET save(final Object iPojo, final String iClusterName) {
return (RET) save(iPojo, iClusterName, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
@Override
public boolean updatedReplica(Object iPojo) {
OSerializationThreadLocal.INSTANCE.get().clear();
// GET THE ASSOCIATED DOCUMENT
final Object proxiedObject = OObjectEntitySerializer.serializeObject(iPojo, this);
final ODocument record = getRecordByUserObject(proxiedObject, true);
boolean result;
try {
record.setInternalStatus(com.orientechnologies.orient.core.db.record.ORecordElement.STATUS.MARSHALLING);
result = underlying.updatedReplica(record);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).updateLoadedFieldMap(proxiedObject);
// RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
registerUserObject(proxiedObject, record);
} finally {
record.setInternalStatus(com.orientechnologies.orient.core.db.record.ORecordElement.STATUS.LOADED);
}
return result;
}
/**
* Saves an object to the database forcing a record cluster where to store it. First checks if the object is new or not. In case
* it's new a new ODocument is created and bound to the object, otherwise the ODocument is retrieved and updated. The object is
* introspected using the Java Reflection to extract the field values. <br/>
* If a multi value (array, collection or map of objects) is passed, then each single object is stored separately.
*
* Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
* following the constraints declared in the schema.
*
* @see ORecordSchemaAware#validate()
*/
public <RET> RET save(final Object iPojo, final String iClusterName, OPERATION_MODE iMode, boolean iForceCreate,
final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
checkOpeness();
if (iPojo == null)
return (RET) iPojo;
else if (OMultiValue.isMultiValue(iPojo)) {
// MULTI VALUE OBJECT: STORE SINGLE POJOS
for (Object pojo : OMultiValue.getMultiValueIterable(iPojo)) {
save(pojo, iClusterName);
}
return (RET) iPojo;
} else {
OSerializationThreadLocal.INSTANCE.get().clear();
// GET THE ASSOCIATED DOCUMENT
final Object proxiedObject = OObjectEntitySerializer.serializeObject(iPojo, this);
final ODocument record = getRecordByUserObject(proxiedObject, true);
try {
record.setInternalStatus(ORecordElement.STATUS.MARSHALLING);
if (!saveOnlyDirty || record.isDirty()) {
// REGISTER BEFORE TO SERIALIZE TO AVOID PROBLEMS WITH CIRCULAR DEPENDENCY
// registerUserObject(iPojo, record);
deleteOrphans((((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler())));
ODocument savedRecord = underlying.save(record, iClusterName, iMode, iForceCreate, iRecordCreatedCallback,
iRecordUpdatedCallback);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).setDoc(savedRecord);
((OObjectProxyMethodHandler) ((ProxyObject) proxiedObject).getHandler()).updateLoadedFieldMap(proxiedObject);
// RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
registerUserObject(proxiedObject, record);
}
} finally {
record.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return (RET) proxiedObject;
}
}
public ODatabaseObject delete(final Object iPojo) {
checkOpeness();
if (iPojo == null)
return this;
ODocument record = getRecordByUserObject(iPojo, false);
if (record == null) {
final ORecordId rid = OObjectSerializerHelper.getObjectID(this, iPojo);
if (rid == null)
throw new OObjectNotDetachedException("Cannot retrieve the object's ID for '" + iPojo + "' because has not been detached");
record = (ODocument) underlying.load(rid);
}
deleteCascade(record);
underlying.delete(record);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, record);
return this;
}
@Override
public ODatabaseObject delete(final ORID iRID) {
checkOpeness();
if (iRID == null)
return this;
final ORecordInternal<?> record = iRID.getRecord();
if (record instanceof ODocument) {
Object iPojo = getUserObjectByRecord(record, null);
deleteCascade((ODocument) record);
underlying.delete(record);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, (ODocument) record);
}
return this;
}
@Override
public ODatabaseObject delete(final ORID iRID, final ORecordVersion iVersion) {
deleteRecord(iRID, iVersion, false);
return this;
}
@Override
public ODatabaseComplex<Object> cleanOutRecord(ORID iRID, ORecordVersion iVersion) {
deleteRecord(iRID, iVersion, true);
return this;
}
private boolean deleteRecord(ORID iRID, ORecordVersion iVersion, boolean prohibitTombstones) {
checkOpeness();
if (iRID == null)
return true;
ODocument record = iRID.getRecord();
if (record != null) {
Object iPojo = getUserObjectByRecord(record, null);
deleteCascade(record);
if (prohibitTombstones)
underlying.cleanOutRecord(iRID, iVersion);
else
underlying.delete(iRID, iVersion);
if (getTransaction() instanceof OTransactionNoTx)
unregisterPojo(iPojo, record);
}
return false;
}
protected void deleteCascade(final ODocument record) {
if (record == null)
return;
List<String> toDeleteCascade = OObjectEntitySerializer.getCascadeDeleteFields(record.getClassName());
if (toDeleteCascade != null) {
for (String field : toDeleteCascade) {
Object toDelete = record.field(field);
if (toDelete instanceof OIdentifiable) {
if (toDelete != null)
delete(((OIdentifiable) toDelete).getIdentity());
} else if (toDelete instanceof Collection) {
for (OIdentifiable cascadeRecord : ((Collection<OIdentifiable>) toDelete)) {
if (cascadeRecord != null)
delete(((OIdentifiable) cascadeRecord).getIdentity());
}
} else if (toDelete instanceof Map) {
for (OIdentifiable cascadeRecord : ((Map<Object, OIdentifiable>) toDelete).values()) {
if (cascadeRecord != null)
delete(((OIdentifiable) cascadeRecord).getIdentity());
}
}
}
}
}
public long countClass(final String iClassName) {
checkOpeness();
return underlying.countClass(iClassName);
}
public long countClass(final Class<?> iClass) {
checkOpeness();
return underlying.countClass(iClass.getSimpleName());
}
public ODictionary<Object> getDictionary() {
checkOpeness();
if (dictionary == null)
dictionary = new ODictionaryWrapper(this, underlying.getDictionary().getIndex());
return dictionary;
}
@Override
public ODatabasePojoAbstract<Object> commit() {
try {
// BY PASS DOCUMENT DB
((ODatabaseRecordTx) underlying.getUnderlying()).commit();
if (getTransaction().getAllRecordEntries() != null) {
// UPDATE ID & VERSION FOR ALL THE RECORDS
Object pojo = null;
for (ORecordOperation entry : getTransaction().getAllRecordEntries()) {
switch (entry.type) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
break;
case ORecordOperation.DELETED:
unregisterPojo(pojo, (ODocument) entry.getRecord());
break;
}
}
}
} finally {
getTransaction().close();
}
return this;
}
@Override
public ODatabasePojoAbstract<Object> rollback() {
try {
// COPY ALL TX ENTRIES
final List<ORecordOperation> newEntries;
if (getTransaction().getCurrentRecordEntries() != null) {
newEntries = new ArrayList<ORecordOperation>();
for (ORecordOperation entry : getTransaction().getCurrentRecordEntries())
if (entry.type == ORecordOperation.CREATED)
newEntries.add(entry);
} else
newEntries = null;
// BY PASS DOCUMENT DB
((ODatabaseRecordTx) underlying.getUnderlying()).rollback();
} finally {
getTransaction().close();
}
return this;
}
public OEntityManager getEntityManager() {
return entityManager;
}
@Override
public ODatabaseDocument getUnderlying() {
return underlying;
}
/**
* Returns the version number of the object. Version starts from 0 assigned on creation.
*
* @param iPojo
* User object
*/
@Override
public ORecordVersion getVersion(final Object iPojo) {
checkOpeness();
final ODocument record = getRecordByUserObject(iPojo, false);
if (record != null)
return record.getRecordVersion();
return OObjectSerializerHelper.getObjectVersion(iPojo);
}
/**
* Returns the object unique identity.
*
* @param iPojo
* User object
*/
@Override
public ORID getIdentity(final Object iPojo) {
checkOpeness();
if (iPojo instanceof OIdentifiable)
return ((OIdentifiable) iPojo).getIdentity();
final ODocument record = getRecordByUserObject(iPojo, false);
if (record != null)
return record.getIdentity();
return OObjectSerializerHelper.getObjectID(this, iPojo);
}
public boolean isSaveOnlyDirty() {
return saveOnlyDirty;
}
public void setSaveOnlyDirty(boolean saveOnlyDirty) {
this.saveOnlyDirty = saveOnlyDirty;
}
public Object newInstance() {
checkOpeness();
return new ODocument();
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final byte iOperation) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation);
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final int iOperation, Object iResourceSpecific) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation, iResourceSpecific);
}
public <DBTYPE extends ODatabase> DBTYPE checkSecurity(final String iResource, final int iOperation, Object... iResourcesSpecific) {
return (DBTYPE) underlying.checkSecurity(iResource, iOperation, iResourcesSpecific);
}
@Override
public ODocument pojo2Stream(final Object iPojo, final ODocument iRecord) {
if (iPojo instanceof ProxyObject) {
return ((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).getDoc();
}
return OObjectSerializerHelper.toStream(iPojo, iRecord, getEntityManager(),
getMetadata().getSchema().getClass(iPojo.getClass().getSimpleName()), this, this, saveOnlyDirty);
}
@Override
public Object stream2pojo(ODocument iRecord, final Object iPojo, final String iFetchPlan) {
return stream2pojo(iRecord, iPojo, iFetchPlan, false);
}
public Object stream2pojo(ODocument iRecord, final Object iPojo, final String iFetchPlan, boolean iReload) {
if (iRecord.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED)
iRecord = (ODocument) iRecord.load();
if (iReload) {
if (iPojo != null) {
if (iPojo instanceof Proxy) {
((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).setDoc(iRecord);
((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).updateLoadedFieldMap(iPojo);
return iPojo;
} else
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iPojo.getClass(), iRecord);
} else
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iRecord.getClassName(), entityManager, iRecord, null);
} else if (!(iPojo instanceof Proxy))
return OObjectEntityEnhancer.getInstance().getProxiedInstance(iPojo.getClass(), iRecord);
else
return iPojo;
}
public boolean isLazyLoading() {
return lazyLoading;
}
public void setLazyLoading(final boolean lazyLoading) {
this.lazyLoading = lazyLoading;
}
public String getType() {
return TYPE;
}
@Override
public ODocument getRecordByUserObject(Object iPojo, boolean iCreateIfNotAvailable) {
if (iPojo instanceof Proxy)
return OObjectEntitySerializer.getDocument((Proxy) iPojo);
return OObjectEntitySerializer.getDocument((Proxy) OObjectEntitySerializer.serializeObject(iPojo, this));
}
@Override
public Object getUserObjectByRecord(final OIdentifiable iRecord, final String iFetchPlan, final boolean iCreate) {
final ODocument document = iRecord.getRecord();
return OObjectEntityEnhancer.getInstance().getProxiedInstance(document.getClassName(), getEntityManager(), document, null);
}
@Override
public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) {
}
public void registerUserObjectAfterLinkSave(ORecordInternal<?> iRecord) {
}
@Override
public void unregisterPojo(final Object iObject, final ODocument iRecord) {
}
public void registerClassMethodFilter(Class<?> iClass, OObjectMethodFilter iMethodFilter) {
OObjectEntityEnhancer.getInstance().registerClassMethodFilter(iClass, iMethodFilter);
}
public void deregisterClassMethodFilter(final Class<?> iClass) {
OObjectEntityEnhancer.getInstance().deregisterClassMethodFilter(iClass);
}
protected void init() {
entityManager = OEntityManager.getEntityManagerByDatabaseURL(getURL());
entityManager.setClassHandler(OObjectEntityClassHandler.getInstance());
saveOnlyDirty = OGlobalConfiguration.OBJECT_SAVE_ONLY_DIRTY.getValueAsBoolean();
OObjectSerializerHelper.register();
lazyLoading = true;
if (!isClosed() && entityManager.getEntityClass(OUser.class.getSimpleName()) == null) {
entityManager.registerEntityClass(OUser.class);
entityManager.registerEntityClass(ORole.class);
}
}
protected void deleteOrphans(final OObjectProxyMethodHandler handler) {
for (ORID orphan : handler.getOrphans()) {
final ODocument doc = orphan.getRecord();
deleteCascade(doc);
underlying.delete(doc);
}
handler.getOrphans().clear();
}
}
| Minor: fixed object database for non document record from tx
| object/src/main/java/com/orientechnologies/orient/object/db/OObjectDatabaseTx.java | Minor: fixed object database for non document record from tx | <ide><path>bject/src/main/java/com/orientechnologies/orient/object/db/OObjectDatabaseTx.java
<ide> break;
<ide>
<ide> case ORecordOperation.DELETED:
<del> unregisterPojo(pojo, (ODocument) entry.getRecord());
<add> final ORecordInternal<?> rec = entry.getRecord();
<add> if (rec instanceof ODocument)
<add> unregisterPojo(pojo, (ODocument) rec);
<ide> break;
<ide> }
<ide> } |
|
Java | bsd-2-clause | 8690f1e401b7ff6ee364707a46ae89899472e049 | 0 | biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej | package ij.process;
import loci.formats.FormatException;
import loci.plugins.util.ImagePlusReader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class ByteProcessorTest {
private static int width;
private static int height;
private static byte[] imageByteData;
private static ColorModel cm;
/*
* Open an known image for internal testing...
*/
@BeforeClass
public static void runBeforeClass()
{
String id = "/Volumes/data/khoros/samples/head8bit.tif";
ImagePlusReader imagePlusReader = new ImagePlusReader();
ImageProcessor imageProcessor = null;
try {
imagePlusReader.setId(id);
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
imageProcessor = imagePlusReader.openProcessors(0)[0];
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
width = imageProcessor.getWidth();
height = imageProcessor.getHeight();
imageByteData = new byte[width*height];
try {
imagePlusReader.openBytes( 0, imageByteData );
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
//assign the color model
cm = imageProcessor.getColorModel();
}
@Test
public void testSetColorColor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
int setcolorvalue = 2;
//set the value
byteProcessor.setColor(setcolorvalue);
//see if the test passes
assertEquals(setcolorvalue, byteProcessor.fgColor, 0.0);
}
@Test
public void testSetValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
float setcolorvalue = 1;
byteProcessor.setValue(setcolorvalue);
//overwrite the pixel value with the new default fill value
byteProcessor.drawPixel(1, 1);
//see if the value was over-writen with the SetColor value
float postDrawPixelValue = byteProcessor.getf(1, 1);
assertEquals(setcolorvalue, postDrawPixelValue, 0.0);
}
@Test
public void testSetBackgroundValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//reference
double refBackground = 0x00000000;
//set the background
byteProcessor.setBackgroundValue(refBackground);
//get the value
double returnedReferenceValue = byteProcessor.getBackgroundValue();
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(refBackground, returnedReferenceValue, 0.0);
}
@Test
public void testGetMin()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
int min = Integer.MAX_VALUE;
for (byte b : imageByteData)
if(b < min) min = b;
//correct for +-128 bias
min+=127;
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(min, byteProcessor.getMin(), 0.0);
}
@Test
public void testGetMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
int max = Integer.MIN_VALUE;
for (byte b : imageByteData)
if(b > max) max = b;
//correct for +-128 bias
max+=128;
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(max, byteProcessor.getMax(), 0.0);
}
@Test
public void testSetMinAndMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the values for max and min used in the test
double max = 2.0;
double min = 1.0;
byteProcessor.setMinAndMax(min, max);
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(max, byteProcessor.getMax(), 1.0);
assertEquals(min, byteProcessor.getMin(), 1.0);
}
@Test
public void testResetMinAndMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
double refMax = byteProcessor.getMax();
double refMin = byteProcessor.getMin();
//set the values for max and min used in the test
double max = 2.0;
double min = 1.0;
byteProcessor.setMinAndMax(min, max);
//reset should yield the initial values
byteProcessor.resetMinAndMax();
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(refMax, byteProcessor.getMax(), 0.0);
}
@Test
public void testFlipVertical()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
byteProcessor.flipVertical();
byteProcessor.flipVertical();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testFillImageProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//reference
double refBackground = 0x00000000;
//set the background
byteProcessor.setBackgroundValue(refBackground);
//fill the image
byteProcessor.fill(byteProcessor);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
double result = byteProcessor.get( reference );
assertEquals( refBackground, result, 0.0);
}
}
}
@Test
public void testGetPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] testRef = (byte[]) byteProcessor.getPixels();
for(int i=0; i<imageByteData.length; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
}
@Test
public void testGetPixelsCopy()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] testRef = (byte[]) byteProcessor.getPixelsCopy();
for(int i=0; i<imageByteData.length; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
//test snapshot mode
byteProcessor.setSnapshotCopyMode(true);
Rectangle roi = new Rectangle(0, 0, width/2, height/2);
byteProcessor.setRoi(roi);
byteProcessor.snapshot();
testRef = (byte[]) byteProcessor.getPixelsCopy();
for(int i=0; i<width/2 + height/2; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
}
@Test
public void testGetPixelIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.getPixel( x , y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( x , y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetIntIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 1;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.set(x, y, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 1;
//set the reference value
byteProcessor.setValue(refValue);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.set(reference, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetfIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getf( x, y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetfInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetfIntIntFloat()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
float refValue = 2.0f;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.setf( x, y, refValue);
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetfIntFloat()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
float refValue = 2.0f;
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int reference = y * width + x;
byteProcessor.setf( reference, refValue);
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetInterpolatedPixel()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byteProcessor.setInterpolationMethod(ImageProcessor.BILINEAR);
for(int y = 0; y < height-1; y++)
{
for(int x = 0; x < width-1; x++)
{
//Bilinear interpolation
int xbase = x;
int ybase = y;
double xFraction = x - xbase;
double yFraction = y - ybase;
int offset = ybase * width + xbase;
double lowerLeft = imageByteData[offset];
double lowerRight = imageByteData[offset + 1];
double upperRight = imageByteData[offset + width + 1];
double upperLeft = imageByteData[offset + width];
double upperAverage = upperLeft + xFraction * (upperRight - upperLeft);
double lowerAverage = lowerLeft + xFraction * (lowerRight - lowerLeft);
double referenceResult = lowerAverage + yFraction * (upperAverage - lowerAverage);
//get the pixel value that was set
double result = byteProcessor.getInterpolatedPixel((double) x, (double) y);
//check the result
assertEquals( referenceResult, result, Float.MAX_VALUE );
}
}
}
@Test
public void testGetPixelInterpolated()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byteProcessor.setInterpolationMethod(ImageProcessor.BILINEAR);
for(int y = 0; y < height-1; y++)
{
for(int x = 0; x < width-1; x++)
{
//Bilinear interpolation
int xbase = x;
int ybase = y;
double xFraction = x - xbase;
double yFraction = y - ybase;
int offset = ybase * width + xbase;
double lowerLeft = imageByteData[offset];
double lowerRight = imageByteData[offset + 1];
double upperRight = imageByteData[offset + width + 1];
double upperLeft = imageByteData[offset + width];
double upperAverage = upperLeft + xFraction * (upperRight - upperLeft);
double lowerAverage = lowerLeft + xFraction * (lowerRight - lowerLeft);
double referenceResult = lowerAverage + yFraction * (upperAverage - lowerAverage);
//get the pixel value that was set
double result = byteProcessor.getPixelInterpolated( (double) x, (double) y);
//check the result
assertEquals( referenceResult, result, Float.MAX_VALUE );
}
}
}
@Test
public void testPutPixelIntIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 2;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.putPixel( x, y, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetPixelValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getPixelValue( x, y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testPutPixelValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
double refValue = 3.0;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
byteProcessor.putPixelValue( x, y, refValue );
float result = byteProcessor.getPixelValue( x, y );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testDrawPixel()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
float setColorValue = 1;
byteProcessor.setValue(setColorValue);
//overwrite the pixel value with the new default fill value
byteProcessor.drawPixel(1, 1);
//see if the value was over-writen with the SetColor value
float postDrawPixelValue = byteProcessor.getf(1, 1);
assertEquals(setColorValue, postDrawPixelValue, 0.0);
}
@Test
public void testSetPixelsObject()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height);
byteProcessor.setPixels( imageByteData );
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testCopyBits()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
testByteProcessor.copyBits( byteProcessor, 0, 0, Blitter.COPY );
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( byteProcessor.getf( reference ), testByteProcessor.getf( reference ), 0.0);
}
}
}
@Test
public void testApplyTable()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
int[] sine_table = {99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};
byteProcessor.applyTable(sine_table);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
int lutValue = sine_table[refValue];
assertEquals( lutValue, result, 0.0);
}
}
}
@Test
public void testCreateImage()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
Image testImage = byteProcessor.createImage();
assertEquals( testImage.getWidth(null), width);
assertEquals( testImage.getHeight(null), height);
//TODO: add testing for actual image objects
}
@Test
public void testGetBufferedImage()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
BufferedImage testImage = byteProcessor.getBufferedImage();
assertEquals( testImage.getWidth(null), width);
assertEquals( testImage.getHeight(null), height);
//create a reference image
//TODO: Compare the images
}
@Test
public void testCreateProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
ByteProcessor testByteProcessor = (ByteProcessor) byteProcessor.createProcessor(width, height);
//test empty image
assertEquals( testByteProcessor.getWidth(), width);
assertEquals( testByteProcessor.getHeight(), height);
}
@Test
public void testSnapshot()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//take a snapshot
byteProcessor.snapshot();
//change the entire image
byteProcessor.flipVertical();
//revert from snapshot
byteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testReset()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//take a snapshot
byteProcessor.snapshot();
//change the entire image
byteProcessor.flipVertical();
//revert from snapshot
byteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testResetImageProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//change the entire image
byteProcessor.flipVertical();
//reset from new imageprocessor
byteProcessor.reset( new ByteProcessor(width, height, imageByteData, cm));
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetSnapshotPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
//change the entire image
testByteProcessor.setSnapshotPixels( imageByteData );
//reset from new imageprocessor
testByteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( refByteProcessor.getf( reference ), testByteProcessor.getf( reference ), 0.0);
}
}
}
@Test
public void testGetSnapshotPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
//change the entire image
testByteProcessor.setSnapshotPixels( imageByteData );
byte[] snapShotPixels = ( byte[] )testByteProcessor.getSnapshotPixels();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( snapShotPixels[ reference ], imageByteData[ reference ], 0.0);
}
}
}
@Test //TODO: fix this test
public void testConvolve3x3()
{
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] refPixels = new byte[width*height];
int[] kernel = {-1, -1, -1, -1, 8, -1, -1, -1, -1};
testByteProcessor.convolve3x3(kernel);
byte[] testPixels = (byte[]) testByteProcessor.getPixels();
int p1, p2, p3,
p4, p5, p6,
p7, p8, p9;
int k1=kernel[0], k2=kernel[1], k3=kernel[2],
k4=kernel[3], k5=kernel[4], k6=kernel[5],
k7=kernel[6], k8=kernel[7], k9=kernel[8];
int scale = 0;
for (int i=0; i<kernel.length; i++)
scale += kernel[i];
if (scale==0) scale = 1;
int inc = refByteProcessor.roiHeight/25;
if (inc<1) inc = 1;
byte[] pixels2 = (byte[]) refByteProcessor.getPixelsCopy();
int offset, sum;
int rowOffset = refByteProcessor.width;
for (int y=refByteProcessor.yMin; y<=refByteProcessor.yMax; y++) {
offset = refByteProcessor.xMin + y * refByteProcessor.width;
p1 = 0;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p4 = 0;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p7 = 0;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=refByteProcessor.xMin; x<=refByteProcessor.xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
sum = k1*p1 + k2*p2 + k3*p3
+ k4*p4 + k5*p5 + k6*p6
+ k7*p7 + k8*p8 + k9*p9;
sum /= scale;
if(sum>255) sum= 255;
if(sum<0) sum= 0;
refPixels[offset++] = (byte)sum;
}
}
//test
for(int y = 0; y<refByteProcessor.height; y++)
{
for(int x = 0; x<refByteProcessor.width; x++)
{
int reference = y*refByteProcessor.width + x;
assertEquals( refPixels[ reference ], testPixels[ reference ], 0.0);
}
}
}
@Test
public void testFilter()
{
//Test Filter:BLUR_MORE
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] refPixelArray = (byte[]) refByteProcessor.getPixelsCopy();
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int inc = refByteProcessor.roiHeight/25;
if (inc<1) inc = 1;
byte[] pixels2 = (byte[])refByteProcessor.getPixelsCopy();
if (width==1) {
refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, refByteProcessor.roiX, refByteProcessor.roiY, 0, 1);
return;
}
int offset, sum=0;
int rowOffset = width;
for (int y=refByteProcessor.yMin; y<=refByteProcessor.yMax; y++) {
offset = refByteProcessor.xMin + y * width;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=refByteProcessor.xMin; x<=refByteProcessor.xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
sum = (p1+p2+p3+p4+p5+p6+p7+p8+p9)/9;
refPixelArray[offset++] = (byte)sum;
}
//if (y%inc==0)
// showProgress((double)(y-roiY)/roiHeight);
}
if (refByteProcessor.xMin==1) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, refByteProcessor.roiX, refByteProcessor.roiY, 0, 1);
if (refByteProcessor.yMin==1) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiWidth, refByteProcessor.roiX, refByteProcessor.roiY, 1, 0);
if (refByteProcessor.xMax==width-2) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, width-1, refByteProcessor.roiY, 0, 1);
if (refByteProcessor.yMax==height-2) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiWidth, refByteProcessor.roiX, height-1, 1, 0);
//assert testFilter:BLUR_MORE
testByteProcessor.filter(ImageProcessor.BLUR_MORE);
byte[] testPixels = (byte[]) testByteProcessor.getPixelsCopy();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( refPixelArray[ reference ], testPixels[ reference ], 0.0);
}
}
}
@Test
public void testMedianFilter() {
fail("Not yet implemented");
}
@Test
public void testNoise() {
fail("Not yet implemented");
}
@Test
public void testCrop() {
fail("Not yet implemented");
}
@Test
public void testThreshold() {
fail("Not yet implemented");
}
@Test
public void testDuplicate() {
fail("Not yet implemented");
}
@Test
public void testScale() {
fail("Not yet implemented");
}
@Test
public void testResizeIntInt() {
fail("Not yet implemented");
}
@Test
public void testRotate() {
fail("Not yet implemented");
}
@Test
public void testGetHistogram() {
fail("Not yet implemented");
}
@Test
public void testErode() {
fail("Not yet implemented");
}
@Test
public void testDilate() {
fail("Not yet implemented");
}
@Test
public void testConvolve() {
fail("Not yet implemented");
}
@Test
public void testToFloat() {
fail("Not yet implemented");
}
@Test
public void testSetPixelsIntFloatProcessor() {
fail("Not yet implemented");
}
@Test
public void testCreate8BitImage() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorImage() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorIntInt() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorIntIntByteArrayColorModel() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorBufferedImage() {
fail("Not yet implemented");
}
@Test
public void testCreateBufferedImage() {
fail("Not yet implemented");
}
@Test
public void testFilterEdge() {
fail("Not yet implemented");
}
@Test
public void testGetEdgePixel() {
fail("Not yet implemented");
}
@Test
public void testGetEdgePixel0() {
fail("Not yet implemented");
}
@Test
public void testErodeIntInt() {
fail("Not yet implemented");
}
@Test
public void testDilateIntInt() {
fail("Not yet implemented");
}
@Test
public void testOutline() {
fail("Not yet implemented");
}
@Test
public void testSkeletonize() {
fail("Not yet implemented");
}
@Test
public void testGetHistogramImageProcessor() {
fail("Not yet implemented");
}
@Test
public void testApplyLut() {
fail("Not yet implemented");
}
@Test
public void testToFloatProcessors() {
fail("Not yet implemented");
}
@Test
public void testSetFromFloatProcessors() {
fail("Not yet implemented");
}
@Test
public void testToFloatArrays() {
fail("Not yet implemented");
}
@Test
public void testSetFromFloatArrays() {
fail("Not yet implemented");
}
}
| ij/process/ByteProcessorTest.java | package ij.process;
import loci.formats.FormatException;
import loci.plugins.util.ImagePlusReader;
import org.junit.BeforeClass;
import org.junit.Test;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class ByteProcessorTest {
private static int width;
private static int height;
private static byte[] imageByteData;
private static ColorModel cm;
/*
* Open an known image for internal testing...
*/
@BeforeClass
public static void runBeforeClass()
{
String id = "/Volumes/data/khoros/samples/head8bit.tif";
ImagePlusReader imagePlusReader = new ImagePlusReader();
ImageProcessor imageProcessor = null;
try {
imagePlusReader.setId(id);
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
imageProcessor = imagePlusReader.openProcessors(0)[0];
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
width = imageProcessor.getWidth();
height = imageProcessor.getHeight();
imageByteData = new byte[width*height];
try {
imagePlusReader.openBytes( 0, imageByteData );
} catch (FormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
//assign the color model
cm = imageProcessor.getColorModel();
}
@Test
public void testSetColorColor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
int setcolorvalue = 2;
//set the value
byteProcessor.setColor(setcolorvalue);
//see if the test passes
assertEquals(setcolorvalue, byteProcessor.fgColor, 0.0);
}
@Test
public void testSetValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
float setcolorvalue = 1;
byteProcessor.setValue(setcolorvalue);
//overwrite the pixel value with the new default fill value
byteProcessor.drawPixel(1, 1);
//see if the value was over-writen with the SetColor value
float postDrawPixelValue = byteProcessor.getf(1, 1);
assertEquals(setcolorvalue, postDrawPixelValue, 0.0);
}
@Test
public void testSetBackgroundValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//reference
double refBackground = 0x00000000;
//set the background
byteProcessor.setBackgroundValue(refBackground);
//get the value
double returnedReferenceValue = byteProcessor.getBackgroundValue();
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(refBackground, returnedReferenceValue, 0.0);
}
@Test
public void testGetMin()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
int min = Integer.MAX_VALUE;
for (byte b : imageByteData)
if(b < min) min = b;
//correct for +-128 bias
min+=127;
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(min, byteProcessor.getMin(), 0.0);
}
@Test
public void testGetMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
int max = Integer.MIN_VALUE;
for (byte b : imageByteData)
if(b > max) max = b;
//correct for +-128 bias
max+=128;
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(max, byteProcessor.getMax(), 0.0);
}
@Test
public void testSetMinAndMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the values for max and min used in the test
double max = 2.0;
double min = 1.0;
byteProcessor.setMinAndMax(min, max);
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(max, byteProcessor.getMax(), 1.0);
assertEquals(min, byteProcessor.getMin(), 1.0);
}
@Test
public void testResetMinAndMax()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
double refMax = byteProcessor.getMax();
double refMin = byteProcessor.getMin();
//set the values for max and min used in the test
double max = 2.0;
double min = 1.0;
byteProcessor.setMinAndMax(min, max);
//reset should yield the initial values
byteProcessor.resetMinAndMax();
//see if the test passes assertEquals(float expected, float actual, float delta)
assertEquals(refMax, byteProcessor.getMax(), 0.0);
}
@Test
public void testFlipVertical()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
byteProcessor.flipVertical();
byteProcessor.flipVertical();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testFillImageProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//reference
double refBackground = 0x00000000;
//set the background
byteProcessor.setBackgroundValue(refBackground);
//fill the image
byteProcessor.fill(byteProcessor);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
double result = byteProcessor.get( reference );
assertEquals( refBackground, result, 0.0);
}
}
}
@Test
public void testGetPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] testRef = (byte[]) byteProcessor.getPixels();
for(int i=0; i<imageByteData.length; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
}
@Test
public void testGetPixelsCopy()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] testRef = (byte[]) byteProcessor.getPixelsCopy();
for(int i=0; i<imageByteData.length; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
//test snapshot mode
byteProcessor.setSnapshotCopyMode(true);
Rectangle roi = new Rectangle(0, 0, width/2, height/2);
byteProcessor.setRoi(roi);
byteProcessor.snapshot();
testRef = (byte[]) byteProcessor.getPixelsCopy();
for(int i=0; i<width/2 + height/2; i++)
{
assertEquals( imageByteData[i], testRef[i], 0.0 );
}
}
@Test
public void testGetPixelIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.getPixel( x , y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( x , y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetIntIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 1;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.set(x, y, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 1;
//set the reference value
byteProcessor.setValue(refValue);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.set(reference, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetfIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getf( x, y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetfInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetfIntIntFloat()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
float refValue = 2.0f;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.setf( x, y, refValue);
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetfIntFloat()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
float refValue = 2.0f;
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
int reference = y * width + x;
byteProcessor.setf( reference, refValue);
//get the set value (converted back to an int)
float result = byteProcessor.getf( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetInterpolatedPixel()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byteProcessor.setInterpolationMethod(ImageProcessor.BILINEAR);
for(int y = 0; y < height-1; y++)
{
for(int x = 0; x < width-1; x++)
{
//Bilinear interpolation
int xbase = x;
int ybase = y;
double xFraction = x - xbase;
double yFraction = y - ybase;
int offset = ybase * width + xbase;
double lowerLeft = imageByteData[offset];
double lowerRight = imageByteData[offset + 1];
double upperRight = imageByteData[offset + width + 1];
double upperLeft = imageByteData[offset + width];
double upperAverage = upperLeft + xFraction * (upperRight - upperLeft);
double lowerAverage = lowerLeft + xFraction * (lowerRight - lowerLeft);
double referenceResult = lowerAverage + yFraction * (upperAverage - lowerAverage);
//get the pixel value that was set
double result = byteProcessor.getInterpolatedPixel((double) x, (double) y);
//check the result
assertEquals( referenceResult, result, Float.MAX_VALUE );
}
}
}
@Test
public void testGetPixelInterpolated()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byteProcessor.setInterpolationMethod(ImageProcessor.BILINEAR);
for(int y = 0; y < height-1; y++)
{
for(int x = 0; x < width-1; x++)
{
//Bilinear interpolation
int xbase = x;
int ybase = y;
double xFraction = x - xbase;
double yFraction = y - ybase;
int offset = ybase * width + xbase;
double lowerLeft = imageByteData[offset];
double lowerRight = imageByteData[offset + 1];
double upperRight = imageByteData[offset + width + 1];
double upperLeft = imageByteData[offset + width];
double upperAverage = upperLeft + xFraction * (upperRight - upperLeft);
double lowerAverage = lowerLeft + xFraction * (lowerRight - lowerLeft);
double referenceResult = lowerAverage + yFraction * (upperAverage - lowerAverage);
//get the pixel value that was set
double result = byteProcessor.getPixelInterpolated( (double) x, (double) y);
//check the result
assertEquals( referenceResult, result, Float.MAX_VALUE );
}
}
}
@Test
public void testPutPixelIntIntInt()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//set a reference value
int refValue = 2;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
byteProcessor.putPixel( x, y, refValue);
//get the set value (converted back to an int)
int result = byteProcessor.get( reference );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testGetPixelValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
float result = byteProcessor.getPixelValue( x, y );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testPutPixelValue()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
double refValue = 3.0;
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
//get the set value (converted back to an int)
byteProcessor.putPixelValue( x, y, refValue );
float result = byteProcessor.getPixelValue( x, y );
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testDrawPixel()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height,imageByteData, cm);
//set the default fill value
float setColorValue = 1;
byteProcessor.setValue(setColorValue);
//overwrite the pixel value with the new default fill value
byteProcessor.drawPixel(1, 1);
//see if the value was over-writen with the SetColor value
float postDrawPixelValue = byteProcessor.getf(1, 1);
assertEquals(setColorValue, postDrawPixelValue, 0.0);
}
@Test
public void testSetPixelsObject()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height);
byteProcessor.setPixels( imageByteData );
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testCopyBits()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
testByteProcessor.copyBits( byteProcessor, 0, 0, Blitter.COPY );
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( byteProcessor.getf( reference ), testByteProcessor.getf( reference ), 0.0);
}
}
}
@Test
public void testApplyTable()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
int[] sine_table = {99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};
byteProcessor.applyTable(sine_table);
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
int lutValue = sine_table[refValue];
assertEquals( lutValue, result, 0.0);
}
}
}
@Test
public void testCreateImage()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
Image testImage = byteProcessor.createImage();
assertEquals( testImage.getWidth(null), width);
assertEquals( testImage.getHeight(null), height);
//TODO: add testing for actual image objects
}
@Test
public void testGetBufferedImage()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
BufferedImage testImage = byteProcessor.getBufferedImage();
assertEquals( testImage.getWidth(null), width);
assertEquals( testImage.getHeight(null), height);
//create a reference image
//TODO: Compare the images
}
@Test
public void testCreateProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//get the image
ByteProcessor testByteProcessor = (ByteProcessor) byteProcessor.createProcessor(width, height);
//test empty image
assertEquals( testByteProcessor.getWidth(), width);
assertEquals( testByteProcessor.getHeight(), height);
}
@Test
public void testSnapshot()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//take a snapshot
byteProcessor.snapshot();
//change the entire image
byteProcessor.flipVertical();
//revert from snapshot
byteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testReset()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//take a snapshot
byteProcessor.snapshot();
//change the entire image
byteProcessor.flipVertical();
//revert from snapshot
byteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testResetImageProcessor()
{
//Create a new ByteProcessor object for testing
ByteProcessor byteProcessor = new ByteProcessor(width, height, imageByteData, cm);
//change the entire image
byteProcessor.flipVertical();
//reset from new imageprocessor
byteProcessor.reset( new ByteProcessor(width, height, imageByteData, cm));
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
float result = byteProcessor.getf( reference );
int refValue;
if ( imageByteData[reference] < 0)
{ refValue = imageByteData[reference] + 256; }
else
{ refValue = imageByteData[reference]; }
assertEquals( refValue, result, 0.0);
}
}
}
@Test
public void testSetSnapshotPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
//change the entire image
testByteProcessor.setSnapshotPixels( imageByteData );
//reset from new imageprocessor
testByteProcessor.reset();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( refByteProcessor.getf( reference ), testByteProcessor.getf( reference ), 0.0);
}
}
}
@Test
public void testGetSnapshotPixels()
{
//Create a new ByteProcessor object for testing
ByteProcessor testByteProcessor = new ByteProcessor(width, height);
//change the entire image
testByteProcessor.setSnapshotPixels( imageByteData );
byte[] snapShotPixels = ( byte[] )testByteProcessor.getSnapshotPixels();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( snapShotPixels[ reference ], imageByteData[ reference ], 0.0);
}
}
}
@Test //TODO: fix this test
public void testConvolve3x3()
{
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] refPixels = new byte[width*height];
int[] kernel = {-1, -1, -1, -1, 8, -1, -1, -1, -1};
testByteProcessor.convolve3x3(kernel);
byte[] testPixels = (byte[]) testByteProcessor.getPixels();
int p1, p2, p3,
p4, p5, p6,
p7, p8, p9;
int k1=kernel[0], k2=kernel[1], k3=kernel[2],
k4=kernel[3], k5=kernel[4], k6=kernel[5],
k7=kernel[6], k8=kernel[7], k9=kernel[8];
int scale = 0;
for (int i=0; i<kernel.length; i++)
scale += kernel[i];
if (scale==0) scale = 1;
int inc = refByteProcessor.roiHeight/25;
if (inc<1) inc = 1;
byte[] pixels2 = (byte[]) refByteProcessor.getPixelsCopy();
int offset, sum;
int rowOffset = refByteProcessor.width;
for (int y=refByteProcessor.yMin; y<=refByteProcessor.yMax; y++) {
offset = refByteProcessor.xMin + y * refByteProcessor.width;
p1 = 0;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p4 = 0;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p7 = 0;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=refByteProcessor.xMin; x<=refByteProcessor.xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
sum = k1*p1 + k2*p2 + k3*p3
+ k4*p4 + k5*p5 + k6*p6
+ k7*p7 + k8*p8 + k9*p9;
sum /= scale;
if(sum>255) sum= 255;
if(sum<0) sum= 0;
refPixels[offset++] = (byte)sum;
}
}
//test
for(int y = 0; y<refByteProcessor.height; y++)
{
for(int x = 0; x<refByteProcessor.width; x++)
{
int reference = y*refByteProcessor.width + x;
assertEquals( refPixels[ reference ], testPixels[ reference ], 0.0);
}
}
}
@Test
public void testFilter()
{
//Test Filter:BLUR_MORE
//Create a new ByteProcessor object for testing
ByteProcessor refByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
ByteProcessor testByteProcessor = new ByteProcessor(width, height, imageByteData, cm);
byte[] refPixelArray = (byte[]) refByteProcessor.getPixelsCopy();
int p1, p2, p3, p4, p5, p6, p7, p8, p9;
int inc = refByteProcessor.roiHeight/25;
if (inc<1) inc = 1;
byte[] pixels2 = (byte[])refByteProcessor.getPixelsCopy();
if (width==1) {
refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, refByteProcessor.roiX, refByteProcessor.roiY, 0, 1);
return;
}
int offset, sum=0;
int rowOffset = width;
for (int y=refByteProcessor.yMin; y<=refByteProcessor.yMax; y++) {
offset = refByteProcessor.xMin + y * width;
p2 = pixels2[offset-rowOffset-1]&0xff;
p3 = pixels2[offset-rowOffset]&0xff;
p5 = pixels2[offset-1]&0xff;
p6 = pixels2[offset]&0xff;
p8 = pixels2[offset+rowOffset-1]&0xff;
p9 = pixels2[offset+rowOffset]&0xff;
for (int x=refByteProcessor.xMin; x<=refByteProcessor.xMax; x++) {
p1 = p2; p2 = p3;
p3 = pixels2[offset-rowOffset+1]&0xff;
p4 = p5; p5 = p6;
p6 = pixels2[offset+1]&0xff;
p7 = p8; p8 = p9;
p9 = pixels2[offset+rowOffset+1]&0xff;
sum = (p1+p2+p3+p4+p5+p6+p7+p8+p9)/9;
refPixelArray[offset++] = (byte)sum;
}
//if (y%inc==0)
// showProgress((double)(y-roiY)/roiHeight);
}
if (refByteProcessor.xMin==1) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, refByteProcessor.roiX, refByteProcessor.roiY, 0, 1);
if (refByteProcessor.yMin==1) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiWidth, refByteProcessor.roiX, refByteProcessor.roiY, 1, 0);
if (refByteProcessor.xMax==width-2) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiHeight, width-1, refByteProcessor.roiY, 0, 1);
if (refByteProcessor.yMax==height-2) refByteProcessor.filterEdge(refByteProcessor.BLUR_MORE, pixels2, refByteProcessor.roiWidth, refByteProcessor.roiX, height-1, 1, 0);
//assert testFilter:BLUR_MORE
testByteProcessor.filter(ImageProcessor.BLUR_MORE);
byte[] testPixels = (byte[]) testByteProcessor.getPixelsCopy();
for(int y = 0; y<height; y++)
{
for(int x = 0; x<width; x++)
{
int reference = y*width + x;
assertEquals( refPixelArray[ reference ], testPixels[ reference ], 0.0);
}
}
}
@Test
public void testMedianFilter() {
fail("Not yet implemented");
}
@Test
public void testNoise() {
fail("Not yet implemented");
}
@Test
public void testCrop() {
fail("Not yet implemented");
}
@Test
public void testThreshold() {
fail("Not yet implemented");
}
@Test
public void testDuplicate() {
fail("Not yet implemented");
}
@Test
public void testScale() {
fail("Not yet implemented");
}
@Test
public void testResizeIntInt() {
fail("Not yet implemented");
}
@Test
public void testRotate() {
fail("Not yet implemented");
}
@Test
public void testGetHistogram() {
fail("Not yet implemented");
}
@Test
public void testErode() {
fail("Not yet implemented");
}
@Test
public void testDilate() {
fail("Not yet implemented");
}
@Test
public void testConvolve() {
fail("Not yet implemented");
}
@Test
public void testToFloat() {
fail("Not yet implemented");
}
@Test
public void testSetPixelsIntFloatProcessor() {
fail("Not yet implemented");
}
@Test
public void testCreate8BitImage() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorImage() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorIntInt() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorIntIntByteArrayColorModel() {
fail("Not yet implemented");
}
@Test
public void testByteProcessorBufferedImage() {
fail("Not yet implemented");
}
@Test
public void testCreateBufferedImage() {
fail("Not yet implemented");
}
@Test
public void testFilterEdge() {
fail("Not yet implemented");
}
@Test
public void testGetEdgePixel() {
fail("Not yet implemented");
}
@Test
public void testGetEdgePixel0() {
fail("Not yet implemented");
}
@Test
public void testErodeIntInt() {
fail("Not yet implemented");
}
@Test
public void testDilateIntInt() {
fail("Not yet implemented");
}
@Test
public void testOutline() {
fail("Not yet implemented");
}
@Test
public void testSkeletonize() {
fail("Not yet implemented");
}
@Test
public void testGetHistogramImageProcessor() {
fail("Not yet implemented");
}
@Test
public void testApplyLut() {
fail("Not yet implemented");
}
@Test
public void testToFloatProcessors() {
fail("Not yet implemented");
}
@Test
public void testSetFromFloatProcessors() {
fail("Not yet implemented");
}
@Test
public void testToFloatArrays() {
fail("Not yet implemented");
}
@Test
public void testSetFromFloatArrays() {
fail("Not yet implemented");
}
}
| Test commit
This used to be revision r1065.
| ij/process/ByteProcessorTest.java | Test commit | <ide><path>j/process/ByteProcessorTest.java
<ide> + k7*p7 + k8*p8 + k9*p9;
<ide> sum /= scale;
<ide>
<del> if(sum>255) sum= 255;
<add> if(sum>255) sum= 255;
<ide> if(sum<0) sum= 0;
<ide>
<ide> refPixels[offset++] = (byte)sum; |
|
Java | mit | 75fab4a7dbbab305a101da4db1169546638aab51 | 0 | SVss/computer-shop-mpp,SVss/computer-shop-mpp,SVss/computer-shop-mpp,SVss/computer-shop-mpp | package by.bsuir.mpp.computershop.utils;
import by.bsuir.mpp.computershop.dto.full.UserAuthFullDto;
import by.bsuir.mpp.computershop.dto.full.UserInfoFullDto;
import by.bsuir.mpp.computershop.entity.UserAuth;
import java.math.BigInteger;
import java.util.Random;
public class TestHelper {
public static final Random RANDOM = new Random();
public static final String NON_RANDOM_STRING = "some_nonrandom_value";
private static final int BITS_COUNT = 130;
private static final int RADIX = 32;
public static Long nextLongId() {
return RANDOM.nextLong() + 1;
}
public static Long nextLong() {
return RANDOM.nextLong();
}
public static int nextInt(int max) {
return RANDOM.nextInt(max + 1);
}
public static String nextString() {
return nextString(BITS_COUNT);
}
public static String nextString(int bitsCount) {
return new BigInteger(bitsCount, RANDOM).toString(RADIX);
}
public static UserAuthFullDto nextUserAuthFullDto() {
UserInfoFullDto info = new UserInfoFullDto();
info.setFirstName(nextString());
info.setLastName(nextString());
UserAuthFullDto result = new UserAuthFullDto();
result.setEmail(nextString());
result.setPass(nextString());
result.setRole(UserAuth.Role.VALUES.get(RANDOM.nextInt(UserAuth.Role.SIZE)));
result.setUserInfo(info);
return result;
}
}
| src/test/java/by/bsuir/mpp/computershop/utils/TestHelper.java | package by.bsuir.mpp.computershop.utils;
import by.bsuir.mpp.computershop.dto.full.UserAuthFullDto;
import by.bsuir.mpp.computershop.dto.full.UserInfoFullDto;
import by.bsuir.mpp.computershop.entity.UserAuth;
import java.math.BigInteger;
import java.util.Random;
public class TestHelper {
public static final Random RANDOM = new Random();
public static final String NON_RANDOM_STRING = "some_nonrandom_value";
private static final int BITS_COUNT = 130;
private static final int RADIX = 32;
public static Long nextLongId() {
return RANDOM.nextLong() + 1;
}
public static int nextInt(int max) {
return RANDOM.nextInt(max + 1);
}
public static String nextString() {
return nextString(BITS_COUNT);
}
public static String nextString(int bitsCount) {
return new BigInteger(bitsCount, RANDOM).toString(RADIX);
}
public static UserAuthFullDto nextUserAuthFullDto() {
UserInfoFullDto info = new UserInfoFullDto();
info.setFirstName(nextString());
info.setLastName(nextString());
UserAuthFullDto result = new UserAuthFullDto();
result.setEmail(nextString());
result.setPass(nextString());
result.setRole(UserAuth.Role.VALUES.get(RANDOM.nextInt(UserAuth.Role.SIZE)));
result.setUserInfo(info);
return result;
}
}
| Add NextLong method
| src/test/java/by/bsuir/mpp/computershop/utils/TestHelper.java | Add NextLong method | <ide><path>rc/test/java/by/bsuir/mpp/computershop/utils/TestHelper.java
<ide>
<ide> public static Long nextLongId() {
<ide> return RANDOM.nextLong() + 1;
<add> }
<add>
<add> public static Long nextLong() {
<add> return RANDOM.nextLong();
<ide> }
<ide>
<ide> public static int nextInt(int max) { |
|
Java | mit | 0c4bf7d3ab571f10138da57abe033f68f740364f | 0 | sunnydas/grokkingalgos,sunnydas/grokkingalgos | package com.sunny.grokkingalgorithms.boot2019.phleps;
public class PositionOfRightmostSetBit {
/*
Write a one line function to return position of first 1 from right to left, in binary representation of an Integer.
I/P 18, Binary Representation 010010
O/P 2
I/P 19, Binary Representation 010011
O/P 1
*/
public static int positionOfRightMostSetBit(int number){
int mask = 1;
int position = -1;
while(number != 0){
if(position < 0){
position = 0;
}
if((number & mask) == 1){
break;
}
number = number>>1;
position++;
}
return (position + 1);
}
public static void main(String[] args) {
int n = 18;
System.out.println(positionOfRightMostSetBit(n));
n = 19;
System.out.println(positionOfRightMostSetBit(n));
n = 12;
System.out.println(positionOfRightMostSetBit(n));
n = 16;
System.out.println(positionOfRightMostSetBit(n));
}
}
| src/main/java/com/sunny/grokkingalgorithms/boot2019/phleps/PositionOfRightmostSetBit.java | package com.sunny.grokkingalgorithms.boot2019.phleps;
public class PositionOfRightmostSetBit {
/*
Write a one line function to return position of first 1 from right to left, in binary representation of an Integer.
I/P 18, Binary Representation 010010
O/P 2
I/P 19, Binary Representation 010011
O/P 1
*/
public static int positionOfRightMostSetBit(int number){
int mask = 1;
int position = -1;
while(number != 0){
if(position < 0){
position = 0;
}
if((number & mask) == 1){
break;
}
number = number>>1;
position++;
}
return (position + 1);
}
public static void main(String[] args) {
int n = 18;
System.out.println(positionOfRightMostSetBit(n));
n = 19;
System.out.println(positionOfRightMostSetBit(n));
n = 12;
System.out.println(positionOfRightMostSetBit(n));
}
}
| n = 16
| src/main/java/com/sunny/grokkingalgorithms/boot2019/phleps/PositionOfRightmostSetBit.java | n = 16 | <ide><path>rc/main/java/com/sunny/grokkingalgorithms/boot2019/phleps/PositionOfRightmostSetBit.java
<ide> System.out.println(positionOfRightMostSetBit(n));
<ide> n = 12;
<ide> System.out.println(positionOfRightMostSetBit(n));
<add> n = 16;
<add> System.out.println(positionOfRightMostSetBit(n));
<ide> }
<ide>
<ide> } |
|
Java | mit | d7ff1e560351617f36c6a1cf927305fa3df1b82d | 0 | mcflugen/wmt-rest,mcflugen/wmt-rest | /**
* <License>
*/
package edu.colorado.csdms.wmt.client.ui.widgets;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import edu.colorado.csdms.wmt.client.data.ComponentJSO;
import edu.colorado.csdms.wmt.client.ui.handler.DialogCancelHandler;
/**
* A dialog box used to display metadata (id, url, author, etc.) about a WMT
* component.
*
* @author Mark Piper ([email protected])
*/
public class ComponentInfoDialogBox extends DialogBox {
private static String[] LABELS = {"summary", "url", "author"};
private Grid grid;
private ClosePanel closePanel;
/**
* Creates an {@link ComponentInfoDialogBox}. It must be populated later by
* calling {@link ComponentInfoDialogBox#update()}.
*/
public ComponentInfoDialogBox() {
this.setAutoHideEnabled(false);
this.setModal(false);
grid = new Grid(LABELS.length, 1);
grid.setCellPadding(5); // px
closePanel = new ClosePanel();
VerticalPanel contents = new VerticalPanel();
contents.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
contents.setWidth("35em");
contents.add(grid);
contents.add(closePanel);
this.setWidget(contents);
/*
* Hides the dialog box.
*/
closePanel.getButton().addClickHandler(new DialogCancelHandler(this));
}
/**
* Updates the {@link ComponentInfoDialogBox} with information from the
* input component.
*
* @param componentJso a {@link ComponentJSO} instance
*/
public void update(final ComponentJSO componentJso) {
String title = componentJso.getName();
if (componentJso.getVersion() != null) {
title += " v" + componentJso.getVersion();
}
if (componentJso.getDoi() != null) {
title += " (" + componentJso.getDoi() + ")";
}
this.setText(title);
String url = "<a href='" + componentJso.getURL() + "'>"
+ componentJso.getURL() + "</a>";
String author = (componentJso.getAuthor() == null)
? " " : componentJso.getAuthor();
String[] info = {componentJso.getSummary(), url,
"Model developer: " + author};
HTML urlHtml = null;
for (int i = 0; i < LABELS.length; i++) {
if (url.equals(info[i])) {
urlHtml = new HTML(info[i]);
grid.setWidget(i, 0, urlHtml);
} else {
grid.setWidget(i, 0, new HTML(info[i]));
}
}
/*
* Intercepts the click on the component URL and opens it in a new tab.
*/
urlHtml.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
event.preventDefault();
Window.open(componentJso.getURL(), "componentInfoDialog", null);
}
});
}
}
| gui/src/edu/colorado/csdms/wmt/client/ui/widgets/ComponentInfoDialogBox.java | /**
* <License>
*/
package edu.colorado.csdms.wmt.client.ui.widgets;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.VerticalPanel;
import edu.colorado.csdms.wmt.client.data.ComponentJSO;
import edu.colorado.csdms.wmt.client.ui.handler.DialogCancelHandler;
/**
* A dialog box used to display metadata (id, url, author, etc.) about a WMT
* component.
*
* @author Mark Piper ([email protected])
*/
public class ComponentInfoDialogBox extends DialogBox {
private static String[] LABELS = {"summary", "url", "author"};
private Grid grid;
private ClosePanel closePanel;
/**
* Creates an {@link ComponentInfoDialogBox}. It must be populated later by
* calling {@link ComponentInfoDialogBox#update()}.
*/
public ComponentInfoDialogBox() {
this.setAutoHideEnabled(false);
this.setModal(false);
grid = new Grid(LABELS.length, 1);
grid.setCellPadding(5); // px
closePanel = new ClosePanel();
VerticalPanel contents = new VerticalPanel();
contents.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
contents.setWidth("35em");
contents.add(grid);
contents.add(closePanel);
this.setWidget(contents);
/*
* Hides the dialog box.
*/
closePanel.getButton().addClickHandler(new DialogCancelHandler(this));
}
/**
* Updates the {@link ComponentInfoDialogBox} with information from the
* input component.
*
* @param componentJso a {@link ComponentJSO} instance
*/
public void update(final ComponentJSO componentJso) {
String title = componentJso.getName();
if (componentJso.getVersion() != null) {
title += " v" + componentJso.getVersion();
}
if (componentJso.getDoi() != null) {
title += " (" + componentJso.getDoi() + ")";
}
this.setText(title);
String url =
"<a href='" + componentJso.getURL() + "'>" + componentJso.getURL()
+ "</a>";
String[] info = {componentJso.getSummary(), url, componentJso.getAuthor()};
HTML urlHtml = null;
for (int i = 0; i < LABELS.length; i++) {
if (url.equals(info[i])) {
urlHtml = new HTML(info[i]);
grid.setWidget(i, 0, urlHtml);
} else {
grid.setWidget(i, 0, new HTML(info[i]));
}
}
/*
* Intercepts the click on the component URL and opens it in a new tab.
*/
urlHtml.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
event.preventDefault();
Window.open(componentJso.getURL(), "componentInfoDialog", null);
}
});
}
}
| Modify "author" field of ComponentInfoDialogBox
Per Irina's request.
| gui/src/edu/colorado/csdms/wmt/client/ui/widgets/ComponentInfoDialogBox.java | Modify "author" field of ComponentInfoDialogBox | <ide><path>ui/src/edu/colorado/csdms/wmt/client/ui/widgets/ComponentInfoDialogBox.java
<ide> }
<ide> this.setText(title);
<ide>
<del> String url =
<del> "<a href='" + componentJso.getURL() + "'>" + componentJso.getURL()
<del> + "</a>";
<del> String[] info = {componentJso.getSummary(), url, componentJso.getAuthor()};
<add> String url = "<a href='" + componentJso.getURL() + "'>"
<add> + componentJso.getURL() + "</a>";
<add> String author = (componentJso.getAuthor() == null)
<add> ? " " : componentJso.getAuthor();
<add> String[] info = {componentJso.getSummary(), url,
<add> "Model developer: " + author};
<ide>
<ide> HTML urlHtml = null;
<ide> for (int i = 0; i < LABELS.length; i++) { |
|
JavaScript | mit | cd3cfa7beb085748a10396fcd922428ae9d0d921 | 0 | sean9keenan/WordWeb,sean9keenan/WordWeb,sean9keenan/WordWeb,sean9keenan/WordWeb | var globalScalingFactor = .6
var c
c = document.getElementById("wordweb");
c.width = c.offsetWidth;
c.height = c.offsetHeight;
var ctx
setDefaultView = function(){
ctx.setTransform(
1.0119992278780352,
0,
0,
1.0119992278780352,
20.144126420245993,
0.32101987756787453)
}
window.onload = function(){
ctx = c.getContext("2d");
trackTransforms(ctx);
setDefaultView()
}
window.onresize = function(){
c.width = c.offsetWidth;
c.height = c.offsetHeight;
redraw();
setDefaultView()
}
$('#wrapper').scrollLeft(600);
$('#wrapper').scrollTop(800);
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
if (getCookie('user') != ""){
var data = {};
data.name = getCookie('user');
window.socket.emit('loginToMainWebsite', data);
} else {
failedLogin()
}
window.socket.on('loginReturn', function(data){
if (data == 'Success') {
requestPuzzleProgress()
$('#createUser').hide();
$('#GuessId').fadeIn();
} else {
failedLogin()
}
});
function failedLogin(){
$('#createUser').fadeIn();
$('#GuessId').fadeOut();
}
$('#createUser').keypress(function (e) {
if (e.which == 13) {
window.socket.emit('registerUser', $('#userCreation').val());
setCookie('user', $('#userCreation').val(), 365)
var data = {};
data.name = getCookie('user');
window.socket.emit('loginToMainWebsite', data);
return false;
}
});
function requestPuzzleProgress(){
window.socket.emit("requestPuzzleProgress")
}
function drawLine(x1, y1, x2, y2, item1, item2){
var xs = x1 + c.width/2;
var ys = y1 + c.height/2;
var xe = x2 + c.width/2;
var ye = y2 + c.height/2;
ctx.beginPath();
var c1 = 'hsl('+item1.hue+','+item1.sat+'%,'+item1.light+'%)';
var c2 = 'hsl('+item2.hue+','+item2.sat+'%,'+item2.light+'%)';
var grad= ctx.createLinearGradient(xs, ys, xe, ye);
grad.addColorStop(0, c1);
grad.addColorStop(1, c2);
if (item1.sat == 100){
ctx.strokeStyle = c1;
} else if (item2.sat == 100){
ctx.strokeStyle = c2;
} else {
ctx.strokeStyle = grad;
}
ctx.moveTo(xs, ys);
ctx.lineTo(xe, ye);
ctx.stroke();
}
function drawText(x, y, text, item1){
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "black";
ctx.font = "bold 28px Arial";
textwidth = ctx.measureText(text).width + 10;
textheight = 28 + 10;
// Rectangle
ctx.beginPath();
ctx.rect(x + c.width/2 - textwidth/2, y + c.height/2 - textheight/2, textwidth, textheight);
ctx.fillStyle = 'white';
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = 'hsl('+item1.hue+','+item1.sat+'%,'+item1.light+'%)';
ctx.stroke();
//
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "black";
ctx.font = "bold 28px Arial";
ctx.fillText(text, x + c.width/2, y + c.height/2);
}
$('#GuessId').keypress(function (e) {
if (e.which == 13) {
window.socket.emit('webRequest', $('#deviceGuess').val());
return false;
}
});
var totalMap = {}
window.socket.on('puzzleState', function(data){
totalMap.web = data.web
totalMap.validIndexes = data.validIndexes
totalMap.wordweb = data.wordweb
updateMap(data.web, data.validIndexes);
});
window.socket.on('puzzleUpdate', function(data){
totalMap.web = data.web
totalMap.validIndexes = data.validIndexes
totalMap.wordweb = data.wordweb
redraw()
});
removeGuestClasses = function(){
window.setTimeout(function() {
$('#GuessId').removeClass('has-error')
$('#GuessId').removeClass('has-success')
$('#GuessId').removeClass('has-warning')
}, 1000);
}
window.socket.on('isAnswerCorrect', function(data){
if (data){
$('#deviceGuess').val("");
$('#GuessId').addClass('has-success')
$('#instructions').slideUp()
} else {
$('#deviceGuess').val("");
$('#GuessId').addClass('has-error')
}
removeGuestClasses()
});
window.socket.on('answerAlreadyThere', function(data){
$('#deviceGuess').val("");
$('#GuessId').addClass('has-warning')
removeGuestClasses()
});
checkIfClicked = function (web, updateList, factor){
if (clickedPoint.isClicked){
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
if (clickedPoint.x > web[i].x*factor -110&& clickedPoint.y > web[i].y*factor - 30){
if (clickedPoint.x < web[i].x*factor +110 && clickedPoint.y < web[i].y*factor + 30){
clickedPoint.lasti = i
if (web[i].sat != 100){
clickedPoint.lastLight = web[i].light;
clickedPoint.lastSat = web[i].sat;
web[i].light = 50;
web[i].sat = 100;
}
}
}
}
}
}
}
function updateMap(web, updateList){
var factor = globalScalingFactor
checkIfClicked(web, updateList,factor);
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
for (var j=0; j < web[i].connections.length; j++){
if (updateList.indexOf(web[i].connections[j]) != -1){
drawLine(web[i].x * factor, web[i].y * factor, web[web[i].connections[j]].x * factor, web[web[i].connections[j]].y * factor, web[i], web[web[i].connections[j]]);
}
}
}
}
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
drawText(web[i].x * factor, web[i].y * factor, web[i].word, web[i])
}
}
}
var redraw = function(){
// Store the current transformation matrix
ctx.save();
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, c.width, c.height);
// Restore the transform
ctx.restore();
updateMap(totalMap.web, totalMap.validIndexes);
percent = totalMap.wordweb.length / totalMap.web.length;
if (percent > .3){
$("#percentage").fadeIn();
$("#percentage").html("" + Math.floor(percent*100*100)/100 + "%")
}
}
var clickedPoint = {isClicked: false, lasti : -1};
var lastX=c.width/2, lastY=c.height/2;
var dragStart,dragged;
mouseDown = function(evt){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
lastX = evt.offsetX || (evt.pageX - c.offsetLeft);
lastY = evt.offsetY || (evt.pageY - c.offsetTop);
dragStart = ctx.transformedPoint(lastX,lastY);
dragged = false;
}
mouseMove = function(evt){
lastX = evt.offsetX || (evt.pageX - c.offsetLeft);
lastY = evt.offsetY || (evt.pageY - c.offsetTop);
dragged = true;
if (dragStart){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
redraw();
}
evt.stopPropagation();
}
mouseUp = function(evt){
dragStart = null;
// if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
if (!dragged){
clickedPoint.isClicked = true;
var pt = ctx.transformedPoint(lastX,lastY);
clickedPoint.x = pt.x - c.width/2
clickedPoint.y = pt.y - c.height/2
web = totalMap.web
factor = globalScalingFactor;
if (clickedPoint.lasti != -1){
i = clickedPoint.lasti;
if (clickedPoint.x > web[i].x*factor -110&& clickedPoint.y > web[i].y*factor - 30){
if (clickedPoint.x < web[i].x*factor +110 && clickedPoint.y < web[i].y*factor + 30){
clickedPoint.isClicked = false;
}
}
totalMap.web[clickedPoint.lasti].light = clickedPoint.lastLight;
totalMap.web[clickedPoint.lasti].sat = clickedPoint.lastSat;
clickedPoint.lasti = -1;
}
redraw()
}
}
c.addEventListener('mousedown',mouseDown,false);
c.addEventListener('mousemove',mouseMove,false);
c.addEventListener('mouseup',mouseUp,false);
c.addEventListener("touchstart", mouseDown, false);
c.addEventListener("touchend", mouseUp, false);
// c.addEventListener("touchcancel", mouseEnd, false);
// c.addEventListener("touchleave", mouseEnd, false);
c.addEventListener("touchmove", mouseMove, false);
var scaleFactor = 1.1;
var zoom = function(clicks){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
redraw();
}
var handleScroll = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
c.addEventListener('DOMMouseScroll',handleScroll,false);
c.addEventListener('mousewheel',handleScroll,false);
// Adds ctx.getTransform() - returns an SVGMatrix
// Adds ctx.transformedPoint(x,y) - returns an SVGPoint
function trackTransforms(ctx){
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
xform = savedTransforms.pop();
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
xform = xform.scaleNonUniform(sx,sy);
return scale.call(ctx,sx,sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
return rotate.call(ctx,radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
return translate.call(ctx,dx,dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
xform = xform.multiply(m2);
return transform.call(ctx,a,b,c,d,e,f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
xform.a = a;
xform.b = b;
xform.c = c;
xform.d = d;
xform.e = e;
xform.f = f;
return setTransform.call(ctx,a,b,c,d,e,f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y){
pt.x=x; pt.y=y;
return pt.matrixTransform(xform.inverse());
}
} | frontend/web.js | var globalScalingFactor = .6
var c
c = document.getElementById("wordweb");
c.width = c.offsetWidth;
c.height = c.offsetHeight;
var ctx
setDefaultView = function(){
ctx.setTransform(
1.0119992278780352,
0,
0,
1.0119992278780352,
20.144126420245993,
0.32101987756787453)
}
window.onload = function(){
ctx = c.getContext("2d");
trackTransforms(ctx);
setDefaultView()
}
window.onresize = function(){
c.width = c.offsetWidth;
c.height = c.offsetHeight;
redraw();
setDefaultView()
}
$('#wrapper').scrollLeft(600);
$('#wrapper').scrollTop(800);
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
if (getCookie('user') != ""){
var data = {};
data.name = getCookie('user');
window.socket.emit('loginToMainWebsite', data);
} else {
failedLogin()
}
window.socket.on('loginReturn', function(data){
if (data == 'Success') {
requestPuzzleProgress()
$('#createUser').fadeOut();
$('#GuessId').fadeIn();
} else {
failedLogin()
}
});
function failedLogin(){
$('#createUser').fadeIn();
$('#GuessId').fadeOut();
}
$('#createUser').keypress(function (e) {
if (e.which == 13) {
window.socket.emit('registerUser', $('#userCreation').val());
setCookie('user', $('#userCreation').val(), 365)
var data = {};
data.name = getCookie('user');
window.socket.emit('loginToMainWebsite', data);
return false;
}
});
function requestPuzzleProgress(){
window.socket.emit("requestPuzzleProgress")
}
function drawLine(x1, y1, x2, y2, item1, item2){
var xs = x1 + c.width/2;
var ys = y1 + c.height/2;
var xe = x2 + c.width/2;
var ye = y2 + c.height/2;
ctx.beginPath();
var c1 = 'hsl('+item1.hue+','+item1.sat+'%,'+item1.light+'%)';
var c2 = 'hsl('+item2.hue+','+item2.sat+'%,'+item2.light+'%)';
var grad= ctx.createLinearGradient(xs, ys, xe, ye);
grad.addColorStop(0, c1);
grad.addColorStop(1, c2);
if (item1.sat == 100){
ctx.strokeStyle = c1;
} else if (item2.sat == 100){
ctx.strokeStyle = c2;
} else {
ctx.strokeStyle = grad;
}
ctx.moveTo(xs, ys);
ctx.lineTo(xe, ye);
ctx.stroke();
}
function drawText(x, y, text, item1){
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "black";
ctx.font = "bold 28px Arial";
textwidth = ctx.measureText(text).width + 10;
textheight = 28 + 10;
// Rectangle
ctx.beginPath();
ctx.rect(x + c.width/2 - textwidth/2, y + c.height/2 - textheight/2, textwidth, textheight);
ctx.fillStyle = 'white';
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = 'hsl('+item1.hue+','+item1.sat+'%,'+item1.light+'%)';
ctx.stroke();
//
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "black";
ctx.font = "bold 28px Arial";
ctx.fillText(text, x + c.width/2, y + c.height/2);
}
$('#GuessId').keypress(function (e) {
if (e.which == 13) {
window.socket.emit('webRequest', $('#deviceGuess').val());
return false;
}
});
var totalMap = {}
window.socket.on('puzzleState', function(data){
totalMap.web = data.web
totalMap.validIndexes = data.validIndexes
totalMap.wordweb = data.wordweb
updateMap(data.web, data.validIndexes);
});
window.socket.on('puzzleUpdate', function(data){
totalMap.web = data.web
totalMap.validIndexes = data.validIndexes
totalMap.wordweb = data.wordweb
redraw()
});
removeGuestClasses = function(){
window.setTimeout(function() {
$('#GuessId').removeClass('has-error')
$('#GuessId').removeClass('has-success')
$('#GuessId').removeClass('has-warning')
}, 1000);
}
window.socket.on('isAnswerCorrect', function(data){
if (data){
$('#deviceGuess').val("");
$('#GuessId').addClass('has-success')
$('#instructions').slideUp()
} else {
$('#deviceGuess').val("");
$('#GuessId').addClass('has-error')
}
removeGuestClasses()
});
window.socket.on('answerAlreadyThere', function(data){
$('#deviceGuess').val("");
$('#GuessId').addClass('has-warning')
removeGuestClasses()
});
checkIfClicked = function (web, updateList, factor){
if (clickedPoint.isClicked){
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
if (clickedPoint.x > web[i].x*factor -110&& clickedPoint.y > web[i].y*factor - 30){
if (clickedPoint.x < web[i].x*factor +110 && clickedPoint.y < web[i].y*factor + 30){
clickedPoint.lasti = i
if (web[i].sat != 100){
clickedPoint.lastLight = web[i].light;
clickedPoint.lastSat = web[i].sat;
web[i].light = 50;
web[i].sat = 100;
}
}
}
}
}
}
}
function updateMap(web, updateList){
var factor = globalScalingFactor
checkIfClicked(web, updateList,factor);
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
for (var j=0; j < web[i].connections.length; j++){
if (updateList.indexOf(web[i].connections[j]) != -1){
drawLine(web[i].x * factor, web[i].y * factor, web[web[i].connections[j]].x * factor, web[web[i].connections[j]].y * factor, web[i], web[web[i].connections[j]]);
}
}
}
}
for (var i=0; i<web.length; i++){
if (updateList.indexOf(i) != -1){
drawText(web[i].x * factor, web[i].y * factor, web[i].word, web[i])
}
}
}
var redraw = function(){
// Store the current transformation matrix
ctx.save();
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, c.width, c.height);
// Restore the transform
ctx.restore();
updateMap(totalMap.web, totalMap.validIndexes);
percent = totalMap.wordweb.length / totalMap.web.length;
if (percent > .3){
$("#percentage").fadeIn();
$("#percentage").html("" + Math.floor(percent*100*100)/100 + "%")
}
}
var clickedPoint = {isClicked: false, lasti : -1};
var lastX=c.width/2, lastY=c.height/2;
var dragStart,dragged;
mouseDown = function(evt){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
lastX = evt.offsetX || (evt.pageX - c.offsetLeft);
lastY = evt.offsetY || (evt.pageY - c.offsetTop);
dragStart = ctx.transformedPoint(lastX,lastY);
dragged = false;
}
mouseMove = function(evt){
lastX = evt.offsetX || (evt.pageX - c.offsetLeft);
lastY = evt.offsetY || (evt.pageY - c.offsetTop);
dragged = true;
if (dragStart){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
redraw();
}
evt.stopPropagation();
}
mouseUp = function(evt){
dragStart = null;
// if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
if (!dragged){
clickedPoint.isClicked = true;
var pt = ctx.transformedPoint(lastX,lastY);
clickedPoint.x = pt.x - c.width/2
clickedPoint.y = pt.y - c.height/2
web = totalMap.web
factor = globalScalingFactor;
if (clickedPoint.lasti != -1){
i = clickedPoint.lasti;
if (clickedPoint.x > web[i].x*factor -110&& clickedPoint.y > web[i].y*factor - 30){
if (clickedPoint.x < web[i].x*factor +110 && clickedPoint.y < web[i].y*factor + 30){
clickedPoint.isClicked = false;
}
}
totalMap.web[clickedPoint.lasti].light = clickedPoint.lastLight;
totalMap.web[clickedPoint.lasti].sat = clickedPoint.lastSat;
clickedPoint.lasti = -1;
}
redraw()
}
}
c.addEventListener('mousedown',mouseDown,false);
c.addEventListener('mousemove',mouseMove,false);
c.addEventListener('mouseup',mouseUp,false);
c.addEventListener("touchstart", mouseDown, false);
c.addEventListener("touchend", mouseUp, false);
// c.addEventListener("touchcancel", mouseEnd, false);
// c.addEventListener("touchleave", mouseEnd, false);
c.addEventListener("touchmove", mouseMove, false);
var scaleFactor = 1.1;
var zoom = function(clicks){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
redraw();
}
var handleScroll = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
c.addEventListener('DOMMouseScroll',handleScroll,false);
c.addEventListener('mousewheel',handleScroll,false);
// Adds ctx.getTransform() - returns an SVGMatrix
// Adds ctx.transformedPoint(x,y) - returns an SVGPoint
function trackTransforms(ctx){
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
xform = savedTransforms.pop();
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
xform = xform.scaleNonUniform(sx,sy);
return scale.call(ctx,sx,sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
return rotate.call(ctx,radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
return translate.call(ctx,dx,dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
xform = xform.multiply(m2);
return transform.call(ctx,a,b,c,d,e,f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
xform.a = a;
xform.b = b;
xform.c = c;
xform.d = d;
xform.e = e;
xform.f = f;
return setTransform.call(ctx,a,b,c,d,e,f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y){
pt.x=x; pt.y=y;
return pt.matrixTransform(xform.inverse());
}
} | fixes
| frontend/web.js | fixes | <ide><path>rontend/web.js
<ide> window.socket.on('loginReturn', function(data){
<ide> if (data == 'Success') {
<ide> requestPuzzleProgress()
<del> $('#createUser').fadeOut();
<add> $('#createUser').hide();
<ide> $('#GuessId').fadeIn();
<ide> } else {
<ide> failedLogin() |
|
Java | apache-2.0 | bfee1425f1ebcf8f28946254ff46c4673b4832bf | 0 | robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,chamikaramj/beam,robertwb/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,apache/beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,chamikaramj/beam | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.schemas.transforms;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.schemas.SchemaCoder;
import org.apache.beam.sdk.schemas.SchemaRegistry;
import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory;
import org.apache.beam.sdk.schemas.utils.ConvertHelpers;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A set of utilities for converting between different objects supporting schemas. */
@Experimental(Kind.SCHEMAS)
@SuppressWarnings({
"nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class Convert {
/**
* Convert a {@link PCollection}{@literal <InputT>} into a {@link PCollection}{@literal <Row>}.
*
* <p>The input {@link PCollection} must have a schema attached. The output collection will have
* the same schema as the input.
*/
public static <InputT> PTransform<PCollection<InputT>, PCollection<Row>> toRows() {
return to(Row.class);
}
/**
* Convert a {@link PCollection}{@literal <Row>} into a {@link PCollection}{@literal <OutputT>}.
*
* <p>The output schema will be inferred using the schema registry. A schema must be registered
* for this type, or the conversion will fail.
*/
public static <OutputT> PTransform<PCollection<Row>, PCollection<OutputT>> fromRows(
Class<OutputT> clazz) {
return to(clazz);
}
/**
* Convert a {@link PCollection}{@literal <Row>} into a {@link PCollection}{@literal <Row>}.
*
* <p>The output schema will be inferred using the schema registry. A schema must be registered
* for this type, or the conversion will fail.
*/
public static <OutputT> PTransform<PCollection<Row>, PCollection<OutputT>> fromRows(
TypeDescriptor<OutputT> typeDescriptor) {
return to(typeDescriptor);
}
/**
* Convert a {@link PCollection}{@literal <InputT>} to a {@link PCollection}{@literal <OutputT>}.
*
* <p>This function allows converting between two types as long as the two types have
* <i>compatible</i> schemas. Two schemas are said to be <i>compatible</i> if they recursively
* have fields with the same names, but possibly different orders. If the source schema can be
* unboxed to match the target schema (i.e. the source schema contains a single field that is
* compatible with the target schema), then conversion also succeeds.
*/
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
Class<OutputT> clazz) {
return to(TypeDescriptor.of(clazz));
}
/**
* Convert a {@link PCollection}{@literal <InputT>} to a {@link PCollection}{@literal <OutputT>}.
*
* <p>This function allows converting between two types as long as the two types have
* <i>compatible</i> schemas. Two schemas are said to be <i>compatible</i> if they recursively
* have fields with the same names, but possibly different orders. If the source schema can be
* unboxed to match the target schema (i.e. the source schema contains a single field that is
* compatible with the target schema), then conversion also succeeds.
*/
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
TypeDescriptor<OutputT> typeDescriptor) {
return new ConvertTransform<>(typeDescriptor);
}
private static class ConvertTransform<InputT, OutputT>
extends PTransform<PCollection<InputT>, PCollection<OutputT>> {
TypeDescriptor<OutputT> outputTypeDescriptor;
ConvertTransform(TypeDescriptor<OutputT> outputTypeDescriptor) {
this.outputTypeDescriptor = outputTypeDescriptor;
}
private static @Nullable Schema getBoxedNestedSchema(Schema schema) {
if (schema.getFieldCount() != 1) {
return null;
}
FieldType fieldType = schema.getField(0).getType();
if (!fieldType.getTypeName().isCompositeType()) {
return null;
}
return fieldType.getRowSchema();
}
@Override
@SuppressWarnings("unchecked")
public PCollection<OutputT> expand(PCollection<InputT> input) {
if (!input.hasSchema()) {
throw new RuntimeException("Convert requires a schema on the input.");
}
SchemaCoder<InputT> coder = (SchemaCoder<InputT>) input.getCoder();
if (coder.getEncodedTypeDescriptor().equals(outputTypeDescriptor)) {
return (PCollection<OutputT>) input;
}
SchemaRegistry registry = input.getPipeline().getSchemaRegistry();
ConvertHelpers.ConvertedSchemaInformation<OutputT> converted =
ConvertHelpers.getConvertedSchemaInformation(
input.getSchema(), outputTypeDescriptor, registry);
boolean unbox = converted.unboxedType != null;
PCollection<OutputT> output;
if (converted.outputSchemaCoder != null) {
output =
input.apply(
ParDo.of(
new DoFn<InputT, OutputT>() {
@ProcessElement
public void processElement(@Element Row row, OutputReceiver<OutputT> o) {
// Read the row, potentially unboxing if necessary.
Object input = unbox ? row.getValue(0) : row;
// The output has a schema, so we need to convert to the appropriate type.
o.output(
converted.outputSchemaCoder.getFromRowFunction().apply((Row) input));
}
}));
output.setCoder(converted.outputSchemaCoder);
} else {
SerializableFunction<?, OutputT> convertPrimitive =
ConvertHelpers.getConvertPrimitive(
converted.unboxedType, outputTypeDescriptor, new DefaultTypeConversionsFactory());
output =
input.apply(
ParDo.of(
new DoFn<InputT, OutputT>() {
@ProcessElement
public void processElement(@Element Row row, OutputReceiver<OutputT> o) {
o.output(convertPrimitive.apply(row.getValue(0)));
}
}));
output.setTypeDescriptor(outputTypeDescriptor);
// TODO: Support boxing in Convert (e.g. Long -> Row with Schema { Long }).
}
return output;
}
}
}
| sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.schemas.transforms;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.schemas.SchemaRegistry;
import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory;
import org.apache.beam.sdk.schemas.utils.ConvertHelpers;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.checkerframework.checker.nullness.qual.Nullable;
/** A set of utilities for converting between different objects supporting schemas. */
@Experimental(Kind.SCHEMAS)
@SuppressWarnings({
"nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class Convert {
/**
* Convert a {@link PCollection}{@literal <InputT>} into a {@link PCollection}{@literal <Row>}.
*
* <p>The input {@link PCollection} must have a schema attached. The output collection will have
* the same schema as the input.
*/
public static <InputT> PTransform<PCollection<InputT>, PCollection<Row>> toRows() {
return to(Row.class);
}
/**
* Convert a {@link PCollection}{@literal <Row>} into a {@link PCollection}{@literal <OutputT>}.
*
* <p>The output schema will be inferred using the schema registry. A schema must be registered
* for this type, or the conversion will fail.
*/
public static <OutputT> PTransform<PCollection<Row>, PCollection<OutputT>> fromRows(
Class<OutputT> clazz) {
return to(clazz);
}
/**
* Convert a {@link PCollection}{@literal <Row>} into a {@link PCollection}{@literal <Row>}.
*
* <p>The output schema will be inferred using the schema registry. A schema must be registered
* for this type, or the conversion will fail.
*/
public static <OutputT> PTransform<PCollection<Row>, PCollection<OutputT>> fromRows(
TypeDescriptor<OutputT> typeDescriptor) {
return to(typeDescriptor);
}
/**
* Convert a {@link PCollection}{@literal <InputT>} to a {@link PCollection}{@literal <OutputT>}.
*
* <p>This function allows converting between two types as long as the two types have
* <i>compatible</i> schemas. Two schemas are said to be <i>compatible</i> if they recursively
* have fields with the same names, but possibly different orders. If the source schema can be
* unboxed to match the target schema (i.e. the source schema contains a single field that is
* compatible with the target schema), then conversion also succeeds.
*/
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
Class<OutputT> clazz) {
return to(TypeDescriptor.of(clazz));
}
/**
* Convert a {@link PCollection}{@literal <InputT>} to a {@link PCollection}{@literal <OutputT>}.
*
* <p>This function allows converting between two types as long as the two types have
* <i>compatible</i> schemas. Two schemas are said to be <i>compatible</i> if they recursively
* have fields with the same names, but possibly different orders. If the source schema can be
* unboxed to match the target schema (i.e. the source schema contains a single field that is
* compatible with the target schema), then conversion also succeeds.
*/
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
TypeDescriptor<OutputT> typeDescriptor) {
return new ConvertTransform<>(typeDescriptor);
}
private static class ConvertTransform<InputT, OutputT>
extends PTransform<PCollection<InputT>, PCollection<OutputT>> {
TypeDescriptor<OutputT> outputTypeDescriptor;
ConvertTransform(TypeDescriptor<OutputT> outputTypeDescriptor) {
this.outputTypeDescriptor = outputTypeDescriptor;
}
private static @Nullable Schema getBoxedNestedSchema(Schema schema) {
if (schema.getFieldCount() != 1) {
return null;
}
FieldType fieldType = schema.getField(0).getType();
if (!fieldType.getTypeName().isCompositeType()) {
return null;
}
return fieldType.getRowSchema();
}
@Override
@SuppressWarnings("unchecked")
public PCollection<OutputT> expand(PCollection<InputT> input) {
if (!input.hasSchema()) {
throw new RuntimeException("Convert requires a schema on the input.");
}
SchemaRegistry registry = input.getPipeline().getSchemaRegistry();
ConvertHelpers.ConvertedSchemaInformation<OutputT> converted =
ConvertHelpers.getConvertedSchemaInformation(
input.getSchema(), outputTypeDescriptor, registry);
boolean unbox = converted.unboxedType != null;
PCollection<OutputT> output;
if (converted.outputSchemaCoder != null) {
output =
input.apply(
ParDo.of(
new DoFn<InputT, OutputT>() {
@ProcessElement
public void processElement(@Element Row row, OutputReceiver<OutputT> o) {
// Read the row, potentially unboxing if necessary.
Object input = unbox ? row.getValue(0) : row;
// The output has a schema, so we need to convert to the appropriate type.
o.output(
converted.outputSchemaCoder.getFromRowFunction().apply((Row) input));
}
}));
output.setCoder(converted.outputSchemaCoder);
} else {
SerializableFunction<?, OutputT> convertPrimitive =
ConvertHelpers.getConvertPrimitive(
converted.unboxedType, outputTypeDescriptor, new DefaultTypeConversionsFactory());
output =
input.apply(
ParDo.of(
new DoFn<InputT, OutputT>() {
@ProcessElement
public void processElement(@Element Row row, OutputReceiver<OutputT> o) {
o.output(convertPrimitive.apply(row.getValue(0)));
}
}));
output.setTypeDescriptor(outputTypeDescriptor);
// TODO: Support boxing in Convert (e.g. Long -> Row with Schema { Long }).
}
return output;
}
}
}
| [BEAM-11571] Don't transform if input and output types are equal on Convert transform
| sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java | [BEAM-11571] Don't transform if input and output types are equal on Convert transform | <ide><path>dks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/Convert.java
<ide> import org.apache.beam.sdk.annotations.Experimental.Kind;
<ide> import org.apache.beam.sdk.schemas.Schema;
<ide> import org.apache.beam.sdk.schemas.Schema.FieldType;
<add>import org.apache.beam.sdk.schemas.SchemaCoder;
<ide> import org.apache.beam.sdk.schemas.SchemaRegistry;
<ide> import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.DefaultTypeConversionsFactory;
<ide> import org.apache.beam.sdk.schemas.utils.ConvertHelpers;
<ide> throw new RuntimeException("Convert requires a schema on the input.");
<ide> }
<ide>
<add> SchemaCoder<InputT> coder = (SchemaCoder<InputT>) input.getCoder();
<add> if (coder.getEncodedTypeDescriptor().equals(outputTypeDescriptor)) {
<add> return (PCollection<OutputT>) input;
<add> }
<ide> SchemaRegistry registry = input.getPipeline().getSchemaRegistry();
<ide> ConvertHelpers.ConvertedSchemaInformation<OutputT> converted =
<ide> ConvertHelpers.getConvertedSchemaInformation( |
|
Java | apache-2.0 | e7dddb7107085f57d1c9881aae41d5cea2bf7062 | 0 | ST-DDT/CrazyLogin,ST-DDT/CrazyLogin | package de.st_ddt.crazylogin;
import java.util.Date;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class CrazyLoginPlayerListener implements Listener
{
private final CrazyLogin plugin;
private final HashMap<String, Location> savelogin = new HashMap<String, Location>();
public CrazyLoginPlayerListener(final CrazyLogin plugin)
{
super();
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void PlayerLogin(final PlayerLoginEvent event)
{
final Player player = event.getPlayer();
if (!plugin.checkNameLength(event.getPlayer().getName()))
{
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "NAME.INVALIDLENGTH", plugin.getMinNameLength(), plugin.getMaxNameLength()));
return;
}
if (plugin.isForceSingleSessionEnabled())
if (player.isOnline())
{
if (plugin.isForceSingleSessionSameIPBypassEnabled())
if (player.getAddress() != null)
if (event.getAddress().getHostAddress().equals(player.getAddress().getAddress().getHostAddress()))
if (event.getAddress().getHostName().equals(player.getAddress().getAddress().getHostName()))
return;
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "SESSION.DUPLICATE"));
plugin.broadcastLocaleMessage(true, "crazylogin.warnsession", "SESSION.DUPLICATEWARN", event.getAddress().getHostAddress(), player.getName());
plugin.sendLocaleMessage("SESSION.DUPLICATEWARN", player, event.getAddress().getHostAddress(), player.getName());
}
}
@EventHandler
public void PlayerJoin(final PlayerJoinEvent event)
{
final Player player = event.getPlayer();
if (savelogin.get(player.getName().toLowerCase()) != null)
player.teleport(savelogin.get(player.getName().toLowerCase()), TeleportCause.PLUGIN);
if (!plugin.hasAccount(player))
{
if (plugin.isAlwaysNeedPassword())
plugin.sendLocaleMessage("REGISTER.HEADER", player);
else
plugin.sendLocaleMessage("REGISTER.HEADER2", player);
plugin.sendLocaleMessage("REGISTER.MESSAGE", player);
final int autoKick = plugin.getAutoKickUnregistered();
if (plugin.isAlwaysNeedPassword() || autoKick != -1)
if (savelogin.get(player.getName().toLowerCase()) == null)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
if (autoKick != -1)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("REGISTER.REQUEST"), true), autoKick * 20);
return;
}
final LoginData playerdata = plugin.getPlayerData(player);
if (!playerdata.hasIP(player.getAddress().getAddress().getHostAddress()))
playerdata.logout();
if (plugin.isAutoLogoutEnabled())
if (plugin.getAutoLogoutTime() * 1000 + playerdata.getLastActionTime().getTime() < new Date().getTime())
playerdata.logout();
if (plugin.isLoggedIn(player))
return;
if (savelogin.get(player.getName().toLowerCase()) == null)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
plugin.sendLocaleMessage("LOGIN.REQUEST", player);
final int autoKick = plugin.getAutoKick();
if (autoKick >= 10)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("LOGIN.REQUEST")), autoKick * 20);
}
@EventHandler
public void PlayerQuit(final PlayerQuitEvent event)
{
final Player player = event.getPlayer();
final LoginData playerdata = plugin.getPlayerData(player);
if (playerdata != null)
{
if (!plugin.isLoggedIn(player))
return;
playerdata.notifyAction();
if (plugin.isInstantAutoLogoutEnabled())
playerdata.logout();
}
}
@EventHandler
public void PlayerDropItem(final PlayerDropItemEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteract(final PlayerInteractEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteractEntity(final PlayerInteractEntityEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerMove(final PlayerMoveEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
final Location current = savelogin.get(player.getName().toLowerCase());
if (current != null)
if (current.getWorld() == event.getTo().getWorld())
if (current.distance(event.getTo()) < plugin.getMoveRange())
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerTeleport(final PlayerTeleportEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
if (savelogin.get(player.getName().toLowerCase()) == null)
return;
if (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.UNKNOWN)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
final Location target = event.getTo();
if (target.distance(target.getWorld().getSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
if (player.getBedSpawnLocation() != null)
if (target.getWorld() == player.getBedSpawnLocation().getWorld())
if (target.distance(player.getBedSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerDamage(final EntityDamageEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByBlockEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByEntityEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerPreCommand(final PlayerCommandPreprocessEvent event)
{
final Player player = event.getPlayer();
if (!plugin.isBlockingGuestCommandsEnabled() || plugin.hasAccount(player))
if (plugin.isLoggedIn(player))
return;
final String message = event.getMessage().toLowerCase();
if (message.startsWith("/"))
{
if (message.startsWith("/login") || message.startsWith("/crazylogin password") || message.startsWith("/crazylanguage") || message.startsWith("/language") || message.startsWith("/register"))
return;
for (final String command : plugin.getCommandWhiteList())
if (message.startsWith(command))
return;
event.setCancelled(true);
plugin.broadcastLocaleMessage(true, "crazylogin.warncommandexploits", "COMMAND.EXPLOITWARN", player.getName(), player.getAddress().getAddress().getHostAddress(), message);
if (plugin.isAutoKickCommandUsers())
{
player.kickPlayer(plugin.getLocale().getLocaleMessage(player, "LOGIN.REQUEST"));
return;
}
plugin.requestLogin(event.getPlayer());
return;
}
}
@EventHandler
public void PlayerCommand(final PlayerChatEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
public void notifyLogin(Player player)
{
savelogin.remove(player.getName().toLowerCase());
}
}
| src/de/st_ddt/crazylogin/CrazyLoginPlayerListener.java | package de.st_ddt.crazylogin;
import java.util.Date;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class CrazyLoginPlayerListener implements Listener
{
private final CrazyLogin plugin;
private final HashMap<String, Location> savelogin = new HashMap<String, Location>();
public CrazyLoginPlayerListener(final CrazyLogin plugin)
{
super();
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void PlayerLogin(final PlayerLoginEvent event)
{
final Player player = event.getPlayer();
if (!plugin.checkNameLength(event.getPlayer().getName()))
{
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "NAME.INVALIDLENGTH", plugin.getMinNameLength(), plugin.getMaxNameLength()));
return;
}
if (plugin.isForceSingleSessionEnabled())
if (player.isOnline())
{
if (plugin.isForceSingleSessionSameIPBypassEnabled())
if (player.getAddress() != null)
if (event.getAddress().getHostAddress().equals(player.getAddress().getAddress().getHostAddress()))
if (event.getAddress().getHostName().equals(player.getAddress().getAddress().getHostName()))
return;
event.setResult(Result.KICK_OTHER);
event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "SESSION.DUPLICATE"));
plugin.broadcastLocaleMessage(true, "crazylogin.warnsession", "SESSION.DUPLICATEWARN", event.getAddress().getHostAddress(), player.getName());
plugin.sendLocaleMessage("SESSION.DUPLICATEWARN", player, event.getAddress().getHostAddress(), player.getName());
}
}
@EventHandler
public void PlayerJoin(final PlayerJoinEvent event)
{
final Player player = event.getPlayer();
if (savelogin.get(player.getName().toLowerCase()) != null)
player.teleport(savelogin.get(player.getName().toLowerCase()), TeleportCause.PLUGIN);
if (!plugin.hasAccount(player))
{
if (plugin.isAlwaysNeedPassword())
plugin.sendLocaleMessage("REGISTER.HEADER", player);
else
plugin.sendLocaleMessage("REGISTER.HEADER2", player);
plugin.sendLocaleMessage("REGISTER.MESSAGE", player);
final int autoKick = plugin.getAutoKickUnregistered();
if (plugin.isAlwaysNeedPassword() || autoKick != -1)
if (savelogin.get(player.getName().toLowerCase()) == null)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
if (autoKick != -1)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("REGISTER.REQUEST"), true), autoKick * 20);
return;
}
final LoginData playerdata = plugin.getPlayerData(player);
if (!playerdata.hasIP(player.getAddress().getAddress().getHostAddress()))
playerdata.logout();
if (plugin.isAutoLogoutEnabled())
if (plugin.getAutoLogoutTime() * 1000 + playerdata.getLastActionTime().getTime() < new Date().getTime())
playerdata.logout();
if (plugin.isLoggedIn(player))
return;
if (savelogin.get(player.getName().toLowerCase()) == null)
savelogin.put(player.getName().toLowerCase(), player.getLocation());
plugin.sendLocaleMessage("LOGIN.REQUEST", player);
final int autoKick = plugin.getAutoKick();
if (autoKick >= 10)
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("LOGIN.REQUEST")), autoKick * 20);
}
@EventHandler
public void PlayerQuit(final PlayerQuitEvent event)
{
final Player player = event.getPlayer();
final LoginData playerdata = plugin.getPlayerData(player);
if (playerdata != null)
{
if (!plugin.isLoggedIn(player))
return;
playerdata.notifyAction();
if (plugin.isInstantAutoLogoutEnabled())
playerdata.logout();
}
}
@EventHandler
public void PlayerDropItem(final PlayerDropItemEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteract(final PlayerInteractEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerInteractEntity(final PlayerInteractEntityEvent event)
{
if (plugin.isLoggedIn(event.getPlayer()))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerMove(final PlayerMoveEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
final Location current = savelogin.get(player.getName().toLowerCase());
if (current != null)
if (current.getWorld() == event.getTo().getWorld())
if (current.distance(event.getTo()) < plugin.getMoveRange())
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerTeleport(final PlayerTeleportEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
if (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.UNKNOWN)
return;
final Location target = event.getTo();
if (target.distance(target.getWorld().getSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
if (player.getBedSpawnLocation() != null)
if (target.getWorld() == player.getBedSpawnLocation().getWorld())
if (target.distance(player.getBedSpawnLocation()) < 10)
{
savelogin.put(player.getName().toLowerCase(), event.getTo());
return;
}
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
@EventHandler
public void PlayerDamage(final EntityDamageEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByBlockEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerDamage(final EntityDamageByEntityEvent event)
{
if (!(event.getEntity() instanceof Player))
return;
final Player player = (Player) event.getEntity();
if (plugin.isLoggedIn(player))
return;
Location location = player.getBedSpawnLocation();
if (location == null)
location = player.getWorld().getSpawnLocation();
player.teleport(location, TeleportCause.PLUGIN);
event.setCancelled(true);
}
@EventHandler
public void PlayerPreCommand(final PlayerCommandPreprocessEvent event)
{
final Player player = event.getPlayer();
if (!plugin.isBlockingGuestCommandsEnabled() || plugin.hasAccount(player))
if (plugin.isLoggedIn(player))
return;
final String message = event.getMessage().toLowerCase();
if (message.startsWith("/"))
{
if (message.startsWith("/login") || message.startsWith("/crazylogin password") || message.startsWith("/crazylanguage") || message.startsWith("/language") || message.startsWith("/register"))
return;
for (final String command : plugin.getCommandWhiteList())
if (message.startsWith(command))
return;
event.setCancelled(true);
plugin.broadcastLocaleMessage(true, "crazylogin.warncommandexploits", "COMMAND.EXPLOITWARN", player.getName(), player.getAddress().getAddress().getHostAddress(), message);
if (plugin.isAutoKickCommandUsers())
{
player.kickPlayer(plugin.getLocale().getLocaleMessage(player, "LOGIN.REQUEST"));
return;
}
plugin.requestLogin(event.getPlayer());
return;
}
}
@EventHandler
public void PlayerCommand(final PlayerChatEvent event)
{
final Player player = event.getPlayer();
if (plugin.isLoggedIn(player))
return;
event.setCancelled(true);
plugin.requestLogin(event.getPlayer());
}
public void notifyLogin(Player player)
{
savelogin.remove(player.getName().toLowerCase());
}
}
| CrazyLogin: code improvements on teleport for saveLogin | src/de/st_ddt/crazylogin/CrazyLoginPlayerListener.java | CrazyLogin: code improvements on teleport for saveLogin | <ide><path>rc/de/st_ddt/crazylogin/CrazyLoginPlayerListener.java
<ide> final Player player = event.getPlayer();
<ide> if (plugin.isLoggedIn(player))
<ide> return;
<add> if (savelogin.get(player.getName().toLowerCase()) == null)
<add> return;
<ide> if (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.UNKNOWN)
<del> return;
<add> {
<add> savelogin.put(player.getName().toLowerCase(), event.getTo());
<add> return;
<add> }
<ide> final Location target = event.getTo();
<ide> if (target.distance(target.getWorld().getSpawnLocation()) < 10)
<ide> { |
|
JavaScript | mit | d28fcfb0c42c7a08d18eb815d4e4519ec87e1b7d | 0 | riyazdf/consoleJSON,riyazdf/consoleJSON,riyazdf/consoleJSON | var consoleJSON = consoleJSON || {};
consoleJSON.Util = consoleJSON.Util || {};
var DELIMITER = " ";
var LINE_LENGTH = 80;
var CONSOLE_STYLE_SPECIFIER = "%c";
consoleJSON.TYPES = {
FILTER : "filter",
STYLE : "style",
FORMAT : "format"
};
consoleJSON.TARGETS = {
KEY : "key",
VAL : "val",
NUM : "number",
STR : "string",
BOOL : "boolean",
NULL : "null",
UNDEF : "undefined",
ARR : "array",
OBJ : "object",
ALL : "all",
UNUSED : "unused"
};
consoleJSON.ATTRS = {
HIDE : "hide",
REMOVE : "remove",
HIGHLIGHT : "highlight",
FONT_COLOR : "font_color",
FONT_SIZE : "font_size",
FONT_STYLE : "font_style",
FONT_WEIGHT : "font_weight",
FONT_FAMILY : "font_family",
LINE_LEN : "line_length",
INSERT_NEWLINE : "insert_newline",
INDENT_AMT : "indent_amt"
};
consoleJSON.ATTR_TO_CSS = {};
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.HIGHLIGHT] = "background";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_COLOR] = "color";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_SIZE] = "font-size";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_STYLE] = "font-style";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT] = "font-weight";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_FAMILY] = "font-family";
consoleJSON.BEGIN_DELIM = {};
consoleJSON.BEGIN_DELIM[consoleJSON.TARGETS.ARR] = "[";
consoleJSON.BEGIN_DELIM[consoleJSON.TARGETS.OBJ] = "{";
consoleJSON.END_DELIM = {};
consoleJSON.END_DELIM[consoleJSON.TARGETS.ARR] = "]";
consoleJSON.END_DELIM[consoleJSON.TARGETS.OBJ] = "}";
consoleJSON.SEP = {};
consoleJSON.SEP[consoleJSON.TARGETS.ARR] = ",";
consoleJSON.SEP[consoleJSON.TARGETS.OBJ] = ",";
consoleJSON.KEY_VAL_SEP = {};
consoleJSON.KEY_VAL_SEP[consoleJSON.TARGETS.OBJ] = ": ";
consoleJSON.log = function(json, ruleset) {
// pretty prints JSON to console according to given ruleset
// obj is a Javascript object, ruleset is a consoleJSON ruleset
ruleset = ruleset || new consoleJSON.Ruleset();
var beginD = consoleJSON.getDelimiter(json, ruleset, consoleJSON.BEGIN_DELIM);
if (beginD) {
consoleJSON.startGroup([beginD[0]], [beginD[1]], 0, DELIMITER, LINE_LENGTH);
}
consoleJSON.traverse(json, ruleset, 1);
var endD = consoleJSON.getDelimiter(json, ruleset, consoleJSON.END_DELIM);
if (endD) {
consoleJSON.print([endD[0]], [endD[1]], 0, DELIMITER, LINE_LENGTH);
consoleJSON.endGroup();
}
//console.log(json);
};
// TODO: add show hierarchy flag, for now we're just removing instead of hiding
// afang
consoleJSON.filter = function(json, filterKey, ruleset) {
// Filter out subtrees of the json, third parameter is optional.
//var removeRule = consoleJSON.Rule(consoleJSON.TYPES.FILTER, consoleJSON.ATTRS.REMOVE, null);
// Maybe here need to check to see if remove rule exists already?
//ruleset.addGlobalRule(removeRule);
ruleset = ruleset || new consoleJSON.Ruleset();
var doFilter = ruleset.getDoFilter();
ruleset.setDoFilter(true);
ruleset.addFilterKey(filterKey);
consoleJSON.log(json, ruleset);
ruleset.removeFilterKey(filterKey);
ruleset.setDoFilter(doFilter);
//ruleset.removeGlobalRule(removeRule);
};
consoleJSON.traverse = function(json, ruleset, lvl) {
// traverses the json tree
// lvl is the depth of the current node (for indentation)
var type = $.type(json);
switch (type) {
case 'array':
consoleJSON.traverseArray(json, ruleset, lvl);
break;
case 'object':
consoleJSON.traverseObject(json, ruleset, lvl);
break;
default:
var output = consoleJSON.outputPrimitive(json, ruleset, null, false);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
consoleJSON.print([output[0]], [output[1]], lvl, DELIMITER, lineLen);
}
};
consoleJSON.traverseArray = function(jsonArray, ruleset, lvl) {
// Traverses an array data type (called from traverse)
// Handles delimiters and groupings, and other printing rules for arrs
var sep = consoleJSON.getDelimiter(jsonArray, ruleset, consoleJSON.SEP);
var sepTarget = sep[0];
var sepStyle = sep[1];
for (var i = 0; i < jsonArray.length; i++) {
var el = jsonArray[i];
var type = $.type(el);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
if (ruleset[consoleJSON.ATTRS.INDENT_AMT]) {
lvl = ruleset[consoleJSON.ATTRS.INDENT_AMT];
}
switch (type) {
case 'array':
case 'object':
var beginD = consoleJSON.getDelimiter(el, ruleset, consoleJSON.BEGIN_DELIM);
consoleJSON.startGroup([beginD[0]], [beginD[1]], lvl, DELIMITER, lineLen);
consoleJSON.traverse(el, ruleset, lvl+1);
var endD = consoleJSON.getDelimiter(el, ruleset, consoleJSON.END_DELIM);
var endDTargets = [endD[0]];
var endDStyles = [endD[1]];
if (i < jsonArray.length-1) {
endDTargets.push(sepTarget);
endDStyles.push(sepStyle);
}
consoleJSON.print(endDTargets, endDStyles, lvl, DELIMITER, lineLen);
consoleJSON.endGroup();
break;
default:
var output = consoleJSON.outputVal(el, ruleset, null);
var outputTargets = [output[0]];
var outputStyles = [output[1]];
if (i < jsonArray.length-1) {
outputTargets.push(sepTarget);
outputStyles.push(sepStyle);
}
consoleJSON.print(outputTargets, outputStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
}
}
};
consoleJSON.traverseObject = function(jsonObj, ruleset, lvl) {
// Traverses an object data type (called from traverse)
// Handles delimiters and groupings, and other printing rules for objs
// var ruleset = ruleset || {};
var sep = consoleJSON.getDelimiter(jsonObj, ruleset, consoleJSON.SEP);
var sepTarget = sep[0];
var sepStyle = sep[1];
var keyValSep = consoleJSON.getDelimiter(jsonObj, ruleset, consoleJSON.KEY_VAL_SEP);
var keyValSepTarget = keyValSep[0];
var keyValSepStyle = keyValSep[1];
var keys = Object.keys(jsonObj);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
if (ruleset[consoleJSON.ATTRS.INDENT_AMT]) {
lvl = ruleset[consoleJSON.ATTRS.INDENT_AMT];
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var keyOutput = consoleJSON.outputKey(key, ruleset, key);
var keyOutputTargets = [keyOutput[0]];
var keyOutputStyles = [keyOutput[1]];
var val = jsonObj[key];
var valType = $.type(val);
if ((!ruleset.getDoFilter()) || (ruleset.getDoFilter() && $.inArray(key, ruleset.getFilterKeys()) != -1)) {
switch (valType) {
case 'array':
case 'object':
var doingFilter = ruleset.getDoFilter();
//console.log(doingFilter);
if (doingFilter) {
ruleset.setDoFilter(false);
}
var beginD = consoleJSON.getDelimiter(val, ruleset, consoleJSON.BEGIN_DELIM);
var beginDTargets = keyOutputTargets.concat(keyValSepTarget, beginD[0]);
var beginDStyles = keyOutputStyles.concat(keyValSepStyle, beginD[1]);
consoleJSON.startGroup(beginDTargets, beginDStyles, lvl, DELIMITER, lineLen);
consoleJSON.traverse(val, ruleset, lvl+1);
ruleset.setDoFilter(doingFilter);
var endD = consoleJSON.getDelimiter(val, ruleset, consoleJSON.END_DELIM);
var endDTargets = [endD[0]];
var endDStyles = [endD[1]];
if (i < keys.length-1) {
endDTargets.push(sepTarget);
endDStyles.push(sepStyle);
}
consoleJSON.print(endDTargets, endDStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
consoleJSON.endGroup();
break;
default:
var output = consoleJSON.outputVal(val, ruleset, key);
var outputTargets = [output[0]];
var outputStyles = [output[1]];
if (i < keys.length-1) {
outputTargets.push(sepTarget);
outputStyles.push(sepStyle);
}
var outputKeyValTargets = keyOutputTargets.concat(keyValSepTarget, outputTargets);
var outputKeyValStyles = keyOutputStyles.concat(keyValSepStyle, outputStyles);
consoleJSON.print(outputKeyValTargets, outputKeyValStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
}
} else if (valType == 'array' || valType == 'object') {
//console.log('watatata');
consoleJSON.traverse(val, ruleset, lvl);
}
}
};
// TODO: passed in ruleset should be for child object/array
consoleJSON.getDelimiter = function(json, ruleset, delimDict) {
// Function to handle the closing delimiter for arrays, objs, etc.
var type = $.type(json);
if (!(type in delimDict)) {
return null;
}
var target = delimDict[type];
var rules = ruleset.lookupRules(null);
var matchingRules = consoleJSON.Util.findMatchingStyleRules(rules, json, false)
var style = consoleJSON.Util.rulesToCSS(matchingRules);
return [target, style];
};
consoleJSON.outputPrimitive = function(json, ruleset, key, isKey) {
// Prints a primitive to the output, subject to a ruleset
var target = json;
var type = $.type(json);
switch (type) {
case consoleJSON.TARGETS.STR:
if (!isKey) {
target = '\"' + json + '\"';
}
break;
}
var rules = ruleset.lookupRules(key);
var matchingRules = consoleJSON.Util.findMatchingStyleRules(rules, json, isKey)
var style = consoleJSON.Util.rulesToCSS(matchingRules);
return [target, style];
};
consoleJSON.outputKey = function(json, ruleset, key) {
// Prints a key to the output, subject to a ruleset
return consoleJSON.outputPrimitive(json, ruleset, key, true);
};
consoleJSON.outputVal = function(json, ruleset, key) {
// Prints a value to the output, subject to a ruleset
return consoleJSON.outputPrimitive(json, ruleset, key, false);
};
// TODO: this also breaks words apart. fix this
// TODO: ignore %c
consoleJSON.indentWrap = function(target, indentationLvl, delimiter, lineLen) {
// A function to handle word wrapping in the console output
var indent = delimiter.repeat(indentationLvl);
var remainingLen = lineLen - indent.length;
var result = "";
var currPos = 0;
while (currPos+remainingLen < target.length) {
result += indent + target.substring(currPos,currPos+remainingLen) + "\n";
currPos += remainingLen;
}
result += indent + target.substring(currPos);
return result;
};
consoleJSON.print = function(targets, styles, indentationLvl, delimiter, lineLen) {
// Function to write word-wrapped data to console output
// TODO: fix indentWrap to ignore %c
//var output = consoleJSON.indentWrap(target, indentationLvl, delimiter);
console.log.apply(console, consoleJSON.Util.formatForConsole(targets, styles, indentationLvl, lineLen));
};
consoleJSON.startGroup = function(targets, styles, indentationLvl, delimiter, lineLen) {
// Begin a console grouping
// TODO: fix indentWrap to ignore %c
//var output = consoleJSON.indentWrap(target, indentationLvl, delimiter);
// default style for group start is bold; undo this
for (var i = 0; i < styles.length; i++) {
var css = styles[i];
if (css.indexOf(consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT]) == -1) {
styles[i] = css + ";" + consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT] + ":" + "normal";
}
}
console.group.apply(console, consoleJSON.Util.formatForConsole(targets, styles, indentationLvl, lineLen));
};
consoleJSON.endGroup = function() {
// Finish a console grouping
console.groupEnd();
};
/**
* BEGIN RULESET & RULES PORTION OF CODE
*/
consoleJSON.Ruleset = function() {
// Constructor for Ruleset
this.nestedRulesets = {}; // map from key to Ruleset
this.globalRules = []; // list of Rules
this.filterKeysList = []; // keys to filter, used for filtering
this.doFilter = false; // a flag to tell the traverser whether or not to do filtering
// TODO: Initialize default values
this.addGlobalRule(["style","font_weight","bold","key"])
.addGlobalRule(["style","font_color","black","key"])
.addGlobalRule(["style","font_color","#606aa1","string"])
.addGlobalRule(["style","font_color","#4ea1df","number"])
.addGlobalRule(["style","font_color","#da564a","boolean"])
.addGlobalRule(["style","font_size","12px","all"])
.addGlobalRule(["style","font_family","Verdana, Geneva, sans-serif","all"])
};
// TODO: add mechanism for dot notation in keys specified by user (generate internal nested rulesets automatically)
consoleJSON.Ruleset.prototype.addRuleset = function(key, ruleset) {
// Add a key-specific, nested ruleset to the ruleset.
// TODO: If ruleset for key already exists, merge existing ruleset with new ruleset?
this.nestedRulesets[key] = ruleset;
return this;
};
consoleJSON.Ruleset.prototype.addRule = function(key, ruleOrParams) {
// Add a key-specific rule to the ruleset (convenience function).
// If there's an existing rule for the same key with all fields matching except value, overwrites the existing value.
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.nestedRulesets[key] = this.nestedRulesets[key] || new consoleJSON.Ruleset();
this.nestedRulesets[key].addGlobalRule(rule);
return this;
};
consoleJSON.Ruleset.prototype.addGlobalRule = function(ruleOrParams) {
// Add a global rule to the ruleset.
// If there's an existing global rule with all fields matching except value, overwrites the existing value.
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.globalRules = consoleJSON.Util.addRule(this.globalRules, rule, consoleJSON.Util.rulesEqual);
return this;
};
consoleJSON.Ruleset.prototype.removeRuleset = function(key) {
// Remove a key-specific, nested ruleset from the ruleset, if it exists.
// TODO: clean up empty rulesets
delete this.nestedRulesets[key];
return this;
};
consoleJSON.Ruleset.prototype.removeRule = function(key, ruleOrParams) {
// Remove a key-specific rule from the ruleset, if it exists (convenience function).
// TODO: clean up empty rulesets
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
if (key in this.nestedRulesets) {
this.nestedRulesets[key].removeGlobalRule(rule);
}
return this;
};
consoleJSON.Ruleset.prototype.removeGlobalRule = function(ruleOrParams) {
// Remove a global rule from the ruleset, if it exists.
// TODO: clean up empty rulesets
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.globalRules = consoleJSON.Util.removeRule(this.globalRules, rule, consoleJSON.Util.rulesEqual);
return this;
};
consoleJSON.Ruleset.prototype.addFilterKey = function(filterKey) {
if ($.type(filterKey) == 'array') {
this.filterKeysList = this.filterKeysList.concat(filterKey);
} else if ($.type(filterKey) == 'string') {
this.filterKeysList = this.filterKeysList.concat(filterKey);
}
}
consoleJSON.Ruleset.prototype.removeFilterKey = function(filterKey) {
if ($.type(filterKey) == 'array') {
for (var i = 0; i < filterKey.length; i++) {
this.filterKeysList = this.filterKeysList.splice($.inArray(filterKey[i], this.filterKeysList), 1);
}
} else if ($.type(filterKey) == 'string') {
this.filterKeysList = this.filterKeysList.splice($.inArray(filterKey, this.filterKeysList), 1);
}
}
consoleJSON.Ruleset.prototype.getFilterKeys = function() {
return this.filterKeysList;
}
consoleJSON.Ruleset.prototype.setDoFilter = function(shouldDoFilter) {
this.doFilter = shouldDoFilter;
return this.doFilter;
}
consoleJSON.Ruleset.prototype.getDoFilter = function() {
return this.doFilter;
}
consoleJSON.Ruleset.prototype.lookupRules = function(key) {
// Finds matching rules in this ruleset for the given key, adhering to precedence for rules that specify the same attribute.
// key can be either null (global rule) or string-valued (key-specific rules).
var matchingRules = [];
if (key !== null) {
// look first in key-specific rulesets
if (key in this.nestedRulesets) {
matchingRules = matchingRules.concat(this.nestedRulesets[key].globalRules);
}
}
// then add global rules
for (var i = 0; i < this.globalRules.length; i++) {
var rule = this.globalRules[i];
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, rule, consoleJSON.Util.rulesEqual);
}
//console.log(matchingRules);
return matchingRules;
};
consoleJSON.Rule = function(type, attr, val, target) {
// Constructor for Rule
// target is only valid if type == consoleJSON.TYPES.STYLE
this.type = type;
this.attr = attr;
this.val = val;
this.target = type == consoleJSON.TYPES.STYLE ? target : consoleJSON.TARGETS.UNUSED;
};
/**
* BEGIN UTIL FUNCTIONS PORTION OF CODE
*/
consoleJSON.Util.addRule = function(ruleList, rule, isMatchFn) {
// If there's an existing rule in ruleList with all fields matching the given rule except value, overwrites the existing value.
// Otherwise, appends rule to ruleList.
// Returns the modified ruleList.
var matchFound = false;
for (var i in ruleList) {
var existingRule = ruleList[i];
if (isMatchFn(existingRule, rule)) {
existingRule.val = rule.val;
matchFound = true;
}
}
if (!matchFound) {
ruleList.push(rule);
}
return ruleList;
};
consoleJSON.Util.addRuleNoOverwrite = function(ruleList, rule, isMatchFn) {
// Appends rule to ruleList only if there's no existing rule in ruleList with all fields matching the given rule except value.
// Returns the modified ruleList.
var matchFound = false;
for (var i in ruleList) {
if (isMatchFn(ruleList[i], rule)) {
matchFound = true;
break;
}
}
if (!matchFound) {
ruleList.push(rule);
}
return ruleList;
};
consoleJSON.Util.removeRule = function(ruleList, rule, isMatchFn) {
// If there's an existing rule in ruleList with all fields matching the given rule except value, removes it.
// Returns the modified ruleList.
for (var i = 0; i < ruleList.length; i++) {
var existingRule = ruleList[i];
if (isMatchFn(ruleList[i], rule)) {
ruleList.splice(i,1);
i--;
}
}
return ruleList;
};
consoleJSON.Util.findMatchingRules = function(ruleList, type, attr, target) {
// Returns all rules in ruleList whose fields match all non-null input fields.
var matchingRules = [];
for (var i = 0; i < ruleList.length; i++) {
var existingRule = ruleList[i];
if ((type === null || existingRule.type == type) &&
(attr === null || existingRule.attr == attr) &&
(target === null || existingRule.target == target)) {
matchingRules.push(existingRule);
}
}
return matchingRules;
};
consoleJSON.Util.findMatchingStyleRules = function(ruleList, json, isKey) {
// Returns all matching style rules for json in ruleList, where isKey determines if the json represents a key or a value.
// first add rules pertaining to target=key/val,
// then add rules pertaining to target=<primitive>/obj/array if no conflicts,
// then add rules pertaining to target=all if no conflicts
var type = $.type(json);
var typeInJson = isKey ? consoleJSON.TARGETS.KEY : consoleJSON.TARGETS.VAL;
var matchingRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, typeInJson);
var matchingTypeRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, type);
for (var i = 0; i < matchingTypeRules.length; i++) {
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, matchingTypeRules[i], consoleJSON.Util.rulesTypeAttrEqual);
}
var matchingAllRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, consoleJSON.TARGETS.ALL);
for (var i = 0; i < matchingAllRules.length; i++) {
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, matchingAllRules[i], consoleJSON.Util.rulesTypeAttrEqual);
}
//console.log(matchingRules);
return matchingRules;
};
consoleJSON.Util.rulesEqual = function(rule1, rule2) {
// Returns whether or not the two rules are the same (with only the attribute value as a possible difference).
return rule1.type == rule2.type && rule1.attr == rule2.attr && rule1.target == rule2.target;
};
consoleJSON.Util.rulesTypeAttrEqual = function(rule1, rule2) {
// Returns whether or not the two rules are the same (with only the attribute value, targets as possible differences).
return rule1.type == rule2.type && rule1.attr == rule2.attr;
};
consoleJSON.Util.formatForConsole = function(targets, styles, indentationLvl, lineLen) {
// Formats the targets and styles into the array expected by console.
// TODO: replace with indentAndWrap, handle indentationLvl, lineLen
var indent = DELIMITER.repeat(indentationLvl);
var targetStr = indent + CONSOLE_STYLE_SPECIFIER + targets.join(CONSOLE_STYLE_SPECIFIER);
var consoleFormattedArr = [targetStr];
return consoleFormattedArr.concat(styles);
};
consoleJSON.Util.rulesToCSS = function(ruleList) {
// Returns a CSS string that contains all styles specified by rules in ruleList.
var cssStrings = [];
for (var i = 0; i < ruleList.length; i++) {
var rule = ruleList[i];
if (rule.type == consoleJSON.TYPES.STYLE) {
cssStrings.push(consoleJSON.ATTR_TO_CSS[rule.attr] + ":" + rule.val);
}
}
return cssStrings.join(";");
};
// From http://stackoverflow.com/questions/202605/repeat-string-javascript
String.prototype.repeat = function(num) {
return new Array(num+1).join(this);
};
| code/consoleJSON.js | var consoleJSON = consoleJSON || {};
consoleJSON.Util = consoleJSON.Util || {};
var DELIMITER = " ";
var LINE_LENGTH = 80;
var CONSOLE_STYLE_SPECIFIER = "%c";
consoleJSON.TYPES = {
FILTER : "filter",
STYLE : "style",
FORMAT : "format"
};
consoleJSON.TARGETS = {
KEY : "key",
VAL : "val",
NUM : "number",
STR : "string",
BOOL : "boolean",
NULL : "null",
UNDEF : "undefined",
ARR : "array",
OBJ : "object",
ALL : "all",
UNUSED : "unused"
};
consoleJSON.ATTRS = {
HIDE : "hide",
REMOVE : "remove",
HIGHLIGHT : "highlight",
FONT_COLOR : "font_color",
FONT_SIZE : "font_size",
FONT_STYLE : "font_style",
FONT_WEIGHT : "font_weight",
FONT_FAMILY : "font_family",
LINE_LEN : "line_length",
INSERT_NEWLINE : "insert_newline",
INDENT_AMT : "indent_amt"
};
consoleJSON.ATTR_TO_CSS = {};
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.HIGHLIGHT] = "background";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_COLOR] = "color";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_SIZE] = "font-size";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_STYLE] = "font-style";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT] = "font-weight";
consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_FAMILY] = "font-family";
consoleJSON.BEGIN_DELIM = {};
consoleJSON.BEGIN_DELIM[consoleJSON.TARGETS.ARR] = "[";
consoleJSON.BEGIN_DELIM[consoleJSON.TARGETS.OBJ] = "{";
consoleJSON.END_DELIM = {};
consoleJSON.END_DELIM[consoleJSON.TARGETS.ARR] = "]";
consoleJSON.END_DELIM[consoleJSON.TARGETS.OBJ] = "}";
consoleJSON.SEP = {};
consoleJSON.SEP[consoleJSON.TARGETS.ARR] = ",";
consoleJSON.SEP[consoleJSON.TARGETS.OBJ] = ",";
consoleJSON.KEY_VAL_SEP = {};
consoleJSON.KEY_VAL_SEP[consoleJSON.TARGETS.OBJ] = ": ";
consoleJSON.log = function(json, ruleset) {
// pretty prints JSON to console according to given ruleset
// obj is a Javascript object, ruleset is a consoleJSON ruleset
ruleset = ruleset || new consoleJSON.Ruleset();
var beginD = consoleJSON.getDelimiter(json, ruleset, consoleJSON.BEGIN_DELIM);
if (beginD) {
consoleJSON.startGroup([beginD[0]], [beginD[1]], 0, DELIMITER, LINE_LENGTH);
}
consoleJSON.traverse(json, ruleset, 1);
var endD = consoleJSON.getDelimiter(json, ruleset, consoleJSON.END_DELIM);
if (endD) {
consoleJSON.print([endD[0]], [endD[1]], 0, DELIMITER, LINE_LENGTH);
consoleJSON.endGroup();
}
//console.log(json);
};
// TODO: add show hierarchy flag, for now we're just removing instead of hiding
// afang
consoleJSON.filter = function(json, filterKey, ruleset) {
// Filter out subtrees of the json, third parameter is optional.
//var removeRule = consoleJSON.Rule(consoleJSON.TYPES.FILTER, consoleJSON.ATTRS.REMOVE, null);
// Maybe here need to check to see if remove rule exists already?
//ruleset.addGlobalRule(removeRule);
ruleset = ruleset || new consoleJSON.Ruleset();
var doFilter = ruleset.getDoFilter();
ruleset.setDoFilter(true);
ruleset.addFilterKey(filterKey);
consoleJSON.log(json, ruleset);
ruleset.removeFilterKey(filterKey);
ruleset.setDoFilter(doFilter);
//ruleset.removeGlobalRule(removeRule);
};
consoleJSON.traverse = function(json, ruleset, lvl) {
// traverses the json tree
// lvl is the depth of the current node (for indentation)
var type = $.type(json);
switch (type) {
case 'array':
consoleJSON.traverseArray(json, ruleset, lvl);
break;
case 'object':
consoleJSON.traverseObject(json, ruleset, lvl);
break;
default:
var output = consoleJSON.outputPrimitive(json, ruleset, null, false);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
consoleJSON.print([output[0]], [output[1]], lvl, DELIMITER, lineLen);
}
};
consoleJSON.traverseArray = function(jsonArray, ruleset, lvl) {
// Traverses an array data type (called from traverse)
// Handles delimiters and groupings, and other printing rules for arrs
var sep = consoleJSON.getDelimiter(jsonArray, ruleset, consoleJSON.SEP);
var sepTarget = sep[0];
var sepStyle = sep[1];
for (var i = 0; i < jsonArray.length; i++) {
var el = jsonArray[i];
var type = $.type(el);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
if (ruleset[consoleJSON.ATTRS.INDENT_AMT]) {
lvl = ruleset[consoleJSON.ATTRS.INDENT_AMT];
}
switch (type) {
case 'array':
case 'object':
var beginD = consoleJSON.getDelimiter(el, ruleset, consoleJSON.BEGIN_DELIM);
consoleJSON.startGroup([beginD[0]], [beginD[1]], lvl, DELIMITER, lineLen);
consoleJSON.traverse(el, ruleset, lvl+1);
var endD = consoleJSON.getDelimiter(el, ruleset, consoleJSON.END_DELIM);
var endDTargets = [endD[0]];
var endDStyles = [endD[1]];
if (i < jsonArray.length-1) {
endDTargets.push(sepTarget);
endDStyles.push(sepStyle);
}
consoleJSON.print(endDTargets, endDStyles, lvl, DELIMITER, lineLen);
consoleJSON.endGroup();
break;
default:
var output = consoleJSON.outputVal(el, ruleset, null);
var outputTargets = [output[0]];
var outputStyles = [output[1]];
if (i < jsonArray.length-1) {
outputTargets.push(sepTarget);
outputStyles.push(sepStyle);
}
consoleJSON.print(outputTargets, outputStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
}
}
};
consoleJSON.traverseObject = function(jsonObj, ruleset, lvl) {
// Traverses an object data type (called from traverse)
// Handles delimiters and groupings, and other printing rules for objs
// var ruleset = ruleset || {};
var sep = consoleJSON.getDelimiter(jsonObj, ruleset, consoleJSON.SEP);
var sepTarget = sep[0];
var sepStyle = sep[1];
var keyValSep = consoleJSON.getDelimiter(jsonObj, ruleset, consoleJSON.KEY_VAL_SEP);
var keyValSepTarget = keyValSep[0];
var keyValSepStyle = keyValSep[1];
var keys = Object.keys(jsonObj);
if (ruleset[consoleJSON.ATTRS.LINE_LENGTH]) {
var lineLen = ruleset[consoleJSON.ATTRS.LINE_LENGTH];
} else {
var lineLen = LINE_LENGTH;
}
if (ruleset[consoleJSON.ATTRS.INDENT_AMT]) {
lvl = ruleset[consoleJSON.ATTRS.INDENT_AMT];
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var keyOutput = consoleJSON.outputKey(key, ruleset, key);
var keyOutputTargets = [keyOutput[0]];
var keyOutputStyles = [keyOutput[1]];
var val = jsonObj[key];
var valType = $.type(val);
if ((!ruleset.getDoFilter()) || (ruleset.getDoFilter() && $.inArray(key, ruleset.getFilterKeys()) != -1)) {
switch (valType) {
case 'array':
case 'object':
var doingFilter = ruleset.getDoFilter();
//console.log(doingFilter);
if (doingFilter) {
ruleset.setDoFilter(false);
}
var beginD = consoleJSON.getDelimiter(val, ruleset, consoleJSON.BEGIN_DELIM);
var beginDTargets = keyOutputTargets.concat(keyValSepTarget, beginD[0]);
var beginDStyles = keyOutputStyles.concat(keyValSepStyle, beginD[1]);
consoleJSON.startGroup(beginDTargets, beginDStyles, lvl, DELIMITER, lineLen);
consoleJSON.traverse(val, ruleset, lvl+1);
ruleset.setDoFilter(doingFilter);
var endD = consoleJSON.getDelimiter(val, ruleset, consoleJSON.END_DELIM);
var endDTargets = [endD[0]];
var endDStyles = [endD[1]];
if (i < keys.length-1) {
endDTargets.push(sepTarget);
endDStyles.push(sepStyle);
}
consoleJSON.print(endDTargets, endDStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
consoleJSON.endGroup();
break;
default:
var output = consoleJSON.outputVal(val, ruleset, key);
var outputTargets = [output[0]];
var outputStyles = [output[1]];
if (i < keys.length-1) {
outputTargets.push(sepTarget);
outputStyles.push(sepStyle);
}
var outputKeyValTargets = keyOutputTargets.concat(keyValSepTarget, outputTargets);
var outputKeyValStyles = keyOutputStyles.concat(keyValSepStyle, outputStyles);
consoleJSON.print(outputKeyValTargets, outputKeyValStyles, lvl, DELIMITER, lineLen);
if (ruleset[consoleJSON.ATTRS.INSERT_NEWLINE]) {
console.log('\n');
}
}
} else if (valType == 'array' || valType == 'object') {
//console.log('watatata');
consoleJSON.traverse(val, ruleset, lvl);
}
}
};
// TODO: passed in ruleset should be for child object/array
consoleJSON.getDelimiter = function(json, ruleset, delimDict) {
// Function to handle the closing delimiter for arrays, objs, etc.
var type = $.type(json);
if (!(type in delimDict)) {
return null;
}
var target = delimDict[type];
var rules = ruleset.lookupRules(null);
var matchingRules = consoleJSON.Util.findMatchingStyleRules(rules, json, false)
var style = consoleJSON.Util.rulesToCSS(matchingRules);
return [target, style];
};
consoleJSON.outputPrimitive = function(json, ruleset, key, isKey) {
// Prints a primitive to the output, subject to a ruleset
var target = json;
var type = $.type(json);
switch (type) {
case consoleJSON.TARGETS.STR:
if (!isKey) {
target = '\"' + json + '\"';
}
break;
}
var rules = ruleset.lookupRules(key);
var matchingRules = consoleJSON.Util.findMatchingStyleRules(rules, json, isKey)
var style = consoleJSON.Util.rulesToCSS(matchingRules);
return [target, style];
};
consoleJSON.outputKey = function(json, ruleset, key) {
// Prints a key to the output, subject to a ruleset
return consoleJSON.outputPrimitive(json, ruleset, key, true);
};
consoleJSON.outputVal = function(json, ruleset, key) {
// Prints a value to the output, subject to a ruleset
return consoleJSON.outputPrimitive(json, ruleset, key, false);
};
// TODO: this also breaks words apart. fix this
// TODO: ignore %c
consoleJSON.indentWrap = function(target, indentationLvl, delimiter, lineLen) {
// A function to handle word wrapping in the console output
var indent = delimiter.repeat(indentationLvl);
var remainingLen = lineLen - indent.length;
var result = "";
var currPos = 0;
while (currPos+remainingLen < target.length) {
result += indent + target.substring(currPos,currPos+remainingLen) + "\n";
currPos += remainingLen;
}
result += indent + target.substring(currPos);
return result;
};
consoleJSON.print = function(targets, styles, indentationLvl, delimiter, lineLen) {
// Function to write word-wrapped data to console output
// TODO: fix indentWrap to ignore %c
//var output = consoleJSON.indentWrap(target, indentationLvl, delimiter);
console.log.apply(console, consoleJSON.Util.formatForConsole(targets, styles, indentationLvl, lineLen));
};
consoleJSON.startGroup = function(targets, styles, indentationLvl, delimiter, lineLen) {
// Begin a console grouping
// TODO: fix indentWrap to ignore %c
//var output = consoleJSON.indentWrap(target, indentationLvl, delimiter);
// default style for group start is bold; undo this
for (var i = 0; i < styles.length; i++) {
var css = styles[i];
if (css.indexOf(consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT]) == -1) {
styles[i] = css + ";" + consoleJSON.ATTR_TO_CSS[consoleJSON.ATTRS.FONT_WEIGHT] + ":" + "normal";
}
}
console.group.apply(console, consoleJSON.Util.formatForConsole(targets, styles, indentationLvl, lineLen));
};
consoleJSON.endGroup = function() {
// Finish a console grouping
console.groupEnd();
};
/**
* BEGIN RULESET & RULES PORTION OF CODE
*/
consoleJSON.Ruleset = function() {
// Constructor for Ruleset
this.nestedRulesets = {}; // map from key to Ruleset
this.globalRules = []; // list of Rules
this.filterKeysList = []; // keys to filter, used for filtering
this.doFilter = false; // a flag to tell the traverser whether or not to do filtering
// TODO: Initialize default values
this.addGlobalRule(["style","font_weight","bold","key"])
.addGlobalRule(["style","font_color","black","key"])
.addGlobalRule(["style","font_color","green","string"])
.addGlobalRule(["style","font_color","blue","number"])
.addGlobalRule(["style","font_color","red","boolean"])
.addGlobalRule(["style","font_size","14px","all"])
.addGlobalRule(["style","font_family","Impact, Charcoal, sans-serif","all"])
};
// TODO: add mechanism for dot notation in keys specified by user (generate internal nested rulesets automatically)
consoleJSON.Ruleset.prototype.addRuleset = function(key, ruleset) {
// Add a key-specific, nested ruleset to the ruleset.
// TODO: If ruleset for key already exists, merge existing ruleset with new ruleset?
this.nestedRulesets[key] = ruleset;
return this;
};
consoleJSON.Ruleset.prototype.addRule = function(key, ruleOrParams) {
// Add a key-specific rule to the ruleset (convenience function).
// If there's an existing rule for the same key with all fields matching except value, overwrites the existing value.
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.nestedRulesets[key] = this.nestedRulesets[key] || new consoleJSON.Ruleset();
this.nestedRulesets[key].addGlobalRule(rule);
return this;
};
consoleJSON.Ruleset.prototype.addGlobalRule = function(ruleOrParams) {
// Add a global rule to the ruleset.
// If there's an existing global rule with all fields matching except value, overwrites the existing value.
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.globalRules = consoleJSON.Util.addRule(this.globalRules, rule, consoleJSON.Util.rulesEqual);
return this;
};
consoleJSON.Ruleset.prototype.removeRuleset = function(key) {
// Remove a key-specific, nested ruleset from the ruleset, if it exists.
// TODO: clean up empty rulesets
delete this.nestedRulesets[key];
return this;
};
consoleJSON.Ruleset.prototype.removeRule = function(key, ruleOrParams) {
// Remove a key-specific rule from the ruleset, if it exists (convenience function).
// TODO: clean up empty rulesets
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
if (key in this.nestedRulesets) {
this.nestedRulesets[key].removeGlobalRule(rule);
}
return this;
};
consoleJSON.Ruleset.prototype.removeGlobalRule = function(ruleOrParams) {
// Remove a global rule from the ruleset, if it exists.
// TODO: clean up empty rulesets
// ruleOrParams: consoleJSON.Rule | [type, attr, val, target]
var rule = $.type(ruleOrParams) == "array" ?
new consoleJSON.Rule(ruleOrParams[0], ruleOrParams[1], ruleOrParams[2], ruleOrParams[3]) : ruleOrParams;
this.globalRules = consoleJSON.Util.removeRule(this.globalRules, rule, consoleJSON.Util.rulesEqual);
return this;
};
consoleJSON.Ruleset.prototype.addFilterKey = function(filterKey) {
if ($.type(filterKey) == 'array') {
this.filterKeysList = this.filterKeysList.concat(filterKey);
} else if ($.type(filterKey) == 'string') {
this.filterKeysList = this.filterKeysList.concat(filterKey);
}
}
consoleJSON.Ruleset.prototype.removeFilterKey = function(filterKey) {
if ($.type(filterKey) == 'array') {
for (var i = 0; i < filterKey.length; i++) {
this.filterKeysList = this.filterKeysList.splice($.inArray(filterKey[i], this.filterKeysList), 1);
}
} else if ($.type(filterKey) == 'string') {
this.filterKeysList = this.filterKeysList.splice($.inArray(filterKey, this.filterKeysList), 1);
}
}
consoleJSON.Ruleset.prototype.getFilterKeys = function() {
return this.filterKeysList;
}
consoleJSON.Ruleset.prototype.setDoFilter = function(shouldDoFilter) {
this.doFilter = shouldDoFilter;
return this.doFilter;
}
consoleJSON.Ruleset.prototype.getDoFilter = function() {
return this.doFilter;
}
consoleJSON.Ruleset.prototype.lookupRules = function(key) {
// Finds matching rules in this ruleset for the given key, adhering to precedence for rules that specify the same attribute.
// key can be either null (global rule) or string-valued (key-specific rules).
var matchingRules = [];
if (key !== null) {
// look first in key-specific rulesets
if (key in this.nestedRulesets) {
matchingRules = matchingRules.concat(this.nestedRulesets[key].globalRules);
}
}
// then add global rules
for (var i = 0; i < this.globalRules.length; i++) {
var rule = this.globalRules[i];
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, rule, consoleJSON.Util.rulesEqual);
}
//console.log(matchingRules);
return matchingRules;
};
consoleJSON.Rule = function(type, attr, val, target) {
// Constructor for Rule
// target is only valid if type == consoleJSON.TYPES.STYLE
this.type = type;
this.attr = attr;
this.val = val;
this.target = type == consoleJSON.TYPES.STYLE ? target : consoleJSON.TARGETS.UNUSED;
};
/**
* BEGIN UTIL FUNCTIONS PORTION OF CODE
*/
consoleJSON.Util.addRule = function(ruleList, rule, isMatchFn) {
// If there's an existing rule in ruleList with all fields matching the given rule except value, overwrites the existing value.
// Otherwise, appends rule to ruleList.
// Returns the modified ruleList.
var matchFound = false;
for (var i in ruleList) {
var existingRule = ruleList[i];
if (isMatchFn(existingRule, rule)) {
existingRule.val = rule.val;
matchFound = true;
}
}
if (!matchFound) {
ruleList.push(rule);
}
return ruleList;
};
consoleJSON.Util.addRuleNoOverwrite = function(ruleList, rule, isMatchFn) {
// Appends rule to ruleList only if there's no existing rule in ruleList with all fields matching the given rule except value.
// Returns the modified ruleList.
var matchFound = false;
for (var i in ruleList) {
if (isMatchFn(ruleList[i], rule)) {
matchFound = true;
break;
}
}
if (!matchFound) {
ruleList.push(rule);
}
return ruleList;
};
consoleJSON.Util.removeRule = function(ruleList, rule, isMatchFn) {
// If there's an existing rule in ruleList with all fields matching the given rule except value, removes it.
// Returns the modified ruleList.
for (var i = 0; i < ruleList.length; i++) {
var existingRule = ruleList[i];
if (isMatchFn(ruleList[i], rule)) {
ruleList.splice(i,1);
i--;
}
}
return ruleList;
};
consoleJSON.Util.findMatchingRules = function(ruleList, type, attr, target) {
// Returns all rules in ruleList whose fields match all non-null input fields.
var matchingRules = [];
for (var i = 0; i < ruleList.length; i++) {
var existingRule = ruleList[i];
if ((type === null || existingRule.type == type) &&
(attr === null || existingRule.attr == attr) &&
(target === null || existingRule.target == target)) {
matchingRules.push(existingRule);
}
}
return matchingRules;
};
consoleJSON.Util.findMatchingStyleRules = function(ruleList, json, isKey) {
// Returns all matching style rules for json in ruleList, where isKey determines if the json represents a key or a value.
// first add rules pertaining to target=key/val,
// then add rules pertaining to target=<primitive>/obj/array if no conflicts,
// then add rules pertaining to target=all if no conflicts
var type = $.type(json);
var typeInJson = isKey ? consoleJSON.TARGETS.KEY : consoleJSON.TARGETS.VAL;
var matchingRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, typeInJson);
var matchingTypeRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, type);
for (var i = 0; i < matchingTypeRules.length; i++) {
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, matchingTypeRules[i], consoleJSON.Util.rulesTypeAttrEqual);
}
var matchingAllRules = consoleJSON.Util.findMatchingRules(ruleList, consoleJSON.TYPES.STYLE, null, consoleJSON.TARGETS.ALL);
for (var i = 0; i < matchingAllRules.length; i++) {
matchingRules = consoleJSON.Util.addRuleNoOverwrite(matchingRules, matchingAllRules[i], consoleJSON.Util.rulesTypeAttrEqual);
}
//console.log(matchingRules);
return matchingRules;
};
consoleJSON.Util.rulesEqual = function(rule1, rule2) {
// Returns whether or not the two rules are the same (with only the attribute value as a possible difference).
return rule1.type == rule2.type && rule1.attr == rule2.attr && rule1.target == rule2.target;
};
consoleJSON.Util.rulesTypeAttrEqual = function(rule1, rule2) {
// Returns whether or not the two rules are the same (with only the attribute value, targets as possible differences).
return rule1.type == rule2.type && rule1.attr == rule2.attr;
};
consoleJSON.Util.formatForConsole = function(targets, styles, indentationLvl, lineLen) {
// Formats the targets and styles into the array expected by console.
// TODO: replace with indentAndWrap, handle indentationLvl, lineLen
var indent = DELIMITER.repeat(indentationLvl);
var targetStr = indent + CONSOLE_STYLE_SPECIFIER + targets.join(CONSOLE_STYLE_SPECIFIER);
var consoleFormattedArr = [targetStr];
return consoleFormattedArr.concat(styles);
};
consoleJSON.Util.rulesToCSS = function(ruleList) {
// Returns a CSS string that contains all styles specified by rules in ruleList.
var cssStrings = [];
for (var i = 0; i < ruleList.length; i++) {
var rule = ruleList[i];
if (rule.type == consoleJSON.TYPES.STYLE) {
cssStrings.push(consoleJSON.ATTR_TO_CSS[rule.attr] + ":" + rule.val);
}
}
return cssStrings.join(";");
};
// From http://stackoverflow.com/questions/202605/repeat-string-javascript
String.prototype.repeat = function(num) {
return new Array(num+1).join(this);
};
| Pretty colors
| code/consoleJSON.js | Pretty colors | <ide><path>ode/consoleJSON.js
<ide> // TODO: Initialize default values
<ide> this.addGlobalRule(["style","font_weight","bold","key"])
<ide> .addGlobalRule(["style","font_color","black","key"])
<del> .addGlobalRule(["style","font_color","green","string"])
<del> .addGlobalRule(["style","font_color","blue","number"])
<del> .addGlobalRule(["style","font_color","red","boolean"])
<del> .addGlobalRule(["style","font_size","14px","all"])
<del> .addGlobalRule(["style","font_family","Impact, Charcoal, sans-serif","all"])
<add> .addGlobalRule(["style","font_color","#606aa1","string"])
<add> .addGlobalRule(["style","font_color","#4ea1df","number"])
<add> .addGlobalRule(["style","font_color","#da564a","boolean"])
<add> .addGlobalRule(["style","font_size","12px","all"])
<add> .addGlobalRule(["style","font_family","Verdana, Geneva, sans-serif","all"])
<ide> };
<ide>
<ide> // TODO: add mechanism for dot notation in keys specified by user (generate internal nested rulesets automatically) |
|
Java | apache-2.0 | 6e5decaa9859b8a372e60fe8ad2a073d774fb2df | 0 | YourDataStories/components-visualisation,YourDataStories/components-visualisation,YourDataStories/components-visualisation | package gr.demokritos.iit.ydsapi.rest;
import gr.demokritos.iit.ydsapi.model.BasketItem;
import gr.demokritos.iit.ydsapi.model.BasketItem.BasketType;
import gr.demokritos.iit.ydsapi.responses.BaseResponse;
import gr.demokritos.iit.ydsapi.responses.BaseResponse.Status;
import gr.demokritos.iit.ydsapi.responses.BasketItemLoadResponse;
import gr.demokritos.iit.ydsapi.responses.BasketListLoadResponse;
import gr.demokritos.iit.ydsapi.responses.BasketSaveResponse;
import gr.demokritos.iit.ydsapi.storage.MongoAPIImpl;
import gr.demokritos.iit.ydsapi.storage.YDSAPI;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author George K. <[email protected]>
*/
@Path("yds/basket/")
@Produces(MediaType.APPLICATION_JSON)
public class Basket {
private static final Logger LOG = Logger.getLogger(Basket.class.getName());
@Path("save")
@POST
public Response save(
String json_basket_item
) {
BasketSaveResponse res = new BasketSaveResponse();
YDSAPI api = MongoAPIImpl.getInstance();
try {
BasketItem item = new BasketItem(json_basket_item);
String id = api.saveBasketItem(item);
if (id != null && !id.isEmpty()) {
res.setStatus(BaseResponse.Status.OK);
res.setID(id);
} else {
res.setStatus(Status.OK);
res.setMessage("Could not save basket item");
res.setID("");
}
} catch (Exception ex) {
System.out.println(ex.toString()); // error response
res.setStatus(BaseResponse.Status.ERROR);
res.setMessage(ex.getMessage() != null
? ex.getMessage()
: ex.toString());
}
return Response.status(
res.getStatus() == Status.OK
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR)
.entity(res.toJSON()).build();
}
@Path("get/{user_id}")
@GET
public Response load(
@PathParam("user_id") String user_id,
@QueryParam("basket_type") String basket_type
) {
YDSAPI api = MongoAPIImpl.getInstance();
List<BasketItem> baskets;
BasketListLoadResponse blr;
LOG.info(String.format("user_id: %s", user_id));
LOG.info(String.format("basket_type: %s", basket_type));
try {
baskets = api.getBasketItems(
user_id,
basket_type == null
? BasketType.ALL
: BasketType.valueOf(basket_type.toUpperCase())
);
LOG.info(String.format("baskets size: %d", baskets.size()));
blr = new BasketListLoadResponse(baskets);
} catch (Exception ex) {
blr = new BasketListLoadResponse(
null,
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
blr.getStatus() == Status.OK || blr.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(blr.toJSON()).build();
}
@Path("get_item/{basket_item_id}")
@GET
public Response getItem(
@PathParam("basket_item_id") String basket_item_id
) {
YDSAPI api = MongoAPIImpl.getInstance();
final BasketItem bskt;
BasketItemLoadResponse blr;
LOG.info(String.format("basket_item_id: %s", basket_item_id));
try {
bskt = api.getBasketItem(basket_item_id);
blr = new BasketItemLoadResponse(bskt);
} catch (Exception ex) {
blr = new BasketItemLoadResponse(
null,
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
blr.getStatus() == Status.OK || blr.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(blr.toJSON()).build();
}
@Path("remove/{user_id}")
@GET
public Response remove(
@PathParam("user_id") String user_id,
@QueryParam("basket_item_id") String basket_item_id
) {
YDSAPI api = MongoAPIImpl.getInstance();
BaseResponse br;
LOG.info(String.format("user_id: %s", user_id));
LOG.info(String.format("basket_item_id: %s", basket_item_id));
try {
if (basket_item_id == null) {
int res = api.removeBasketItems(user_id);
br = new BaseResponse(Status.OK, getMessage(res, user_id));
LOG.info(String.format("delete items: %d", res));
} else {
boolean res = api.removeBasketItem(user_id, basket_item_id);
br = new BaseResponse(Status.OK, getMessage(res, basket_item_id));
LOG.info(String.format("delete item: %s", Boolean.toString(res)));
}
} catch (Exception ex) {
br = new BaseResponse(
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
br.getStatus() == Status.OK || br.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(br.toJSON()).build();
}
private static String getMessage(boolean res, String basket_item_id) {
return res ? String.format("id: '%s' removed succesfully", basket_item_id) : String.format("id: '%s' not found", basket_item_id);
}
private static String getMessage(int res, String user_id) {
return res > 0
? res > 1 ? String.format("removed succesfully %d items", res) : String.format("removed succesfully %d item", res)
: String.format("no basket items found for user '%s'", user_id);
}
}
| BackendUtilities/src/main/java/gr/demokritos/iit/ydsapi/rest/Basket.java | package gr.demokritos.iit.ydsapi.rest;
import gr.demokritos.iit.ydsapi.model.BasketItem;
import gr.demokritos.iit.ydsapi.model.BasketItem.BasketType;
import gr.demokritos.iit.ydsapi.responses.BaseResponse;
import gr.demokritos.iit.ydsapi.responses.BaseResponse.Status;
import gr.demokritos.iit.ydsapi.responses.BasketItemLoadResponse;
import gr.demokritos.iit.ydsapi.responses.BasketListLoadResponse;
import gr.demokritos.iit.ydsapi.responses.BasketSaveResponse;
import gr.demokritos.iit.ydsapi.storage.MongoAPIImpl;
import gr.demokritos.iit.ydsapi.storage.YDSAPI;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author George K. <[email protected]>
*/
@Path("yds/basket/")
@Produces(MediaType.APPLICATION_JSON)
public class Basket {
private static final Logger LOG = Logger.getLogger(Basket.class.getName());
@Path("save")
@POST
public Response save(
String json_basket_item
) {
BasketSaveResponse res = new BasketSaveResponse();
YDSAPI api = MongoAPIImpl.getInstance();
try {
BasketItem item = new BasketItem(json_basket_item);
String id = api.saveBasketItem(item);
if (id != null && !id.isEmpty()) {
res.setStatus(BaseResponse.Status.OK);
res.setID(id);
} else {
res.setStatus(Status.OK);
res.setMessage("Could not save basket item");
res.setID("");
}
} catch (Exception ex) {
System.out.println(ex.toString()); // error response
res.setStatus(BaseResponse.Status.ERROR);
res.setMessage(ex.getMessage() != null
? ex.getMessage()
: ex.toString());
}
return Response.status(
res.getStatus() == Status.OK
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR)
.entity(res.toJSON()).build();
}
@Path("get/{user_id}")
@GET
public Response load(
@PathParam("user_id") String user_id,
@QueryParam("basket_type") String basket_type
) {
YDSAPI api = MongoAPIImpl.getInstance();
List<BasketItem> baskets;
BasketListLoadResponse blr;
LOG.info(String.format("user_id: %s", user_id));
LOG.info(String.format("basket_type: %s", basket_type));
try {
baskets = api.getBasketItems(
user_id,
basket_type == null
? BasketType.ALL
: BasketType.valueOf(basket_type.toUpperCase())
);
LOG.info(String.format("baskets size: %d", baskets.size()));
blr = new BasketListLoadResponse(baskets);
} catch (Exception ex) {
blr = new BasketListLoadResponse(
null,
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
blr.getStatus() == Status.OK || blr.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(blr.toJSON()).build();
}
@Path("get_item/{basket_item_id}")
@GET
public Response getItem(
@PathParam("basket_item_id") String basket_item_id
) {
YDSAPI api = MongoAPIImpl.getInstance();
final BasketItem bskt;
BasketItemLoadResponse blr;
LOG.info(String.format("basket_item_id: %s", basket_item_id));
try {
bskt = api.getBasketItem(basket_item_id);
blr = new BasketItemLoadResponse(bskt);
} catch (Exception ex) {
blr = new BasketItemLoadResponse(
null,
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
blr.getStatus() == Status.OK || blr.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(blr.toJSON()).build();
}
@Path("remove/{user_id}")
@POST
public Response remove(
@PathParam("user_id") String user_id,
@QueryParam("basket_item_id") String basket_item_id
) {
YDSAPI api = MongoAPIImpl.getInstance();
BaseResponse br;
LOG.info(String.format("user_id: %s", user_id));
LOG.info(String.format("basket_item_id: %s", basket_item_id));
try {
if (basket_item_id == null) {
int res = api.removeBasketItems(user_id);
br = new BaseResponse(Status.OK, getMessage(res, user_id));
LOG.info(String.format("delete items: %d", res));
} else {
boolean res = api.removeBasketItem(user_id, basket_item_id);
br = new BaseResponse(Status.OK, getMessage(res, basket_item_id));
LOG.info(String.format("delete item: %s", Boolean.toString(res)));
}
} catch (Exception ex) {
br = new BaseResponse(
Status.ERROR,
ex.getMessage() != null ? ex.getMessage() : ex.toString()
);
}
return Response.status(
br.getStatus() == Status.OK || br.getStatus() == Status.NOT_EXISTS
? Response.Status.OK
: Response.Status.INTERNAL_SERVER_ERROR
).entity(br.toJSON()).build();
}
private static String getMessage(boolean res, String basket_item_id) {
return res ? String.format("id: '%s' removed succesfully", basket_item_id) : String.format("id: '%s' not found", basket_item_id);
}
private static String getMessage(int res, String user_id) {
return res > 0
? res > 1 ? String.format("removed succesfully %d items", res) : String.format("removed succesfully %d item", res)
: String.format("no basket items found for user '%s'", user_id);
}
}
| - /remove/{user_id} : GET/QueryParam (testing) | BackendUtilities/src/main/java/gr/demokritos/iit/ydsapi/rest/Basket.java | - /remove/{user_id} : GET/QueryParam (testing) | <ide><path>ackendUtilities/src/main/java/gr/demokritos/iit/ydsapi/rest/Basket.java
<ide> }
<ide>
<ide> @Path("remove/{user_id}")
<del> @POST
<add> @GET
<ide> public Response remove(
<ide> @PathParam("user_id") String user_id,
<ide> @QueryParam("basket_item_id") String basket_item_id |
|
Java | bsd-2-clause | 4cec689b95facbdd57f631813c871c1ac3e9a857 | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3test.bullet;
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.animation.AnimEventListener;
import com.jme3.animation.LoopMode;
import com.jme3.bullet.BulletAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.control.KinematicRagdollControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import com.jme3.texture.Texture;
/**
* @author normenhansen
*/
public class TestRagdollCharacter extends SimpleApplication implements AnimEventListener, ActionListener {
BulletAppState bulletAppState;
Node model;
KinematicRagdollControl ragdoll;
boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false,
leftRotate = false, rightRotate = false;
AnimControl animControl;
AnimChannel animChannel;
public static void main(String[] args) {
TestRagdollCharacter app = new TestRagdollCharacter();
app.start();
}
public void simpleInitApp() {
setupKeys();
bulletAppState = new BulletAppState();
bulletAppState.setEnabled(true);
stateManager.attach(bulletAppState);
// bulletAppState.getPhysicsSpace().enableDebug(assetManager);
PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
initWall(2,1,1);
setupLight();
cam.setLocation(new Vector3f(-8,0,-4));
cam.lookAt(new Vector3f(4,0,-7), Vector3f.UNIT_Y);
model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
model.lookAt(new Vector3f(0,0,-1), Vector3f.UNIT_Y);
model.setLocalTranslation(4, 0, -7f);
ragdoll = new KinematicRagdollControl(0.5f);
model.addControl(ragdoll);
getPhysicsSpace().add(ragdoll);
speed = 1.3f;
rootNode.attachChild(model);
AnimControl control = model.getControl(AnimControl.class);
animChannel = control.createChannel();
animChannel.setAnim("IdleTop");
control.addListener(this);
}
private void setupLight() {
DirectionalLight dl = new DirectionalLight();
dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
rootNode.addLight(dl);
}
private PhysicsSpace getPhysicsSpace() {
return bulletAppState.getPhysicsSpace();
}
private void setupKeys() {
inputManager.addMapping("Rotate Left",
new KeyTrigger(KeyInput.KEY_H));
inputManager.addMapping("Rotate Right",
new KeyTrigger(KeyInput.KEY_K));
inputManager.addMapping("Walk Forward",
new KeyTrigger(KeyInput.KEY_U));
inputManager.addMapping("Walk Backward",
new KeyTrigger(KeyInput.KEY_J));
inputManager.addMapping("Slice",
new KeyTrigger(KeyInput.KEY_SPACE),
new KeyTrigger(KeyInput.KEY_RETURN));
inputManager.addListener(this, "Strafe Left", "Strafe Right");
inputManager.addListener(this, "Rotate Left", "Rotate Right");
inputManager.addListener(this, "Walk Forward", "Walk Backward");
inputManager.addListener(this, "Slice");
}
public void initWall(float bLength, float bWidth, float bHeight) {
Box brick = new Box(Vector3f.ZERO, bLength, bHeight, bWidth);
brick.scaleTextureCoordinates(new Vector2f(1f, .5f));
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
mat2.setTexture("ColorMap", tex);
float startpt = bLength / 4;
float height = -5;
for (int j = 0; j < 15; j++) {
for (int i = 0; i < 4; i++) {
Vector3f ori = new Vector3f(i * bLength * 2 + startpt, bHeight + height, -10);
Geometry reBoxg = new Geometry("brick", brick);
reBoxg.setMaterial(mat2);
reBoxg.setLocalTranslation(ori);
//for geometry with sphere mesh the physics system automatically uses a sphere collision shape
reBoxg.addControl(new RigidBodyControl(1.5f));
reBoxg.setShadowMode(ShadowMode.CastAndReceive);
reBoxg.getControl(RigidBodyControl.class).setFriction(0.6f);
this.rootNode.attachChild(reBoxg);
this.getPhysicsSpace().add(reBoxg);
}
startpt = -startpt;
height += 2 * bHeight;
}
}
public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
if (channel.getAnimationName().equals("SliceHorizontal")) {
channel.setLoopMode(LoopMode.DontLoop);
channel.setAnim("IdleTop", 5);
channel.setLoopMode(LoopMode.Loop);
}
}
public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
}
public void onAction(String binding, boolean value, float tpf) {
if (binding.equals("Rotate Left")) {
if (value) {
leftRotate = true;
} else {
leftRotate = false;
}
} else if (binding.equals("Rotate Right")) {
if (value) {
rightRotate = true;
} else {
rightRotate = false;
}
} else if (binding.equals("Walk Forward")) {
if (value) {
forward = true;
} else {
forward = false;
}
} else if (binding.equals("Walk Backward")) {
if (value) {
backward = true;
} else {
backward = false;
}
} else if (binding.equals("Slice")) {
if (value) {
animChannel.setAnim("SliceHorizontal");
animChannel.setSpeed(0.3f);
}
}
}
@Override
public void simpleUpdate(float tpf) {
if(forward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(tpf));
}else if(backward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(-tpf));
}else if(leftRotate){
model.rotate(0, tpf, 0);
}else if(rightRotate){
model.rotate(0, -tpf, 0);
}
fpsText.setText(cam.getLocation() + "/" + cam.getRotation());
}
}
| engine/src/test/jme3test/bullet/TestRagdollCharacter.java | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3test.bullet;
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.animation.AnimEventListener;
import com.jme3.animation.Bone;
import com.jme3.animation.LoopMode;
import com.jme3.bullet.BulletAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.RagdollCollisionListener;
import com.jme3.bullet.control.KinematicRagdollControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import com.jme3.texture.Texture;
/**
* @author normenhansen
*/
public class TestRagdollCharacter extends SimpleApplication implements RagdollCollisionListener, AnimEventListener, ActionListener {
BulletAppState bulletAppState;
Node model;
KinematicRagdollControl ragdoll;
boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false,
leftRotate = false, rightRotate = false;
AnimControl animControl;
AnimChannel animChannel;
public static void main(String[] args) {
TestRagdollCharacter app = new TestRagdollCharacter();
app.start();
}
public void simpleInitApp() {
setupKeys();
bulletAppState = new BulletAppState();
bulletAppState.setEnabled(true);
stateManager.attach(bulletAppState);
initWall(2,1,1);
cam.setLocation(new Vector3f(-8,0,-4));
cam.lookAt(new Vector3f(4,0,-7), Vector3f.UNIT_Y);
// bulletAppState.getPhysicsSpace().enableDebug(assetManager);
PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
setupLight();
model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
model.lookAt(new Vector3f(0,0,-1), Vector3f.UNIT_Y);
model.setLocalTranslation(4, 0, -7f);
ragdoll = new KinematicRagdollControl(0.5f);
ragdoll.addCollisionListener(this);
model.addControl(ragdoll);
getPhysicsSpace().add(ragdoll);
speed = 1.3f;
rootNode.attachChild(model);
AnimControl control = model.getControl(AnimControl.class);
animChannel = control.createChannel();
animChannel.setAnim("IdleTop");
control.addListener(this);
}
private void setupLight() {
DirectionalLight dl = new DirectionalLight();
dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
rootNode.addLight(dl);
}
private PhysicsSpace getPhysicsSpace() {
return bulletAppState.getPhysicsSpace();
}
public void collide(Bone bone, PhysicsCollisionObject object, PhysicsCollisionEvent event) {
}
private void setupKeys() {
inputManager.addMapping("Rotate Left",
new KeyTrigger(KeyInput.KEY_H));
inputManager.addMapping("Rotate Right",
new KeyTrigger(KeyInput.KEY_K));
inputManager.addMapping("Walk Forward",
new KeyTrigger(KeyInput.KEY_U));
inputManager.addMapping("Walk Backward",
new KeyTrigger(KeyInput.KEY_J));
inputManager.addMapping("Slice",
new KeyTrigger(KeyInput.KEY_SPACE),
new KeyTrigger(KeyInput.KEY_RETURN));
inputManager.addListener(this, "Strafe Left", "Strafe Right");
inputManager.addListener(this, "Rotate Left", "Rotate Right");
inputManager.addListener(this, "Walk Forward", "Walk Backward");
inputManager.addListener(this, "Slice");
}
public void initWall(float bLength, float bWidth, float bHeight) {
Box brick = new Box(Vector3f.ZERO, bLength, bHeight, bWidth);
brick.scaleTextureCoordinates(new Vector2f(1f, .5f));
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");
key.setGenerateMips(true);
Texture tex = assetManager.loadTexture(key);
mat2.setTexture("ColorMap", tex);
float startpt = bLength / 4;
float height = -5;
for (int j = 0; j < 15; j++) {
for (int i = 0; i < 4; i++) {
Vector3f ori = new Vector3f(i * bLength * 2 + startpt, bHeight + height, -10);
Geometry reBoxg = new Geometry("brick", brick);
reBoxg.setMaterial(mat2);
reBoxg.setLocalTranslation(ori);
//for geometry with sphere mesh the physics system automatically uses a sphere collision shape
reBoxg.addControl(new RigidBodyControl(1.5f));
reBoxg.setShadowMode(ShadowMode.CastAndReceive);
reBoxg.getControl(RigidBodyControl.class).setFriction(0.6f);
this.rootNode.attachChild(reBoxg);
this.getPhysicsSpace().add(reBoxg);
}
startpt = -startpt;
height += 2 * bHeight;
}
}
public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
if (channel.getAnimationName().equals("SliceHorizontal")) {
channel.setLoopMode(LoopMode.DontLoop);
channel.setAnim("IdleTop", 5);
channel.setLoopMode(LoopMode.Loop);
}
}
public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
}
public void onAction(String binding, boolean value, float tpf) {
if (binding.equals("Rotate Left")) {
if (value) {
leftRotate = true;
} else {
leftRotate = false;
}
} else if (binding.equals("Rotate Right")) {
if (value) {
rightRotate = true;
} else {
rightRotate = false;
}
} else if (binding.equals("Walk Forward")) {
if (value) {
forward = true;
} else {
forward = false;
}
} else if (binding.equals("Walk Backward")) {
if (value) {
backward = true;
} else {
backward = false;
}
} else if (binding.equals("Slice")) {
if (value) {
animChannel.setAnim("SliceHorizontal");
animChannel.setSpeed(0.3f);
}
}
}
@Override
public void simpleUpdate(float tpf) {
if(forward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(tpf));
}else if(backward){
model.move(model.getLocalRotation().multLocal(new Vector3f(0,0,1)).multLocal(-tpf));
}else if(leftRotate){
model.rotate(0, tpf, 0);
}else if(rightRotate){
model.rotate(0, -tpf, 0);
}
fpsText.setText(cam.getLocation() + "/" + cam.getRotation());
}
}
| - simplify TestRagdollCharacter
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@8142 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| engine/src/test/jme3test/bullet/TestRagdollCharacter.java | - simplify TestRagdollCharacter | <ide><path>ngine/src/test/jme3test/bullet/TestRagdollCharacter.java
<ide> import com.jme3.animation.AnimChannel;
<ide> import com.jme3.animation.AnimControl;
<ide> import com.jme3.animation.AnimEventListener;
<del>import com.jme3.animation.Bone;
<ide> import com.jme3.animation.LoopMode;
<ide> import com.jme3.bullet.BulletAppState;
<ide> import com.jme3.app.SimpleApplication;
<ide> import com.jme3.asset.TextureKey;
<ide> import com.jme3.bullet.PhysicsSpace;
<del>import com.jme3.bullet.collision.PhysicsCollisionEvent;
<del>import com.jme3.bullet.collision.PhysicsCollisionObject;
<del>import com.jme3.bullet.collision.RagdollCollisionListener;
<ide> import com.jme3.bullet.control.KinematicRagdollControl;
<ide> import com.jme3.bullet.control.RigidBodyControl;
<ide> import com.jme3.input.KeyInput;
<ide> /**
<ide> * @author normenhansen
<ide> */
<del>public class TestRagdollCharacter extends SimpleApplication implements RagdollCollisionListener, AnimEventListener, ActionListener {
<add>public class TestRagdollCharacter extends SimpleApplication implements AnimEventListener, ActionListener {
<ide>
<ide> BulletAppState bulletAppState;
<ide> Node model;
<ide> bulletAppState = new BulletAppState();
<ide> bulletAppState.setEnabled(true);
<ide> stateManager.attach(bulletAppState);
<add>
<add>
<add>// bulletAppState.getPhysicsSpace().enableDebug(assetManager);
<add> PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
<ide> initWall(2,1,1);
<add> setupLight();
<ide>
<ide> cam.setLocation(new Vector3f(-8,0,-4));
<ide> cam.lookAt(new Vector3f(4,0,-7), Vector3f.UNIT_Y);
<del>
<del>
<del>// bulletAppState.getPhysicsSpace().enableDebug(assetManager);
<del> PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
<del> setupLight();
<ide>
<ide> model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
<ide> model.lookAt(new Vector3f(0,0,-1), Vector3f.UNIT_Y);
<ide> model.setLocalTranslation(4, 0, -7f);
<ide>
<ide> ragdoll = new KinematicRagdollControl(0.5f);
<del> ragdoll.addCollisionListener(this);
<ide> model.addControl(ragdoll);
<ide>
<ide> getPhysicsSpace().add(ragdoll);
<ide>
<ide> private PhysicsSpace getPhysicsSpace() {
<ide> return bulletAppState.getPhysicsSpace();
<del> }
<del>
<del> public void collide(Bone bone, PhysicsCollisionObject object, PhysicsCollisionEvent event) {
<ide> }
<ide>
<ide> private void setupKeys() { |
|
JavaScript | mit | 69dd7a92c533b41750cf7f96d043c22d4a767294 | 0 | ryohey/Dropboard,ryohey/Dropboard | // Generated by CoffeeScript 1.4.0
var BASE_PATH, DATA_PATH, LOG_FILE, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, echo, express, fs, getFiles, io, isSet, os, port, request, server, shorten, sortByDate, startListen, url, util, _i, _len;
express = require("express");
fs = require("fs");
os = require("os");
request = require("request");
util = require('util');
/* 定数
*/
BASE_PATH = "../../../../";
DATA_PATH = BASE_PATH + "data/";
UPLOAD_PATH = BASE_PATH + "uploads/";
PUBLIC_PATH = "../public/";
LOG_FILE = "log.txt";
/* 標準出力を上書き
*/
echo = console.log;
console.log = function() {
var scr;
scr = util.format.apply(this, arguments) + '\n';
return fs.appendFileSync(LOG_FILE, scr);
};
/* app
*/
app = express();
app.use(function(req, res, next) {
var hostname, _ref;
hostname = req.headers.host;
if ((hostname != null) && (((_ref = hostname.match(/^localhost/)) != null ? _ref.length : void 0) != null)) {
return next();
} else {
return res.send(400);
}
});
/* static
*/
app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));
app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));
/* データディレクトリがない場合は作成
*/
dirs = [DATA_PATH, UPLOAD_PATH];
for (_i = 0, _len = dirs.length; _i < _len; _i++) {
dir = dirs[_i];
try {
fs.statSync(dir);
} catch (e) {
fs.mkdirSync(dir, "777");
}
}
/* 内部で使う関数
*/
getFiles = function(dataPath) {
var files, list;
files = fs.readdirSync(dataPath);
list = [];
files.forEach(function(fileName) {
var data, file;
if (fileName.match(/.+\.json/)) {
file = fs.readFileSync(dataPath + fileName) + "";
if (file) {
data = null;
try {
data = JSON.parse(file);
} catch (e) {
console.log(e);
}
if (data) {
return list.push(data);
}
}
}
});
return list;
};
isSet = function(arg) {
return (arg != null) && arg !== "";
};
shorten = function(str, length) {
var postfix, s;
s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
postfix = "...";
if (s.length > length) {
if (length > postfix.length) {
return s.slice(0, length - postfix.length) + postfix;
} else {
return s.slice(0, length);
}
} else {
return s;
}
};
sortByDate = function(a, b) {
var ax, bx;
if (!a) {
return -1;
} else if (!b) {
return 1;
}
ax = (new Date(a.date)).getTime();
bx = (new Date(b.date)).getTime();
if (ax == null) {
ax = 0;
}
if (bx == null) {
bx = 0;
}
return ax - bx;
};
/* API
*/
app.post("/upload", function(req, res) {
var files, saved;
files = req.files.files;
if (typeof files.forEach !== 'function') {
files = [files];
}
saved = [];
files.forEach(function(file) {
var data, newPath;
data = fs.readFileSync(file.path);
if (data) {
newPath = __dirname + "/" + UPLOAD_PATH + file.name;
fs.writeFileSync(newPath, data);
console.log("saved:" + file.name);
return saved.push(UPLOAD_PATH + file.name);
}
});
return res.send(JSON.stringify(saved));
});
app.post("/write", function(req, res) {
var data;
data = req.body;
if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
if (err) {
return res.send("0");
} else {
return res.send("1");
}
});
}
});
app.get("/page/:page/:per", function(req, res) {
var end, files, page, per, sliced, start;
files = getFiles(DATA_PATH);
files.sort(sortByDate);
page = parseInt(req.params.page);
per = parseInt(req.params.per);
start = Math.max(files.length - (page + 1) * per, 0);
end = Math.max(files.length - page * per, 0);
sliced = files.slice(start, end);
return res.send(JSON.stringify(sliced));
});
app.get("/read", function(req, res) {
return res.send(JSON.stringify(getFiles(DATA_PATH)));
});
app.get("/exit", function(req, res) {
console.log("httpからサーバーが終了されました");
return process.exit(0);
});
/**
* ポート番号の設定
* macとwindowsではコロン(:)がディレクトリ名に使えない文字なので
* ドライブ文字と被らない::をセパレータとして使う
* 実行しているディレクトリ::portの並びで保存する
*/
checkPort = function() {
var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
dirToPortString = function(port) {
return runtime_dir + separator + port + "\n";
};
portfile = os.tmpDir() + "/.dropboard.port";
runtime_dir = __dirname;
default_port = 50000;
port = default_port;
separator = "::";
detected = false;
exists = fs.existsSync(portfile);
if (exists) {
file = fs.readFileSync(portfile, "utf-8");
lines = file.split("\n");
lines.forEach(function(line) {
var pear;
pear = line.split(separator);
if (pear.length === 2 && pear[0] === runtime_dir) {
port = Number(pear[1]);
return detected = true;
}
});
if (!detected) {
port = default_port + lines.length;
}
}
portDirString = runtime_dir + separator + port + "\n";
if (!detected || !exists) {
fs.appendFileSync(portfile, portDirString, "utf-8");
}
return port;
};
port = checkPort();
url = "http://localhost:" + port + "/";
process.on('uncaughtException', function(err) {
if (err.errno === 'EADDRINUSE') {
return request(url + "exit", function(error, response, body) {
return startListen();
});
}
});
/* WebSocketの準備
*/
server = require('http').createServer(app);
io = require('socket.io').listen(server);
io.set('log level', 1);
io.sockets.on('connection', function(socket) {
/**
* クライアントからの接続時にDATA_PATHの
* 監視を開始する.
*/
var watcher;
watcher = fs.watch(DATA_PATH, function(event, filename) {
/**
* ディレクトリに変更があった際にupdateイベントを
* クライアントにpushする.
*/
return socket.emit('update', {});
});
/**
* クライアントから切断された際に
* ディレクトリの監視を停止する.
*/
return socket.on('disconnect', function() {
return watcher.close();
});
});
/**
* expressのインスタンスではなく
* httpServerのインスタンスでlistenすること!
* そうしないとsocket.io.jsが404になる.
*/
startListen = function() {
return server.listen(port);
};
startListen();
echo(url);
| Dropboard.app/Contents/Resources/node/server.js | <<<<<<< HEAD
// Generated by CoffeeScript 1.4.0
var BASE_PATH, DATA_PATH, LOG_FILE, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, echo, express, fs, getFiles, io, isSet, os, port, request, server, shorten, sortByDate, startListen, url, util, _i, _len;
express = require("express");
fs = require("fs");
os = require("os");
request = require("request");
util = require('util');
/* 定数
*/
BASE_PATH = "../../../../";
DATA_PATH = BASE_PATH + "data/";
UPLOAD_PATH = BASE_PATH + "uploads/";
PUBLIC_PATH = "../public/";
LOG_FILE = "log.txt";
/* 標準出力を上書き
*/
echo = console.log;
console.log = function() {
var scr;
scr = util.format.apply(this, arguments) + '\n';
return fs.appendFileSync(LOG_FILE, scr);
};
/* app
*/
app = express();
app.use(function(req, res, next) {
var hostname, _ref;
hostname = req.headers.host;
if ((hostname != null) && (((_ref = hostname.match(/^localhost/)) != null ? _ref.length : void 0) != null)) {
return next();
} else {
return res.send(400);
}
});
/* static
*/
app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));
app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));
/* データディレクトリがない場合は作成
*/
dirs = [DATA_PATH, UPLOAD_PATH];
for (_i = 0, _len = dirs.length; _i < _len; _i++) {
dir = dirs[_i];
try {
fs.statSync(dir);
} catch (e) {
fs.mkdirSync(dir, "777");
}
}
/* 内部で使う関数
*/
getFiles = function(dataPath) {
var files, list;
files = fs.readdirSync(dataPath);
list = [];
files.forEach(function(fileName) {
var data, file;
if (fileName.match(/.+\.json/)) {
file = fs.readFileSync(dataPath + fileName) + "";
if (file) {
data = null;
try {
data = JSON.parse(file);
} catch (e) {
console.log(e);
}
if (data) {
return list.push(data);
}
}
}
});
return list;
};
isSet = function(arg) {
return (arg != null) && arg !== "";
};
shorten = function(str, length) {
var postfix, s;
s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
postfix = "...";
if (s.length > length) {
if (length > postfix.length) {
return s.slice(0, length - postfix.length) + postfix;
} else {
return s.slice(0, length);
}
} else {
return s;
}
};
sortByDate = function(a, b) {
var ax, bx;
if (!a) {
return -1;
} else if (!b) {
return 1;
}
ax = (new Date(a.date)).getTime();
bx = (new Date(b.date)).getTime();
if (ax == null) {
ax = 0;
}
if (bx == null) {
bx = 0;
}
return ax - bx;
};
/* API
*/
app.post("/upload", function(req, res) {
var files, saved;
files = req.files.files;
if (typeof files.forEach !== 'function') {
files = [files];
}
saved = [];
files.forEach(function(file) {
var data, newPath;
data = fs.readFileSync(file.path);
if (data) {
newPath = __dirname + "/" + UPLOAD_PATH + file.name;
fs.writeFileSync(newPath, data);
console.log("saved:" + file.name);
return saved.push(UPLOAD_PATH + file.name);
}
});
return res.send(JSON.stringify(saved));
});
app.post("/write", function(req, res) {
var data;
data = req.body;
if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
if (err) {
return res.send("0");
} else {
return res.send("1");
}
});
}
});
app.get("/page/:page/:per", function(req, res) {
var end, files, page, per, sliced, start;
files = getFiles(DATA_PATH);
files.sort(sortByDate);
page = parseInt(req.params.page);
per = parseInt(req.params.per);
start = Math.max(files.length - (page + 1) * per, 0);
end = Math.max(files.length - page * per, 0);
sliced = files.slice(start, end);
return res.send(JSON.stringify(sliced));
});
app.get("/read", function(req, res) {
return res.send(JSON.stringify(getFiles(DATA_PATH)));
});
app.get("/exit", function(req, res) {
console.log("httpからサーバーが終了されました");
return process.exit(0);
});
/**
* ポート番号の設定
* macとwindowsではコロン(:)がディレクトリ名に使えない文字なので
* ドライブ文字と被らない::をセパレータとして使う
* 実行しているディレクトリ::portの並びで保存する
*/
checkPort = function() {
var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
dirToPortString = function(port) {
return runtime_dir + separator + port + "\n";
};
portfile = os.tmpDir() + "/.dropboard.port";
runtime_dir = __dirname;
default_port = 50000;
port = default_port;
separator = "::";
detected = false;
exists = fs.existsSync(portfile);
if (exists) {
file = fs.readFileSync(portfile, "utf-8");
lines = file.split("\n");
lines.forEach(function(line) {
var pear;
pear = line.split(separator);
if (pear.length === 2 && pear[0] === runtime_dir) {
port = Number(pear[1]);
return detected = true;
}
});
if (!detected) {
port = default_port + lines.length;
}
}
portDirString = runtime_dir + separator + port + "\n";
if (!detected || !exists) {
fs.appendFileSync(portfile, portDirString, "utf-8");
}
return port;
};
port = checkPort();
url = "http://localhost:" + port + "/";
process.on('uncaughtException', function(err) {
if (err.errno === 'EADDRINUSE') {
return request(url + "exit", function(error, response, body) {
return startListen();
});
}
});
/* WebSocketの準備
*/
server = require('http').createServer(app);
io = require('socket.io').listen(server);
io.set('log level', 1);
io.sockets.on('connection', function(socket) {
/**
* クライアントからの接続時にDATA_PATHの
* 監視を開始する.
*/
var watcher;
watcher = fs.watch(DATA_PATH, function(event, filename) {
/**
* ディレクトリに変更があった際にupdateイベントを
* クライアントにpushする.
*/
return socket.emit('update', {});
});
/**
* クライアントから切断された際に
* ディレクトリの監視を停止する.
*/
return socket.on('disconnect', function() {
return watcher.close();
});
});
/**
* expressのインスタンスではなく
* httpServerのインスタンスでlistenすること!
* そうしないとsocket.io.jsが404になる.
*/
startListen = function() {
return server.listen(port);
};
startListen();
echo(url);
=======
// Generated by CoffeeScript 1.3.3
var DATA_PATH, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, exec, express, fs, getFiles, isSet, os, port, request, shorten, sortByDate, url, _i, _len;
express = require("express");
fs = require("fs");
os = require("os");
request = require("request");
/* teisuu
*/
DATA_PATH = "../../../../data/";
UPLOAD_PATH = "../../../../uploads/";
PUBLIC_PATH = "../public/";
/* app
*/
app = express();
app.use(require("connect").bodyParser());
app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));
app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));
/* データディレクトリがない場合は作成
*/
dirs = [DATA_PATH, UPLOAD_PATH];
for (_i = 0, _len = dirs.length; _i < _len; _i++) {
dir = dirs[_i];
try {
fs.statSync(dir);
} catch (e) {
fs.mkdirSync(dir, "777");
}
}
/* 内部で使う関数
*/
getFiles = function(dataPath) {
var files, list;
files = fs.readdirSync(dataPath);
list = [];
files.forEach(function(fileName) {
var data, file;
if (fileName.match(/.+\.json/)) {
file = fs.readFileSync(dataPath + fileName) + "";
if (file) {
data = null;
try {
data = JSON.parse(file);
} catch (e) {
console.log(e);
}
if (data) {
return list.push(data);
}
}
}
});
return list;
};
isSet = function(arg) {
return (arg != null) && arg !== "";
};
shorten = function(str, length) {
var postfix, s;
s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
postfix = "...";
if (s.length > length) {
if (length > postfix.length) {
return s.slice(0, length - postfix.length) + postfix;
} else {
return s.slice(0, length);
}
} else {
return s;
}
};
sortByDate = function(a, b) {
var ax, bx;
if (!a) {
return -1;
} else if (!b) {
return 1;
}
ax = (new Date(a.date)).getTime();
bx = (new Date(b.date)).getTime();
if (ax == null) {
ax = 0;
}
if (bx == null) {
bx = 0;
}
return ax - bx;
};
/* API
*/
app.post("/upload", function(req, res) {
var files, saved;
files = req.files.files;
if (typeof files.forEach !== 'function') {
files = [files];
}
saved = [];
files.forEach(function(file) {
var data, newPath;
data = fs.readFileSync(file.path);
if (data) {
newPath = __dirname + "/" + UPLOAD_PATH + file.name;
fs.writeFileSync(newPath, data);
console.log("saved:" + file.name);
return saved.push(UPLOAD_PATH + file.name);
}
});
return res.send(JSON.stringify(saved));
});
app.post("/write", function(req, res) {
var data;
data = req.body;
if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
if (err) {
return res.send("0");
} else {
return res.send("1");
}
});
}
});
app.get("/page/:page/:per", function(req, res) {
var end, files, page, per, sliced, start;
files = getFiles(DATA_PATH);
files.sort(sortByDate);
page = parseInt(req.params.page);
per = parseInt(req.params.per);
start = Math.max(files.length - (page + 1) * per, 0);
end = Math.max(files.length - page * per, 0);
sliced = files.slice(start, end);
return res.send(JSON.stringify(sliced));
});
app.get("/read", function(req, res) {
return res.send(JSON.stringify(getFiles(DATA_PATH)));
});
app.get("/exit", function(req, res) {
console.log("httpからサーバーが終了されました");
return process.exit(0);
});
/* ポート番号の設定
*/
checkPort = function() {
var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
dirToPortString = function(port) {
return runtime_dir + separator + port + "\n";
};
portfile = os.tmpDir() + "/.dropboard.port";
runtime_dir = __dirname;
default_port = 50000;
port = default_port;
separator = "::";
detected = false;
exists = fs.existsSync(portfile);
if (exists) {
file = fs.readFileSync(portfile, "utf-8");
lines = file.split("\n");
lines.forEach(function(line) {
var pear;
pear = line.split(separator);
if (pear.length === 2 && pear[0] === runtime_dir) {
port = Number(pear[1]);
return detected = true;
}
});
if (!detected) {
port = default_port + lines.length;
}
}
portDirString = runtime_dir + separator + port + "\n";
if (!detected || !exists) {
fs.appendFileSync(portfile, portDirString, "utf-8");
}
return port;
};
port = checkPort();
url = "http://localhost:" + port + "/";
process.on('uncaughtException', function(err) {
if (err.errno === 'EADDRINUSE') {
return request(url + "exit", function(error, response, body) {
return app.listen(port);
});
}
});
app.listen(port);
exec = require("child_process");
switch (os.type()) {
case "Darwin":
exec.exec("open " + url);
break;
case "Windows_NT":
exec.exec("start " + url);
}
console.log(url);
>>>>>>> mac_dock
| server.jsをcoffeeからコンパイルしたものに置き換え
| Dropboard.app/Contents/Resources/node/server.js | server.jsをcoffeeからコンパイルしたものに置き換え | <ide><path>ropboard.app/Contents/Resources/node/server.js
<del><<<<<<< HEAD
<ide> // Generated by CoffeeScript 1.4.0
<ide> var BASE_PATH, DATA_PATH, LOG_FILE, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, echo, express, fs, getFiles, io, isSet, os, port, request, server, shorten, sortByDate, startListen, url, util, _i, _len;
<ide>
<ide> startListen();
<ide>
<ide> echo(url);
<del>=======
<del>// Generated by CoffeeScript 1.3.3
<del>var DATA_PATH, PUBLIC_PATH, UPLOAD_PATH, app, checkPort, dir, dirs, exec, express, fs, getFiles, isSet, os, port, request, shorten, sortByDate, url, _i, _len;
<del>
<del>express = require("express");
<del>
<del>fs = require("fs");
<del>
<del>os = require("os");
<del>
<del>request = require("request");
<del>
<del>/* teisuu
<del>*/
<del>
<del>
<del>DATA_PATH = "../../../../data/";
<del>
<del>UPLOAD_PATH = "../../../../uploads/";
<del>
<del>PUBLIC_PATH = "../public/";
<del>
<del>/* app
<del>*/
<del>
<del>
<del>app = express();
<del>
<del>app.use(require("connect").bodyParser());
<del>
<del>app.use("/", express["static"](__dirname + "/" + PUBLIC_PATH));
<del>
<del>app.use("/uploads", express["static"](__dirname + "/" + UPLOAD_PATH));
<del>
<del>/* データディレクトリがない場合は作成
<del>*/
<del>
<del>
<del>dirs = [DATA_PATH, UPLOAD_PATH];
<del>
<del>for (_i = 0, _len = dirs.length; _i < _len; _i++) {
<del> dir = dirs[_i];
<del> try {
<del> fs.statSync(dir);
<del> } catch (e) {
<del> fs.mkdirSync(dir, "777");
<del> }
<del>}
<del>
<del>/* 内部で使う関数
<del>*/
<del>
<del>
<del>getFiles = function(dataPath) {
<del> var files, list;
<del> files = fs.readdirSync(dataPath);
<del> list = [];
<del> files.forEach(function(fileName) {
<del> var data, file;
<del> if (fileName.match(/.+\.json/)) {
<del> file = fs.readFileSync(dataPath + fileName) + "";
<del> if (file) {
<del> data = null;
<del> try {
<del> data = JSON.parse(file);
<del> } catch (e) {
<del> console.log(e);
<del> }
<del> if (data) {
<del> return list.push(data);
<del> }
<del> }
<del> }
<del> });
<del> return list;
<del>};
<del>
<del>isSet = function(arg) {
<del> return (arg != null) && arg !== "";
<del>};
<del>
<del>shorten = function(str, length) {
<del> var postfix, s;
<del> s = str.replace(/\n|\\|\/|\:|\*|\?|\"|\<|\>|\|/g, "");
<del> postfix = "...";
<del> if (s.length > length) {
<del> if (length > postfix.length) {
<del> return s.slice(0, length - postfix.length) + postfix;
<del> } else {
<del> return s.slice(0, length);
<del> }
<del> } else {
<del> return s;
<del> }
<del>};
<del>
<del>sortByDate = function(a, b) {
<del> var ax, bx;
<del> if (!a) {
<del> return -1;
<del> } else if (!b) {
<del> return 1;
<del> }
<del> ax = (new Date(a.date)).getTime();
<del> bx = (new Date(b.date)).getTime();
<del> if (ax == null) {
<del> ax = 0;
<del> }
<del> if (bx == null) {
<del> bx = 0;
<del> }
<del> return ax - bx;
<del>};
<del>
<del>/* API
<del>*/
<del>
<del>
<del>app.post("/upload", function(req, res) {
<del> var files, saved;
<del> files = req.files.files;
<del> if (typeof files.forEach !== 'function') {
<del> files = [files];
<del> }
<del> saved = [];
<del> files.forEach(function(file) {
<del> var data, newPath;
<del> data = fs.readFileSync(file.path);
<del> if (data) {
<del> newPath = __dirname + "/" + UPLOAD_PATH + file.name;
<del> fs.writeFileSync(newPath, data);
<del> console.log("saved:" + file.name);
<del> return saved.push(UPLOAD_PATH + file.name);
<del> }
<del> });
<del> return res.send(JSON.stringify(saved));
<del>});
<del>
<del>app.post("/write", function(req, res) {
<del> var data;
<del> data = req.body;
<del> if (isSet(data.name) && isSet(data.date) && isSet(data.text)) {
<del> return fs.writeFile(DATA_PATH + shorten(data.name, 10) + "「" + shorten(data.text, 20) + "」" + ".json", JSON.stringify(data), function(err) {
<del> if (err) {
<del> return res.send("0");
<del> } else {
<del> return res.send("1");
<del> }
<del> });
<del> }
<del>});
<del>
<del>app.get("/page/:page/:per", function(req, res) {
<del> var end, files, page, per, sliced, start;
<del> files = getFiles(DATA_PATH);
<del> files.sort(sortByDate);
<del> page = parseInt(req.params.page);
<del> per = parseInt(req.params.per);
<del> start = Math.max(files.length - (page + 1) * per, 0);
<del> end = Math.max(files.length - page * per, 0);
<del> sliced = files.slice(start, end);
<del> return res.send(JSON.stringify(sliced));
<del>});
<del>
<del>app.get("/read", function(req, res) {
<del> return res.send(JSON.stringify(getFiles(DATA_PATH)));
<del>});
<del>
<del>app.get("/exit", function(req, res) {
<del> console.log("httpからサーバーが終了されました");
<del> return process.exit(0);
<del>});
<del>
<del>/* ポート番号の設定
<del>*/
<del>
<del>
<del>checkPort = function() {
<del> var default_port, detected, dirToPortString, exists, file, lines, port, portDirString, portfile, runtime_dir, separator;
<del> dirToPortString = function(port) {
<del> return runtime_dir + separator + port + "\n";
<del> };
<del> portfile = os.tmpDir() + "/.dropboard.port";
<del> runtime_dir = __dirname;
<del> default_port = 50000;
<del> port = default_port;
<del> separator = "::";
<del> detected = false;
<del> exists = fs.existsSync(portfile);
<del> if (exists) {
<del> file = fs.readFileSync(portfile, "utf-8");
<del> lines = file.split("\n");
<del> lines.forEach(function(line) {
<del> var pear;
<del> pear = line.split(separator);
<del> if (pear.length === 2 && pear[0] === runtime_dir) {
<del> port = Number(pear[1]);
<del> return detected = true;
<del> }
<del> });
<del> if (!detected) {
<del> port = default_port + lines.length;
<del> }
<del> }
<del> portDirString = runtime_dir + separator + port + "\n";
<del> if (!detected || !exists) {
<del> fs.appendFileSync(portfile, portDirString, "utf-8");
<del> }
<del> return port;
<del>};
<del>
<del>port = checkPort();
<del>
<del>url = "http://localhost:" + port + "/";
<del>
<del>process.on('uncaughtException', function(err) {
<del> if (err.errno === 'EADDRINUSE') {
<del> return request(url + "exit", function(error, response, body) {
<del> return app.listen(port);
<del> });
<del> }
<del>});
<del>
<del>app.listen(port);
<del>
<del>exec = require("child_process");
<del>
<del>switch (os.type()) {
<del> case "Darwin":
<del> exec.exec("open " + url);
<del> break;
<del> case "Windows_NT":
<del> exec.exec("start " + url);
<del>}
<del>
<del>console.log(url);
<del>>>>>>>> mac_dock |
|
Java | mit | e403392720a82f558ef9f6481773743a9385052e | 0 | vackosar/search-based-launcher | package com.ideasfrombrain.search_based_launcher_v3;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ViewAnimator;
import android.widget.EditText;
import android.widget.RadioGroup;
import org.json.JSONException;
@SuppressWarnings("Convert2Lambda")
public class MainActivity extends Activity {
public static final int FIRST_INDEX = 0;
static String APP_PACKAGE_NAME = "com.ideasfrombrain.search_based_launcher_v3";
public static final App MENU_APP = new App(APP_PACKAGE_NAME + ".Menu", " Menu-Launcher", APP_PACKAGE_NAME + ".Menu");
boolean newerAndroidVersion = true;
List<App> pkg = new ArrayList<App>();
List<App> pkgFiltered = new ArrayList<App>();
List<App> extra = new ArrayList<App>();
List<App> hidden = new ArrayList<App>();
List<App> recent = new ArrayList<App>();
EditText DialogInput;
private final BroadcastReceiver mPkgApplicationsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
loadApps();
recent.retainAll(pkg);
extra.retainAll(pkg);
hidden.retainAll(pkg);
pkgFiltered.retainAll(pkg);
saveExtRemLists(false);
loadApps();
refresh();
}
};
private SearchText searchText;
private AppListView appListView;
private AutostartButton autostartButton;
private WifiButton wifiButton;
private BluetoothButton bluetoothButton;
private FlashButton flashButton;
private CameraButton cameraButton;
private RadioButtons radioButtons;
private void registerIntentReceivers() {
IntentFilter pkgFilter = new IntentFilter();
pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
pkgFilter.addDataScheme("package");
registerReceiver(mPkgApplicationsReceiver, pkgFilter);
}
public void loadApps() {
Log.d("DEBUG", "start loading apps");
Log.d("DEBUG", "activity arrays prepared");
final Intent main = new Intent(Intent.ACTION_MAIN, null);
final PackageManager pm = getPackageManager();
pkg.clear();
switch (radioButtons.getCheckedRadioButton()) {
case 0:
loadNormal(main, pm);
break;
case 1:
loadAll(main, pm);
break;
case 2:
loadExtra();
break;
case 3:
loadHidden();
break;
}
pkg.add(MENU_APP);
}
private void loadHidden() {
pkg.addAll(hidden);
}
private void loadExtra() {
pkg.addAll(extra);
}
private void loadAll(Intent main, PackageManager pm) {
final List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
for (ResolveInfo launchable : launchables) {
App app = new App(launchable.activityInfo.packageName, deriveNick(launchable), launchable.activityInfo.name);
pkg.add(app);
}
}
private String deriveNick(ResolveInfo launchable) {
String[] split = launchable.activityInfo.name.split("\\.");
String nick = split[1];
for (int j = 2; j < split.length; j++) {
nick = nick + ":" + split[j];
}
return nick;
}
private void loadNormal(Intent main, PackageManager pm) {
pkg.addAll(extra);
main.addCategory(Intent.CATEGORY_LAUNCHER); // will show only Regular Apps
final List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
for (ResolveInfo launchable : launchables) {
String nick = launchable.activityInfo.name;
if (ItemNumInHide(nick) == -1) {
String name = launchable.activityInfo.packageName;
String activity = launchable.activityInfo.loadLabel(pm).toString();
pkg.add(new App(name, nick, activity));
}
}
}
public void loadExtRemLists(boolean check) {
try {
final Context context = getApplicationContext();
extra = loadList("extra", context);
hidden = loadList("hidden", context);
recent = loadList("recent", context);
} catch (Exception e) {
//Log.d("DEBUG","excep. during load" + e.getStackTrace().toString());
saveExtRemLists(false);
}
}
public void saveExtRemLists(boolean check) {
final Context myContext = getApplicationContext();
saveList(extra, "extra", myContext);
saveList(hidden, "hidden", myContext);
saveList(recent, "recent", myContext);
}
public boolean saveList(List<App> list, String listName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences(listName, 0);
SharedPreferences.Editor editor = prefs.edit();
Set<String> set = new HashSet();
for (App app: list) {
set.add(app.getJsonString());
}
editor.putStringSet(listName, set);
return editor.commit();
}
public List<App> loadList(String listName, Context mContext) throws JSONException {
List<App> list = new ArrayList<>();
SharedPreferences prefs = mContext.getSharedPreferences(listName, 0);
for (String json: prefs.getStringSet(listName, null)) {
list.add(new App(json));
}
return list;
}
@Override
public boolean onKeyUp(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_MENU) {
myShowNext(false);
} else if (keycode == KeyEvent.KEYCODE_SEARCH) {
startSearch("", false, null, true);
} else if (keycode == KeyEvent.KEYCODE_BACK) {
ViewAnimator mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
if (mViewAnimator.getDisplayedChild() == 1) {
myShowNext(false);
}
} else {
return super.onKeyUp(keycode, event);
}
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appListView = new AppListView(this);
searchText = new SearchText(this);
autostartButton = new AutostartButton(this);
wifiButton = new WifiButton(this);
bluetoothButton = new BluetoothButton(this);
flashButton = new FlashButton(this);
cameraButton = new CameraButton(this);
createMenuDonateButton();
radioButtons = new RadioButtons(this);
setAndroidVersion();
setAppLists(savedInstanceState);
registerIntentReceivers();
}
private void createMenuDonateButton() {
findViewById(R.id.donateButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PACKAGE_NAME));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(marketIntent);
}
});
}
private void setAppLists(Bundle savedInstanceState) {
if (savedInstanceState == null) {
loadExtRemLists(false);
loadApps();
} else {
pkg.Name = savedInstanceState.getStringArrayList("pkg.Name");
pkg.Nick = savedInstanceState.getStringArrayList("pkg.Nick");
pkg.Activity = savedInstanceState.getStringArrayList("pkg.Activity");
extra.Name = savedInstanceState.getStringArrayList("extra.Name");
extra.Nick = savedInstanceState.getStringArrayList("extra.Nick");
extra.Activity = savedInstanceState.getStringArrayList("extra.Activity");
hidden.Name = savedInstanceState.getStringArrayList("hidden.Name");
hidden.Nick = savedInstanceState.getStringArrayList("hidden.Nick");
hidden.Activity = savedInstanceState.getStringArrayList("hidden.Activity");
recent.Name = savedInstanceState.getStringArrayList("recent.Name");
recent.Nick = savedInstanceState.getStringArrayList("recent.Nick");
recent.Activity = savedInstanceState.getStringArrayList("recent.Activity");
}
}
private void setAndroidVersion() {
String Aversion = android.os.Build.VERSION.RELEASE;
if (Aversion.startsWith("1.") ||
Aversion.startsWith("2.0") ||
Aversion.startsWith("2.1")) {
newerAndroidVersion = false;
} else {
newerAndroidVersion = true;
}
}
public void myShowNext(Boolean DoLoadApps) {
searchText.setNormalColor();
ViewAnimator mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
//mViewAnimator.setInAnimation(null); // Skipping this will cause trouble
// mViewAnimator.setOutAnimation(null);
mViewAnimator.showNext();
if (mViewAnimator.getDisplayedChild() == 0) {
//final TextView myToggleButton = (TextView) findViewById(R.id.toggleButton0);
if (DoLoadApps) {
loadApps();
}
if (radioButtons.getCheckedRadioButton() > 0) {
searchText.setSpaceCharacterToText();
radioButtons.setInvisible();
} else {
wifiButton.setVisibleIfAvailable();
bluetoothButton.setVisibleIfAvailable();
cameraButton.setVisibleIfAvailable();
searchText.clearText();
}
} else {
RadioGroup mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
mRadioGroup.requestFocus();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
radioButtons.save();
savedInstanceState.putBoolean("newerAndroidVersion", newerAndroidVersion);
savedInstanceState.putStringArrayList("pkg.Name", pkg.Name);
savedInstanceState.putStringArrayList("pkg.Nick", pkg.Nick);
savedInstanceState.putStringArrayList("pkg.Activity", pkg.Activity);
savedInstanceState.putStringArrayList("extra.Name", extra.Name);
savedInstanceState.putStringArrayList("extra.Nick", extra.Nick);
savedInstanceState.putStringArrayList("extra.Activity", extra.Activity);
savedInstanceState.putStringArrayList("hidden.Name", hidden.Name);
savedInstanceState.putStringArrayList("hidden.Nick", hidden.Nick);
savedInstanceState.putStringArrayList("hidden.Activity", hidden.Activity);
savedInstanceState.putStringArrayList("recent.Name", recent.Name);
savedInstanceState.putStringArrayList("recent.Nick", recent.Nick);
savedInstanceState.putStringArrayList("recent.Activity", recent.Activity);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
}
@Override
protected void onResume() {
super.onResume();
searchText.setNormalColor();
if ((radioButtons.getCheckedRadioButton() == 0) && autostartButton.isAutostart()) {
searchText.clearText();
}
if (!newerAndroidVersion) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
@Override
public void onDestroy() {
wifiButton.unregisterReceiver();
unregisterReceiver(mPkgApplicationsReceiver);
super.onDestroy();
}
public void runApp(int index) {
searchText.setActivatedColor();
int tmpint = ItemNumInRecent(pkgFiltered.Activity.get(index));
if ((recent.Nick.size() >= 10) && (tmpint == -1)) {
recent.Name.remove(0);
recent.Nick.remove(0);
recent.Activity.remove(0);
} else if (tmpint != -1) {
recent.Name.remove(tmpint);
recent.Nick.remove(tmpint);
recent.Activity.remove(tmpint);
}
final Context myContext = getApplicationContext();
saveList(recent.Name, "recent.Name", myContext);
saveList(recent.Nick, "recent.Nick", myContext);
saveList(recent.Activity, "recent.Activity", myContext);
String tmpNickBefore = pkgFiltered.Nick.get(index);
recent.Name.add(pkgFiltered.Name.get(index));
if ((tmpNickBefore.matches("R:.*"))) {
tmpNickBefore = tmpNickBefore.substring(2, tmpNickBefore.length());
}
recent.Nick.add(tmpNickBefore);
recent.Activity.add(pkgFiltered.Activity.get(index));
if (!newerAndroidVersion) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
if ((APP_PACKAGE_NAME + ".Menu").equals(pkgFiltered.Name.get(index))) {
myShowNext(false);
} else {
try {
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(pkgFiltered.Name.get(index), pkgFiltered.Activity.get(index)));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(intent);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("DEBUG", e.getMessage());
searchText.setNormalColor();
if (!newerAndroidVersion) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
}
}
public void refresh() {
pkgFiltered.Name.clear();
pkgFiltered.Nick.clear();
pkgFiltered.Activity.clear();
String FilterText = searchText.getFilterText();
int tmpsize = recent.Name.size();
for (int i = 0; i < tmpsize; i++) {
//Log.d("DEBUG", recent.Name.get(tmpsize-1-i));
if (recent.Nick.get(tmpsize - 1 - i).toLowerCase().matches(FilterText)) {
pkgFiltered.Name.add(recent.Name.get(tmpsize - 1 - i));
pkgFiltered.Activity.add(recent.Activity.get(tmpsize - 1 - i));
pkgFiltered.Nick.add("R:" + recent.Nick.get(tmpsize - 1 - i));
}
}
for (int i = 0; i < pkg.Name.size(); i++) {
if ((pkg.Nick.get(i).toLowerCase().matches(FilterText)) && (ItemNumInRecent(pkg.Activity.get(i)) == -1)) {
pkgFiltered.Name.add(pkg.Name.get(i));
pkgFiltered.Activity.add(pkg.Activity.get(i));
pkgFiltered.Nick.add(pkg.Nick.get(i));
//Log.d("DEBUG", pkg.Nick[i]);
}
}
if (((pkgFiltered.Name.size()) == 1) && autostartButton.isAutostart()) {
runApp(FIRST_INDEX);
} else {
appListView.setAppList(pkgFiltered.Nick);
}
//}
}
//@Override
public boolean showOptionsForApp(final int index) {
final String activity = pkgFiltered.Activity.get(index);
final String name = pkgFiltered.Name.get(index);
final String nickBefore = pkgFiltered.Nick.get(index);
if ((activity == APP_PACKAGE_NAME + ".Menu")) {
return false;
}
String nick;
if ((nickBefore.matches("R:.*"))) {
nick = nickBefore.substring(2, nickBefore.length());
} else {
nick = nickBefore;
}
switch (radioButtons.getCheckedRadioButton()) {
case 0:
showNormalOptions(activity, name, nick);
break;
case 1:
showAddExtraAppOptions(index, nick);
break;
case 2:
showRemoveExtraAppOptions(index, activity, nick);
break;
case 3:
showUnhideAppOptions(index, activity, nick);
break;
}
return false;
}
private void showUnhideAppOptions(int index, final String tmpActivity, String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Remove this activity (hidden app) from hidden applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInHide = MainActivity.this.ItemNumInHide(tmpActivity);
if (tmpItemNumInHide != -1) {
hidden.Activity.remove(tmpItemNumInHide);
hidden.Name.remove(tmpItemNumInHide);
hidden.Nick.remove(tmpItemNumInHide);
MainActivity.this.saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.create().show();
}
private void showRemoveExtraAppOptions(int index, final String tmpActivity, final String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Remove this (extra added list of all activities) activity from applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if (tmpItemNumInExtra != -1) {
extra.Activity.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Nick.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
MainActivity.this.saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.create().show();
}
private void showAddExtraAppOptions(final int index, String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Add this activity to applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
extra.Name.add(pkgFiltered.Name.get(index));
extra.Nick.add(DialogInput.getText().toString());
extra.Activity.add(pkgFiltered.Activity.get(index));
saveExtRemLists(true);
loadApps();
refresh();
dialog.dismiss();
}
});
dialog.create().show();
}
private void showNormalOptions(final String tmpActivity, final String tmpName, final String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if ((tmpItemNumInExtra == -1) && (MainActivity.this.ItemNumInHide(tmpActivity) == -1)) {
showHideApp(tmpActivity, tmpName, nick, dialog);
} else if ((tmpItemNumInExtra != -1) && (MainActivity.this.ItemNumInHide(tmpActivity) != -1)) {
showRenamedApp(tmpActivity, tmpName, nick, dialog);
} else if (tmpItemNumInExtra != -1) {
showExtraAddedApp(tmpActivity, dialog);
}
dialog.create().show();
}
private void showExtraAddedApp(final String tmpActivity, AlertDialog.Builder dialog) {
dialog.setMessage("Remove activity " + tmpActivity + " from extra added (to applications list) list ?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
extra.Activity.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Nick.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
});
}
private void showRenamedApp(final String tmpActivity, final String tmpName, String nick, AlertDialog.Builder dialog) {
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(nick);
dialog.setView(DialogInput);
dialog.setMessage("This application is in both add and hide lists, thus is probably renamed.");
dialog.setCancelable(true);
dialog.setPositiveButton("Hide", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
//hidden.Name.add(tmpName);
//hidden.Nick.add(tmpNick);
//hidden.Activity.add(tmpActivity);
extra.Nick.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Activity.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.setNeutralButton("Uninstall", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + tmpName));
startActivity(intent);
//loadApps();
refresh();
dialog.dismiss();
}
});
dialog.setNegativeButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
//hidden.Name.add(tmpName);
//hidden.Nick.add(tmpNick);
//hidden.Activity.add(tmpActivity);
extra.Nick.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Activity.remove(tmpItemNumInExtra);
extra.Nick.add(DialogInput.getText().toString());
extra.Name.add(tmpName);
extra.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.set(tmpItemNumInRecent, DialogInput.getText().toString());
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
});
}
private void showHideApp(final String tmpActivity, final String tmpName, final String nick, AlertDialog.Builder dialog) {
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(nick);
dialog.setView(DialogInput);
dialog.setMessage("Hide this application from applications list, rename application (add to Hide and Extra list with diferent names) or uninstall it?");
dialog.setCancelable(true);
dialog.setPositiveButton("Hide", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//int tmpItemNumInExtra=MainActivity.this.ItemNumInExtra(tmpActivity);
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
hidden.Name.add(tmpName);
hidden.Nick.add(nick);
hidden.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.setNeutralButton("Uninstall", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + tmpName));
startActivity(intent);
//loadApps();
refresh();
dialog.dismiss();
}
});
dialog.setNegativeButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
hidden.Name.add(tmpName);
hidden.Nick.add(nick);
hidden.Activity.add(tmpActivity);
extra.Nick.add(DialogInput.getText().toString());
extra.Name.add(tmpName);
extra.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.set(tmpItemNumInRecent, DialogInput.getText().toString());
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
}
public int ItemNumInExtra(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < extra.Activity.size(); i++) {
if (Activity.equals(extra.Activity.get(i))) {
return i;
}
}
return -1;
}
public int ItemNumInHide(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < hidden.Activity.size(); i++) {
if (Activity.equals(hidden.Activity.get(i))) {
return i;
}
}
return -1;
}
public int ItemNumInRecent(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < recent.Activity.size(); i++) {
if (Activity.equals(recent.Activity.get(i))) {
return i;
}
}
return -1;
}
} | src/com/ideasfrombrain/search_based_launcher_v3/MainActivity.java | package com.ideasfrombrain.search_based_launcher_v3;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ViewAnimator;
import android.widget.EditText;
import android.widget.RadioGroup;
import org.json.JSONException;
import org.json.JSONObject;
@SuppressWarnings("Convert2Lambda")
public class MainActivity extends Activity {
public static final int FIRST_INDEX = 0;
static String APP_PACKAGE_NAME = "com.ideasfrombrain.search_based_launcher_v3";
public static final App MENU_APP = new App(APP_PACKAGE_NAME + ".Menu", " Menu-Launcher", APP_PACKAGE_NAME + ".Menu");
boolean NewerAndroid = true;
List<App> pkg = new ArrayList<App>();
List<App> pkgFiltered = new ArrayList<App>();
List<App> extra = new ArrayList<App>();
List<App> hidden = new ArrayList<App>();
List<App> recent = new ArrayList<App>();
EditText DialogInput;
private final BroadcastReceiver mPkgApplicationsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
loadApps();
recent.retainAll(pkg);
extra.retainAll(pkg);
hidden.retainAll(pkg);
pkgFiltered.retainAll(pkg);
saveExtRemLists(false);
loadApps();
refresh();
}
};
private SearchText searchText;
private AppListView appListView;
private AutostartButton autostartButton;
private WifiButton wifiButton;
private BluetoothButton bluetoothButton;
private FlashButton flashButton;
private CameraButton cameraButton;
private RadioButtons radioButtons;
private void registerIntentReceivers() {
IntentFilter pkgFilter = new IntentFilter();
pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
pkgFilter.addDataScheme("package");
registerReceiver(mPkgApplicationsReceiver, pkgFilter);
}
public void loadApps() {
Log.d("DEBUG", "start loading apps");
Log.d("DEBUG", "activity arrays prepared");
final Intent main = new Intent(Intent.ACTION_MAIN, null);
final PackageManager pm = getPackageManager();
pkg.clear();
switch (radioButtons.getCheckedRadioButton()) {
case 0:
loadNormal(main, pm);
break;
case 1:
loadAll(main, pm);
break;
case 2:
loadExtra();
break;
case 3:
loadHidden();
break;
}
pkg.add(MENU_APP);
}
private void loadHidden() {
pkg.addAll(hidden);
}
private void loadExtra() {
pkg.addAll(extra);
}
private void loadAll(Intent main, PackageManager pm) {
final List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
for (ResolveInfo launchable : launchables) {
App app = new App(launchable.activityInfo.packageName, deriveNick(launchable), launchable.activityInfo.name);
pkg.add(app);
}
}
private String deriveNick(ResolveInfo launchable) {
String[] split = launchable.activityInfo.name.split("\\.");
String nick = split[1];
for (int j = 2; j < split.length; j++) {
nick = nick + ":" + split[j];
}
return nick;
}
private void loadNormal(Intent main, PackageManager pm) {
pkg.addAll(extra);
main.addCategory(Intent.CATEGORY_LAUNCHER); // will show only Regular Apps
final List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
for (ResolveInfo launchable : launchables) {
String nick = launchable.activityInfo.name;
if (ItemNumInHide(nick) == -1) {
String name = launchable.activityInfo.packageName;
String activity = launchable.activityInfo.loadLabel(pm).toString();
pkg.add(new App(name, nick, activity));
}
}
}
public void loadExtRemLists(boolean check) {
try {
final Context context = getApplicationContext();
extra = loadList("extra", context);
hidden = loadList("hidden", context);
recent = loadList("recent", context);
} catch (Exception e) {
//Log.d("DEBUG","excep. during load" + e.getStackTrace().toString());
saveExtRemLists(false);
}
}
public void saveExtRemLists(boolean check) {
final Context myContext = getApplicationContext();
saveList(extra, "extra", myContext);
saveList(hidden, "hidden", myContext);
saveList(recent, "recent", myContext);
}
public boolean saveList(List<App> list, String listName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences(listName, 0);
SharedPreferences.Editor editor = prefs.edit();
Set<String> set = new HashSet();
for (App app: list) {
set.add(app.getJsonString());
}
editor.putStringSet(listName, set);
return editor.commit();
}
public List<App> loadList(String listName, Context mContext) throws JSONException {
List<App> list = new ArrayList<>();
SharedPreferences prefs = mContext.getSharedPreferences(listName, 0);
for (String json: prefs.getStringSet(listName, null)) {
list.add(new App(json));
}
return list;
}
@Override
public boolean onKeyUp(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_MENU) {
myShowNext(false);
} else if (keycode == KeyEvent.KEYCODE_SEARCH) {
startSearch("", false, null, true);
} else if (keycode == KeyEvent.KEYCODE_BACK) {
ViewAnimator mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
if (mViewAnimator.getDisplayedChild() == 1) {
myShowNext(false);
}
} else {
return super.onKeyUp(keycode, event);
}
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appListView = new AppListView(this);
searchText = new SearchText(this);
autostartButton = new AutostartButton(this);
wifiButton = new WifiButton(this);
bluetoothButton = new BluetoothButton(this);
flashButton = new FlashButton(this);
cameraButton = new CameraButton(this);
//---------------MENU CODE
findViewById(R.id.donateButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PACKAGE_NAME));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(marketIntent);
}
});
findViewById(R.id.donateButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PACKAGE_NAME + "_donate"));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(marketIntent);
}
});
radioButtons = new RadioButtons(this);
//android version check
String Aversion = android.os.Build.VERSION.RELEASE;
if (savedInstanceState == null) {
if (Aversion.startsWith("1.") ||
Aversion.startsWith("2.0") ||
Aversion.startsWith("2.1")) {
NewerAndroid = false;
} else {
NewerAndroid = true;
}
loadExtRemLists(false);
loadApps();
} else {
NewerAndroid = savedInstanceState.getBoolean("NewerAndroid");
pkg.Name = savedInstanceState.getStringArrayList("pkg.Name");
pkg.Nick = savedInstanceState.getStringArrayList("pkg.Nick");
pkg.Activity = savedInstanceState.getStringArrayList("pkg.Activity");
extra.Name = savedInstanceState.getStringArrayList("extra.Name");
extra.Nick = savedInstanceState.getStringArrayList("extra.Nick");
extra.Activity = savedInstanceState.getStringArrayList("extra.Activity");
hidden.Name = savedInstanceState.getStringArrayList("hidden.Name");
hidden.Nick = savedInstanceState.getStringArrayList("hidden.Nick");
hidden.Activity = savedInstanceState.getStringArrayList("hidden.Activity");
recent.Name = savedInstanceState.getStringArrayList("recent.Name");
recent.Nick = savedInstanceState.getStringArrayList("recent.Nick");
recent.Activity = savedInstanceState.getStringArrayList("recent.Activity");
}
registerIntentReceivers();
}
public void myShowNext(Boolean DoLoadApps) {
searchText.setNormalColor();
ViewAnimator mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
//mViewAnimator.setInAnimation(null); // Skipping this will cause trouble
// mViewAnimator.setOutAnimation(null);
mViewAnimator.showNext();
if (mViewAnimator.getDisplayedChild() == 0) {
//final TextView myToggleButton = (TextView) findViewById(R.id.toggleButton0);
if (DoLoadApps) {
loadApps();
}
if (radioButtons.getCheckedRadioButton() > 0) {
searchText.setSpaceCharacterToText();
radioButtons.setInvisible();
} else {
wifiButton.setVisibleIfAvailable();
bluetoothButton.setVisibleIfAvailable();
cameraButton.setVisibleIfAvailable();
searchText.clearText();
}
} else {
RadioGroup mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
mRadioGroup.requestFocus();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
radioButtons.save();
savedInstanceState.putBoolean("NewerAndroid", NewerAndroid);
savedInstanceState.putStringArrayList("pkg.Name", pkg.Name);
savedInstanceState.putStringArrayList("pkg.Nick", pkg.Nick);
savedInstanceState.putStringArrayList("pkg.Activity", pkg.Activity);
savedInstanceState.putStringArrayList("extra.Name", extra.Name);
savedInstanceState.putStringArrayList("extra.Nick", extra.Nick);
savedInstanceState.putStringArrayList("extra.Activity", extra.Activity);
savedInstanceState.putStringArrayList("hidden.Name", hidden.Name);
savedInstanceState.putStringArrayList("hidden.Nick", hidden.Nick);
savedInstanceState.putStringArrayList("hidden.Activity", hidden.Activity);
savedInstanceState.putStringArrayList("recent.Name", recent.Name);
savedInstanceState.putStringArrayList("recent.Nick", recent.Nick);
savedInstanceState.putStringArrayList("recent.Activity", recent.Activity);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
}
@Override
protected void onResume() {
super.onResume();
searchText.setNormalColor();
if ((radioButtons.getCheckedRadioButton() == 0) && autostartButton.isAutostart()) {
searchText.clearText();
}
if (!NewerAndroid) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
@Override
public void onDestroy() {
wifiButton.unregisterReceiver();
unregisterReceiver(mPkgApplicationsReceiver);
super.onDestroy();
}
public void runApp(int index) {
searchText.setActivatedColor();
int tmpint = ItemNumInRecent(pkgFiltered.Activity.get(index));
if ((recent.Nick.size() >= 10) && (tmpint == -1)) {
recent.Name.remove(0);
recent.Nick.remove(0);
recent.Activity.remove(0);
} else if (tmpint != -1) {
recent.Name.remove(tmpint);
recent.Nick.remove(tmpint);
recent.Activity.remove(tmpint);
}
final Context myContext = getApplicationContext();
saveList(recent.Name, "recent.Name", myContext);
saveList(recent.Nick, "recent.Nick", myContext);
saveList(recent.Activity, "recent.Activity", myContext);
String tmpNickBefore = pkgFiltered.Nick.get(index);
recent.Name.add(pkgFiltered.Name.get(index));
if ((tmpNickBefore.matches("R:.*"))) {
tmpNickBefore = tmpNickBefore.substring(2, tmpNickBefore.length());
}
recent.Nick.add(tmpNickBefore);
recent.Activity.add(pkgFiltered.Activity.get(index));
if (!NewerAndroid) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
if ((APP_PACKAGE_NAME + ".Menu").equals(pkgFiltered.Name.get(index))) {
myShowNext(false);
} else {
try {
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(pkgFiltered.Name.get(index), pkgFiltered.Activity.get(index)));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(intent);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("DEBUG", e.getMessage());
searchText.setNormalColor();
if (!NewerAndroid) {
final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
}
}
public void refresh() {
pkgFiltered.Name.clear();
pkgFiltered.Nick.clear();
pkgFiltered.Activity.clear();
String FilterText = searchText.getFilterText();
int tmpsize = recent.Name.size();
for (int i = 0; i < tmpsize; i++) {
//Log.d("DEBUG", recent.Name.get(tmpsize-1-i));
if (recent.Nick.get(tmpsize - 1 - i).toLowerCase().matches(FilterText)) {
pkgFiltered.Name.add(recent.Name.get(tmpsize - 1 - i));
pkgFiltered.Activity.add(recent.Activity.get(tmpsize - 1 - i));
pkgFiltered.Nick.add("R:" + recent.Nick.get(tmpsize - 1 - i));
}
}
for (int i = 0; i < pkg.Name.size(); i++) {
if ((pkg.Nick.get(i).toLowerCase().matches(FilterText)) && (ItemNumInRecent(pkg.Activity.get(i)) == -1)) {
pkgFiltered.Name.add(pkg.Name.get(i));
pkgFiltered.Activity.add(pkg.Activity.get(i));
pkgFiltered.Nick.add(pkg.Nick.get(i));
//Log.d("DEBUG", pkg.Nick[i]);
}
}
if (((pkgFiltered.Name.size()) == 1) && autostartButton.isAutostart()) {
runApp(FIRST_INDEX);
} else {
appListView.setAppList(pkgFiltered.Nick);
}
//}
}
//@Override
public boolean showOptionsForApp(final int index) {
final String activity = pkgFiltered.Activity.get(index);
final String name = pkgFiltered.Name.get(index);
final String nickBefore = pkgFiltered.Nick.get(index);
if ((activity == APP_PACKAGE_NAME + ".Menu")) {
return false;
}
String nick;
if ((nickBefore.matches("R:.*"))) {
nick = nickBefore.substring(2, nickBefore.length());
} else {
nick = nickBefore;
}
switch (radioButtons.getCheckedRadioButton()) {
case 0:
showNormalOptions(activity, name, nick);
break;
case 1:
showAddExtraAppOptions(index, nick);
break;
case 2:
showRemoveExtraAppOptions(index, activity, nick);
break;
case 3:
showUnhideAppOptions(index, activity, nick);
break;
}
return false;
}
private void showUnhideAppOptions(int index, final String tmpActivity, String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Remove this activity (hidden app) from hidden applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInHide = MainActivity.this.ItemNumInHide(tmpActivity);
if (tmpItemNumInHide != -1) {
hidden.Activity.remove(tmpItemNumInHide);
hidden.Name.remove(tmpItemNumInHide);
hidden.Nick.remove(tmpItemNumInHide);
MainActivity.this.saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.create().show();
}
private void showRemoveExtraAppOptions(int index, final String tmpActivity, final String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Remove this (extra added list of all activities) activity from applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if (tmpItemNumInExtra != -1) {
extra.Activity.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Nick.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
MainActivity.this.saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.create().show();
}
private void showAddExtraAppOptions(final int index, String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(pkgFiltered.Nick.get(index));
dialog.setView(DialogInput);
dialog.setMessage("Add this activity to applications list?");
dialog.setCancelable(true);
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
extra.Name.add(pkgFiltered.Name.get(index));
extra.Nick.add(DialogInput.getText().toString());
extra.Activity.add(pkgFiltered.Activity.get(index));
saveExtRemLists(true);
loadApps();
refresh();
dialog.dismiss();
}
});
dialog.create().show();
}
private void showNormalOptions(final String tmpActivity, final String tmpName, final String nick) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(nick);
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if ((tmpItemNumInExtra == -1) && (MainActivity.this.ItemNumInHide(tmpActivity) == -1)) {
showHideApp(tmpActivity, tmpName, nick, dialog);
} else if ((tmpItemNumInExtra != -1) && (MainActivity.this.ItemNumInHide(tmpActivity) != -1)) {
showRenamedApp(tmpActivity, tmpName, nick, dialog);
} else if (tmpItemNumInExtra != -1) {
showExtraAddedApp(tmpActivity, dialog);
}
dialog.create().show();
}
private void showExtraAddedApp(final String tmpActivity, AlertDialog.Builder dialog) {
dialog.setMessage("Remove activity " + tmpActivity + " from extra added (to applications list) list ?");
dialog.setCancelable(true);
dialog.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
extra.Activity.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Nick.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
});
}
private void showRenamedApp(final String tmpActivity, final String tmpName, String nick, AlertDialog.Builder dialog) {
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(nick);
dialog.setView(DialogInput);
dialog.setMessage("This application is in both add and hide lists, thus is probably renamed.");
dialog.setCancelable(true);
dialog.setPositiveButton("Hide", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
//hidden.Name.add(tmpName);
//hidden.Nick.add(tmpNick);
//hidden.Activity.add(tmpActivity);
extra.Nick.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Activity.remove(tmpItemNumInExtra);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.setNeutralButton("Uninstall", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + tmpName));
startActivity(intent);
//loadApps();
refresh();
dialog.dismiss();
}
});
dialog.setNegativeButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int tmpItemNumInExtra = MainActivity.this.ItemNumInExtra(tmpActivity);
//hidden.Name.add(tmpName);
//hidden.Nick.add(tmpNick);
//hidden.Activity.add(tmpActivity);
extra.Nick.remove(tmpItemNumInExtra);
extra.Name.remove(tmpItemNumInExtra);
extra.Activity.remove(tmpItemNumInExtra);
extra.Nick.add(DialogInput.getText().toString());
extra.Name.add(tmpName);
extra.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.set(tmpItemNumInRecent, DialogInput.getText().toString());
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
});
}
private void showHideApp(final String tmpActivity, final String tmpName, final String nick, AlertDialog.Builder dialog) {
DialogInput = new EditText(this);
DialogInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
DialogInput.setText(nick);
dialog.setView(DialogInput);
dialog.setMessage("Hide this application from applications list, rename application (add to Hide and Extra list with diferent names) or uninstall it?");
dialog.setCancelable(true);
dialog.setPositiveButton("Hide", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//int tmpItemNumInExtra=MainActivity.this.ItemNumInExtra(tmpActivity);
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
hidden.Name.add(tmpName);
hidden.Nick.add(nick);
hidden.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.remove(tmpItemNumInRecent);
recent.Name.remove(tmpItemNumInRecent);
recent.Activity.remove(tmpItemNumInRecent);
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
dialog.setNeutralButton("Uninstall", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + tmpName));
startActivity(intent);
//loadApps();
refresh();
dialog.dismiss();
}
});
dialog.setNegativeButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (MainActivity.this.ItemNumInHide(tmpActivity) == -1) {
hidden.Name.add(tmpName);
hidden.Nick.add(nick);
hidden.Activity.add(tmpActivity);
extra.Nick.add(DialogInput.getText().toString());
extra.Name.add(tmpName);
extra.Activity.add(tmpActivity);
int tmpItemNumInRecent = ItemNumInRecent(tmpActivity);
if (tmpItemNumInRecent != -1) {
recent.Nick.set(tmpItemNumInRecent, DialogInput.getText().toString());
}
saveExtRemLists(false);
loadApps();
refresh();
dialog.dismiss();
}
}
});
}
public int ItemNumInExtra(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < extra.Activity.size(); i++) {
if (Activity.equals(extra.Activity.get(i))) {
return i;
}
}
return -1;
}
public int ItemNumInHide(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < hidden.Activity.size(); i++) {
if (Activity.equals(hidden.Activity.get(i))) {
return i;
}
}
return -1;
}
public int ItemNumInRecent(String Activity) { // NOTE: if not found returns -1
for (int i = 0; i < recent.Activity.size(); i++) {
if (Activity.equals(recent.Activity.get(i))) {
return i;
}
}
return -1;
}
} | Extract methods.
| src/com/ideasfrombrain/search_based_launcher_v3/MainActivity.java | Extract methods. | <ide><path>rc/com/ideasfrombrain/search_based_launcher_v3/MainActivity.java
<ide> import android.widget.RadioGroup;
<ide>
<ide> import org.json.JSONException;
<del>import org.json.JSONObject;
<ide>
<ide>
<ide> @SuppressWarnings("Convert2Lambda")
<ide> static String APP_PACKAGE_NAME = "com.ideasfrombrain.search_based_launcher_v3";
<ide> public static final App MENU_APP = new App(APP_PACKAGE_NAME + ".Menu", " Menu-Launcher", APP_PACKAGE_NAME + ".Menu");
<ide>
<del> boolean NewerAndroid = true;
<add> boolean newerAndroidVersion = true;
<ide>
<ide> List<App> pkg = new ArrayList<App>();
<ide> List<App> pkgFiltered = new ArrayList<App>();
<ide> public void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> setContentView(R.layout.activity_main);
<del>
<ide> appListView = new AppListView(this);
<ide> searchText = new SearchText(this);
<ide> autostartButton = new AutostartButton(this);
<ide> bluetoothButton = new BluetoothButton(this);
<ide> flashButton = new FlashButton(this);
<ide> cameraButton = new CameraButton(this);
<del>
<del>
<del> //---------------MENU CODE
<del>
<del>
<add> createMenuDonateButton();
<add> radioButtons = new RadioButtons(this);
<add> setAndroidVersion();
<add> setAppLists(savedInstanceState);
<add> registerIntentReceivers();
<add> }
<add>
<add> private void createMenuDonateButton() {
<ide> findViewById(R.id.donateButton).setOnClickListener(new View.OnClickListener() {
<ide> public void onClick(View v) {
<ide> Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PACKAGE_NAME));
<ide> startActivity(marketIntent);
<ide> }
<ide> });
<del>
<del> findViewById(R.id.donateButton).setOnClickListener(new View.OnClickListener() {
<del> public void onClick(View v) {
<del> Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PACKAGE_NAME + "_donate"));
<del> marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
<del> startActivity(marketIntent);
<del> }
<del> });
<del>
<del> radioButtons = new RadioButtons(this);
<del>
<del>
<del> //android version check
<del> String Aversion = android.os.Build.VERSION.RELEASE;
<add> }
<add>
<add> private void setAppLists(Bundle savedInstanceState) {
<ide> if (savedInstanceState == null) {
<del> if (Aversion.startsWith("1.") ||
<del> Aversion.startsWith("2.0") ||
<del> Aversion.startsWith("2.1")) {
<del> NewerAndroid = false;
<del> } else {
<del> NewerAndroid = true;
<del> }
<add>
<ide>
<ide> loadExtRemLists(false);
<ide> loadApps();
<ide> } else {
<ide>
<del> NewerAndroid = savedInstanceState.getBoolean("NewerAndroid");
<del>
<ide> pkg.Name = savedInstanceState.getStringArrayList("pkg.Name");
<ide> pkg.Nick = savedInstanceState.getStringArrayList("pkg.Nick");
<ide> pkg.Activity = savedInstanceState.getStringArrayList("pkg.Activity");
<ide> recent.Activity = savedInstanceState.getStringArrayList("recent.Activity");
<ide>
<ide> }
<del> registerIntentReceivers();
<del>
<del>
<add> }
<add>
<add> private void setAndroidVersion() {
<add> String Aversion = android.os.Build.VERSION.RELEASE;
<add> if (Aversion.startsWith("1.") ||
<add> Aversion.startsWith("2.0") ||
<add> Aversion.startsWith("2.1")) {
<add> newerAndroidVersion = false;
<add> } else {
<add> newerAndroidVersion = true;
<add> }
<ide> }
<ide>
<ide>
<ide> // killed and restarted.
<ide>
<ide> radioButtons.save();
<del> savedInstanceState.putBoolean("NewerAndroid", NewerAndroid);
<add> savedInstanceState.putBoolean("newerAndroidVersion", newerAndroidVersion);
<ide>
<ide> savedInstanceState.putStringArrayList("pkg.Name", pkg.Name);
<ide> savedInstanceState.putStringArrayList("pkg.Nick", pkg.Nick);
<ide> searchText.clearText();
<ide> }
<ide>
<del> if (!NewerAndroid) {
<add> if (!newerAndroidVersion) {
<ide> final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
<ide> if (imm != null) {
<ide> imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
<ide> recent.Nick.add(tmpNickBefore);
<ide> recent.Activity.add(pkgFiltered.Activity.get(index));
<ide>
<del> if (!NewerAndroid) {
<add> if (!newerAndroidVersion) {
<ide> final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
<ide> if (imm != null) {
<ide> imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
<ide> Log.d("DEBUG", e.getMessage());
<ide> searchText.setNormalColor();
<ide>
<del> if (!NewerAndroid) {
<add> if (!newerAndroidVersion) {
<ide> final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
<ide> if (imm != null) {
<ide> imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); |
|
JavaScript | apache-2.0 | 7ea1efeeb6f7fbb0fea8d55a98e26a8dab99f23d | 0 | anthonysena/Atlas,anthonysena/Atlas,OHDSI/Atlas,OHDSI/Atlas,OHDSI/Atlas,OHDSI/Atlas | define([
'knockout',
'text!./source-manager.html',
'providers/Component',
'providers/AutoBind',
'utils/CommonUtils',
'appConfig',
'assets/ohdsi.util',
'webapi/SourceAPI',
'services/role',
'lodash',
'webapi/AuthAPI',
'components/ac-access-denied',
'less!./source-manager.less',
'components/heading',
],
function (
ko,
view,
Component,
AutoBind,
commonUtils,
config,
ohdsiUtil,
sourceApi,
roleService,
lodash,
authApi
) {
var defaultDaimons = {
CDM: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Vocabulary: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Results: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Evidence: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Temp: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
};
function Source(data) {
function mapDaimons(daimons) {
daimons = daimons || [];
var defaultKeys = Object.keys(defaultDaimons);
var keys = daimons.map(function (value) { return value.daimonType; });
var result = daimons.map(function (value) {
return {
...lodash.omit(value, ['tableQualifier']),
tableQualifier: ko.observable(value.tableQualifier),
enabled: ko.observable(true),
};
});
var diff = lodash.difference(defaultKeys, keys).map(function(key){
return {
...defaultDaimons[key],
daimonType: key,
enabled: ko.observable(false),
};
});
return lodash.concat(result, diff);
}
var data = data || {};
this.name = ko.observable(data.sourceName || null);
this.key = ko.observable(data.sourceKey || null);
this.dialect = ko.observable(data.sourceDialect || null);
this.connectionString = ko.observable(data.connectionString || null);
this.username = ko.observable(data.username || null);
this.password = ko.observable(data.password || null);
this.daimons = ko.observableArray(mapDaimons(data.daimons));
this.keytabName = ko.observable(data.keytabName);
this.krbAuthMethod = ko.observable(data.krbAuthMethod);
this.krbAdminServer = ko.observable(data.krbAdminServer);
return this;
}
class SourceManager extends AutoBind(Component) {
constructor(params) {
super(params);
this.config = config;
this.model = params.model;
this.loading = ko.observable(false);
this.dirtyFlag = this.model.currentSourceDirtyFlag;
this.selectedSource = params.model.currentSource;
this.selectedSourceId = params.model.selectedSourceId;
this.options = {};
this.isAuthenticated = authApi.isAuthenticated;
this.hasAccess = ko.pureComputed(() => {
if (!config.userAuthenticationEnabled) {
return false;
} else {
return this.isAuthenticated() && authApi.isPermittedEditConfiguration();
}
});
this.canReadSource = ko.pureComputed(() => {
return authApi.isPermittedReadSource(this.selectedSourceId()) || !this.selectedSourceId();
});
this.isDeletePermitted = ko.pureComputed(() => {
return authApi.isPermittedDeleteSource(this.selectedSource().key());
});
this.canEdit = ko.pureComputed(() => {
return authApi.isPermittedEditSource(this.selectedSourceId());
});
this.canSave = ko.pureComputed(() => {
return (
this.selectedSource()
&& this.selectedSource().name()
&& this.selectedSource().key()
&& this.selectedSource().connectionString()
&& this.canEdit()
);
});
this.canDelete = () => {
return (
this.selectedSource()
&& this.selectedSource().key()
&& this.isDeletePermitted()
);
};
this.canEditKey = ko.pureComputed(() => {
return !this.selectedSourceId();
});
this.options.dialectOptions = [
{ name: 'PostgreSQL', id: 'postgresql' },
{ name: 'SQL server', id: 'sqlserver' },
{ name: 'Oracle', id: 'oracle' },
{ name: 'Amazon Redshift', id: 'redshift' },
{ name: 'Google BigQuery', id: 'bigquery' },
{ name: 'Impala', id: 'impala' },
{ name: 'Microsoft PDW', id: 'pdw' },
{ name: 'IBM Netezza', id: 'netezza' },
];
this.sourceCaption = ko.computed(() => {
return (this.model.currentSource() == null || this.model.currentSource().key() == null) ? 'New source' :
'Source ' + this.model.currentSource().name();
});
this.isKrbAuth = ko.computed(() => {
return this.impalaConnectionStringIncludes("AuthMech=1");
});
this.krbHostFQDN = ko.computed(() => {
if (this.isImpalaDS() && this.isNonEmptyConnectionString()) {
var str = this.selectedSource().connectionString();
var strArray = str.match(/KrbHostFQDN=(.*?);/);
if (strArray != null){
var matchedStr = strArray[0];
return matchedStr.substring(matchedStr.search("=") + 1, matchedStr.length - 1);
} else {
return "";
}
}
return "";
});
this.krbRealm = ko.computed(() => {
if (this.isImpalaDS() && this.isNonEmptyConnectionString()) {
var str = this.selectedSource().connectionString();
var strArray = str.match(/KrbRealm=(.*?);/);
if (strArray != null){
var matchedStr = strArray[0];
return matchedStr.substring(matchedStr.search("=") + 1, matchedStr.length - 1);
} else {
return "";
}
}
return "";
});
this.init();
this.fieldsVisibility = {
username: ko.computed(() => !this.isImpalaDS() || this.isKrbAuth()),
password: ko.computed(() => !this.isImpalaDS()),
krbAuthSettings: this.isKrbAuth,
showKeytab: ko.computed(() => {
return this.isKrbAuth() && this.selectedSource().krbAuthMethod() === 'keytab';
}),
krbFileInput: ko.computed(() => {
return this.isKrbAuth() && (typeof this.selectedSource().keytabName() !== 'string' || this.selectedSource().keytabName().length === 0);
}),
// warnings
hostWarning: ko.computed(() => {
var showWarning = this.isKrbAuth() && this.krbHostFQDN() === "";
if (showWarning){
this.dirtyFlag().reset();
}
return showWarning;
}),
realmWarning: ko.computed(() => {
var showWarning = this.isKrbAuth() && this.krbRealm() === "";
if (showWarning) {
this.dirtyFlag().reset();
}
return showWarning;
}),
userWarning: ko.computed(() => {
var showWarning = this.selectedSource() != null && this.selectedSource().username() === "";
if (showWarning) {
this.dirtyFlag().reset();
}
return showWarning;
}),
};
}
newSource() {
this.selectedSource(new Source());
this.dirtyFlag(new ohdsiUtil.dirtyFlag(this.selectedSource()));
}
isImpalaDS() {
return this.selectedSource() && this.selectedSource().dialect() === 'impala';
}
isNonEmptyConnectionString() {
return this.selectedSource() != null && typeof this.selectedSource().connectionString() === 'string' && this.selectedSource().connectionString().length > 0;
}
impalaConnectionStringIncludes(substr) {
return this.isImpalaDS() && this.isNonEmptyConnectionString() && this.selectedSource().connectionString().includes(substr);
}
removeKeytab() {
$('#keytabFile').val(''); // TODO: create "ref" directive
this.keytab = null;
this.selectedSource().keytabName(null);
}
uploadFile(file) {
this.keytab = file;
this.selectedSource().keytabName(file.name)
}
save() {
var source = {
name: this.selectedSource().name() || null,
key: this.selectedSource().key() || null,
dialect: this.selectedSource().dialect() || null,
connectionString: this.selectedSource().connectionString() || null,
krbAuthMethod: this.selectedSource().krbAuthMethod() || "password",
krbAdminServer: this.selectedSource().krbAdminServer() || null,
username: this.selectedSource().username() || null,
password: this.selectedSource().password() || null,
daimons: ko.toJS(this.selectedSource().daimons()).filter(function(d) { return d.enabled; }).map(function(d) {
return lodash.omit(d, ['enabled']);
}),
keytabName: this.selectedSource().keytabName(),
keytab: this.keytab,
};
this.loading(true);
sourceApi.saveSource(this.selectedSourceId(), source)
.then(() => sourceApi.initSourcesConfig())
.then(() => {
roleService.getList()
.then((roles) => {
this.model.roles(roles);
this.loading(false);
this.goToConfigure();
});
})
.catch(() => { this.loading(false); });
}
close() {
if (this.dirtyFlag().isDirty() && !confirm('Source changes are not saved. Would you like to continue?')) {
return;
}
this.selectedSource(null);
this.selectedSourceId(null);
this.dirtyFlag().reset();
this.goToConfigure();
}
delete() {
if (!confirm('Delete source? Warning: deletion can not be undone!')) {
return;
}
this.loading(true);
sourceApi.deleteSource(this.selectedSourceId())
.then(sourceApi.initSourcesConfig)
.then(() => roleService.getList())
.then((roles) => {
this.model.roles(roles);
this.loading(false);
this.goToConfigure();
})
.catch(() => this.loading(false));
}
goToConfigure() {
document.location = '#/configure';
}
init() {
if (this.hasAccess()) {
if (this.selectedSourceId() == null) {
this.newSource();
} else {
this.loading(true);
sourceApi.getSource(this.selectedSourceId())
.then((source) => {
this.selectedSource(new Source(source));
this.dirtyFlag(new ohdsiUtil.dirtyFlag(this.selectedSource()));
this.loading(false);
});
}
}
}
}
return commonUtils.build('source-manager', SourceManager, view);
});
| js/pages/configuration/sources/source-manager.js | define([
'knockout',
'text!./source-manager.html',
'providers/Component',
'providers/AutoBind',
'utils/CommonUtils',
'appConfig',
'assets/ohdsi.util',
'webapi/SourceAPI',
'services/role',
'lodash',
'webapi/AuthAPI',
'components/ac-access-denied',
'less!./source-manager.less',
'components/heading',
],
function (
ko,
view,
Component,
AutoBind,
commonUtils,
config,
ohdsiUtil,
sourceApi,
roleService,
lodash,
authApi
) {
var defaultDaimons = {
CDM: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Vocabulary: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Results: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
Evidence: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
};
function Source(data) {
function mapDaimons(daimons) {
daimons = daimons || [];
var defaultKeys = Object.keys(defaultDaimons);
var keys = daimons.map(function (value) { return value.daimonType; });
var result = daimons.map(function (value) {
return {
...lodash.omit(value, ['tableQualifier']),
tableQualifier: ko.observable(value.tableQualifier),
enabled: ko.observable(true),
};
});
var diff = lodash.difference(defaultKeys, keys).map(function(key){
return {
...defaultDaimons[key],
daimonType: key,
enabled: ko.observable(false),
};
});
return lodash.concat(result, diff);
}
var data = data || {};
this.name = ko.observable(data.sourceName || null);
this.key = ko.observable(data.sourceKey || null);
this.dialect = ko.observable(data.sourceDialect || null);
this.connectionString = ko.observable(data.connectionString || null);
this.username = ko.observable(data.username || null);
this.password = ko.observable(data.password || null);
this.daimons = ko.observableArray(mapDaimons(data.daimons));
this.keytabName = ko.observable(data.keytabName);
this.krbAuthMethod = ko.observable(data.krbAuthMethod);
this.krbAdminServer = ko.observable(data.krbAdminServer);
return this;
}
class SourceManager extends AutoBind(Component) {
constructor(params) {
super(params);
this.config = config;
this.model = params.model;
this.loading = ko.observable(false);
this.dirtyFlag = this.model.currentSourceDirtyFlag;
this.selectedSource = params.model.currentSource;
this.selectedSourceId = params.model.selectedSourceId;
this.options = {};
this.isAuthenticated = authApi.isAuthenticated;
this.hasAccess = ko.pureComputed(() => {
if (!config.userAuthenticationEnabled) {
return false;
} else {
return this.isAuthenticated() && authApi.isPermittedEditConfiguration();
}
});
this.canReadSource = ko.pureComputed(() => {
return authApi.isPermittedReadSource(this.selectedSourceId()) || !this.selectedSourceId();
});
this.isDeletePermitted = ko.pureComputed(() => {
return authApi.isPermittedDeleteSource(this.selectedSource().key());
});
this.canEdit = ko.pureComputed(() => {
return authApi.isPermittedEditSource(this.selectedSourceId());
});
this.canSave = ko.pureComputed(() => {
return (
this.selectedSource()
&& this.selectedSource().name()
&& this.selectedSource().key()
&& this.selectedSource().connectionString()
&& this.canEdit()
);
});
this.canDelete = () => {
return (
this.selectedSource()
&& this.selectedSource().key()
&& this.isDeletePermitted()
);
};
this.canEditKey = ko.pureComputed(() => {
return !this.selectedSourceId();
});
this.options.dialectOptions = [
{ name: 'PostgreSQL', id: 'postgresql' },
{ name: 'SQL server', id: 'sqlserver' },
{ name: 'Oracle', id: 'oracle' },
{ name: 'Amazon Redshift', id: 'redshift' },
{ name: 'Google BigQuery', id: 'bigquery' },
{ name: 'Impala', id: 'impala' },
{ name: 'Microsoft PDW', id: 'pdw' },
{ name: 'IBM Netezza', id: 'netezza' },
];
this.sourceCaption = ko.computed(() => {
return (this.model.currentSource() == null || this.model.currentSource().key() == null) ? 'New source' :
'Source ' + this.model.currentSource().name();
});
this.isKrbAuth = ko.computed(() => {
return this.impalaConnectionStringIncludes("AuthMech=1");
});
this.krbHostFQDN = ko.computed(() => {
if (this.isImpalaDS() && this.isNonEmptyConnectionString()) {
var str = this.selectedSource().connectionString();
var strArray = str.match(/KrbHostFQDN=(.*?);/);
if (strArray != null){
var matchedStr = strArray[0];
return matchedStr.substring(matchedStr.search("=") + 1, matchedStr.length - 1);
} else {
return "";
}
}
return "";
});
this.krbRealm = ko.computed(() => {
if (this.isImpalaDS() && this.isNonEmptyConnectionString()) {
var str = this.selectedSource().connectionString();
var strArray = str.match(/KrbRealm=(.*?);/);
if (strArray != null){
var matchedStr = strArray[0];
return matchedStr.substring(matchedStr.search("=") + 1, matchedStr.length - 1);
} else {
return "";
}
}
return "";
});
this.init();
this.fieldsVisibility = {
username: ko.computed(() => !this.isImpalaDS() || this.isKrbAuth()),
password: ko.computed(() => !this.isImpalaDS()),
krbAuthSettings: this.isKrbAuth,
showKeytab: ko.computed(() => {
return this.isKrbAuth() && this.selectedSource().krbAuthMethod() === 'keytab';
}),
krbFileInput: ko.computed(() => {
return this.isKrbAuth() && (typeof this.selectedSource().keytabName() !== 'string' || this.selectedSource().keytabName().length === 0);
}),
// warnings
hostWarning: ko.computed(() => {
var showWarning = this.isKrbAuth() && this.krbHostFQDN() === "";
if (showWarning){
this.dirtyFlag().reset();
}
return showWarning;
}),
realmWarning: ko.computed(() => {
var showWarning = this.isKrbAuth() && this.krbRealm() === "";
if (showWarning) {
this.dirtyFlag().reset();
}
return showWarning;
}),
userWarning: ko.computed(() => {
var showWarning = this.selectedSource() != null && this.selectedSource().username() === "";
if (showWarning) {
this.dirtyFlag().reset();
}
return showWarning;
}),
};
}
newSource() {
this.selectedSource(new Source());
this.dirtyFlag(new ohdsiUtil.dirtyFlag(this.selectedSource()));
}
isImpalaDS() {
return this.selectedSource() && this.selectedSource().dialect() === 'impala';
}
isNonEmptyConnectionString() {
return this.selectedSource() != null && typeof this.selectedSource().connectionString() === 'string' && this.selectedSource().connectionString().length > 0;
}
impalaConnectionStringIncludes(substr) {
return this.isImpalaDS() && this.isNonEmptyConnectionString() && this.selectedSource().connectionString().includes(substr);
}
removeKeytab() {
$('#keytabFile').val(''); // TODO: create "ref" directive
this.keytab = null;
this.selectedSource().keytabName(null);
}
uploadFile(file) {
this.keytab = file;
this.selectedSource().keytabName(file.name)
}
save() {
var source = {
name: this.selectedSource().name() || null,
key: this.selectedSource().key() || null,
dialect: this.selectedSource().dialect() || null,
connectionString: this.selectedSource().connectionString() || null,
krbAuthMethod: this.selectedSource().krbAuthMethod() || "password",
krbAdminServer: this.selectedSource().krbAdminServer() || null,
username: this.selectedSource().username() || null,
password: this.selectedSource().password() || null,
daimons: ko.toJS(this.selectedSource().daimons()).filter(function(d) { return d.enabled; }).map(function(d) {
return lodash.omit(d, ['enabled']);
}),
keytabName: this.selectedSource().keytabName(),
keytab: this.keytab,
};
this.loading(true);
sourceApi.saveSource(this.selectedSourceId(), source)
.then(() => sourceApi.initSourcesConfig())
.then(() => {
roleService.getList()
.then((roles) => {
this.model.roles(roles);
this.loading(false);
this.goToConfigure();
});
})
.catch(() => { this.loading(false); });
}
close() {
if (this.dirtyFlag().isDirty() && !confirm('Source changes are not saved. Would you like to continue?')) {
return;
}
this.selectedSource(null);
this.selectedSourceId(null);
this.dirtyFlag().reset();
this.goToConfigure();
}
delete() {
if (!confirm('Delete source? Warning: deletion can not be undone!')) {
return;
}
this.loading(true);
sourceApi.deleteSource(this.selectedSourceId())
.then(sourceApi.initSourcesConfig)
.then(() => roleService.getList())
.then((roles) => {
this.model.roles(roles);
this.loading(false);
this.goToConfigure();
})
.catch(() => this.loading(false));
}
goToConfigure() {
document.location = '#/configure';
}
init() {
if (this.hasAccess()) {
if (this.selectedSourceId() == null) {
this.newSource();
} else {
this.loading(true);
sourceApi.getSource(this.selectedSourceId())
.then((source) => {
this.selectedSource(new Source(source));
this.dirtyFlag(new ohdsiUtil.dirtyFlag(this.selectedSource()));
this.loading(false);
});
}
}
}
}
return commonUtils.build('source-manager', SourceManager, view);
});
| ATLP-537 - new daimon Temp; use in createCohortTable.sql
| js/pages/configuration/sources/source-manager.js | ATLP-537 - new daimon Temp; use in createCohortTable.sql | <ide><path>s/pages/configuration/sources/source-manager.js
<ide> Vocabulary: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
<ide> Results: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
<ide> Evidence: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
<add> Temp: { tableQualifier: '', enabled: false, priority: 0, sourceDaimonId: null },
<ide> };
<ide>
<ide> function Source(data) { |
|
Java | apache-2.0 | cf87e5322ac6c0b46409ca2e0f014783bc17b68c | 0 | opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open | package net.onrc.onos.ofcontroller.flowmanager;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import net.floodlightcontroller.util.MACAddress;
import net.onrc.onos.graph.GraphDBOperation;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for performing Flow-related operations on the Database.
*/
public class FlowDatabaseOperation {
private final static Logger log = LoggerFactory.getLogger(FlowDatabaseOperation.class);
/**
* Add a flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowPath the Flow Path to install.
* @return true on success, otherwise false.
*/
static boolean addFlow(GraphDBOperation dbHandler, FlowPath flowPath) {
IFlowPath flowObj = null;
boolean found = false;
try {
if ((flowObj = dbHandler.searchFlowPath(flowPath.flowId())) != null) {
found = true;
} else {
flowObj = dbHandler.newFlowPath();
}
} catch (Exception e) {
dbHandler.rollback();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
log.error(":addFlow FlowId:{} failed: {}",
flowPath.flowId().toString(),
stacktrace);
return false;
}
if (flowObj == null) {
log.error(":addFlow FlowId:{} failed: Flow object not created",
flowPath.flowId().toString());
dbHandler.rollback();
return false;
}
//
// Remove the old Flow Entries
//
if (found) {
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
LinkedList<IFlowEntry> deleteFlowEntries =
new LinkedList<IFlowEntry>();
for (IFlowEntry flowEntryObj : flowEntries)
deleteFlowEntries.add(flowEntryObj);
for (IFlowEntry flowEntryObj : deleteFlowEntries) {
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
}
}
//
// Set the Flow key:
// - flowId
//
flowObj.setFlowId(flowPath.flowId().toString());
flowObj.setType("flow");
//
// Set the Flow attributes:
// - flowPath.installerId()
// - flowPath.flowPathType()
// - flowPath.flowPathUserState()
// - flowPath.flowPathFlags()
// - flowPath.idleTimeout()
// - flowPath.hardTimeout()
// - flowPath.dataPath().srcPort()
// - flowPath.dataPath().dstPort()
// - flowPath.matchSrcMac()
// - flowPath.matchDstMac()
// - flowPath.matchEthernetFrameType()
// - flowPath.matchVlanId()
// - flowPath.matchVlanPriority()
// - flowPath.matchSrcIPv4Net()
// - flowPath.matchDstIPv4Net()
// - flowPath.matchIpProto()
// - flowPath.matchIpToS()
// - flowPath.matchSrcTcpUdpPort()
// - flowPath.matchDstTcpUdpPort()
// - flowPath.flowEntryActions()
//
flowObj.setInstallerId(flowPath.installerId().toString());
flowObj.setFlowPathType(flowPath.flowPathType().toString());
flowObj.setFlowPathUserState(flowPath.flowPathUserState().toString());
flowObj.setFlowPathFlags(flowPath.flowPathFlags().flags());
flowObj.setIdleTimeout(flowPath.idleTimeout());
flowObj.setHardTimeout(flowPath.hardTimeout());
flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString());
flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value());
flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString());
flowObj.setDstPort(flowPath.dataPath().dstPort().port().value());
if (flowPath.flowEntryMatch().matchSrcMac()) {
flowObj.setMatchSrcMac(flowPath.flowEntryMatch().srcMac().toString());
}
if (flowPath.flowEntryMatch().matchDstMac()) {
flowObj.setMatchDstMac(flowPath.flowEntryMatch().dstMac().toString());
}
if (flowPath.flowEntryMatch().matchEthernetFrameType()) {
flowObj.setMatchEthernetFrameType(flowPath.flowEntryMatch().ethernetFrameType());
}
if (flowPath.flowEntryMatch().matchVlanId()) {
flowObj.setMatchVlanId(flowPath.flowEntryMatch().vlanId());
}
if (flowPath.flowEntryMatch().matchVlanPriority()) {
flowObj.setMatchVlanPriority(flowPath.flowEntryMatch().vlanPriority());
}
if (flowPath.flowEntryMatch().matchSrcIPv4Net()) {
flowObj.setMatchSrcIPv4Net(flowPath.flowEntryMatch().srcIPv4Net().toString());
}
if (flowPath.flowEntryMatch().matchDstIPv4Net()) {
flowObj.setMatchDstIPv4Net(flowPath.flowEntryMatch().dstIPv4Net().toString());
}
if (flowPath.flowEntryMatch().matchIpProto()) {
flowObj.setMatchIpProto(flowPath.flowEntryMatch().ipProto());
}
if (flowPath.flowEntryMatch().matchIpToS()) {
flowObj.setMatchIpToS(flowPath.flowEntryMatch().ipToS());
}
if (flowPath.flowEntryMatch().matchSrcTcpUdpPort()) {
flowObj.setMatchSrcTcpUdpPort(flowPath.flowEntryMatch().srcTcpUdpPort());
}
if (flowPath.flowEntryMatch().matchDstTcpUdpPort()) {
flowObj.setMatchDstTcpUdpPort(flowPath.flowEntryMatch().dstTcpUdpPort());
}
if (! flowPath.flowEntryActions().actions().isEmpty()) {
flowObj.setActions(flowPath.flowEntryActions().toString());
}
flowObj.setDataPathSummary(flowPath.dataPath().dataPathSummary());
if (found)
flowObj.setFlowPathUserState("FP_USER_MODIFY");
else
flowObj.setFlowPathUserState("FP_USER_ADD");
// Flow edges:
// HeadFE
//
// Flow Entries:
// flowPath.dataPath().flowEntries()
//
for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_DELETE)
continue; // Skip: all Flow Entries were deleted earlier
if (addFlowEntry(dbHandler, flowObj, flowEntry) == null) {
dbHandler.rollback();
return false;
}
}
dbHandler.commit();
return true;
}
/**
* Add a flow entry to the Network MAP.
*
* @param dbHandler the Graph Database handler to use.
* @param flowObj the corresponding Flow Path object for the Flow Entry.
* @param flowEntry the Flow Entry to install.
* @return the added Flow Entry object on success, otherwise null.
*/
static IFlowEntry addFlowEntry(GraphDBOperation dbHandler,
IFlowPath flowObj,
FlowEntry flowEntry) {
// Flow edges
// HeadFE (TODO)
IFlowEntry flowEntryObj = null;
boolean found = false;
try {
if ((flowEntryObj =
dbHandler.searchFlowEntry(flowEntry.flowEntryId())) != null) {
found = true;
} else {
flowEntryObj = dbHandler.newFlowEntry();
}
} catch (Exception e) {
log.error(":addFlow FlowEntryId:{} failed",
flowEntry.flowEntryId().toString());
return null;
}
if (flowEntryObj == null) {
log.error(":addFlow FlowEntryId:{} failed: FlowEntry object not created",
flowEntry.flowEntryId().toString());
return null;
}
//
// Set the Flow Entry key:
// - flowEntry.flowEntryId()
//
flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString());
flowEntryObj.setType("flow_entry");
//
// Set the Flow Entry Edges and attributes:
// - Switch edge
// - InPort edge
// - OutPort edge
//
// - flowEntry.idleTimeout()
// - flowEntry.hardTimeout()
// - flowEntry.dpid()
// - flowEntry.flowEntryUserState()
// - flowEntry.flowEntrySwitchState()
// - flowEntry.flowEntryErrorState()
// - flowEntry.matchInPort()
// - flowEntry.matchSrcMac()
// - flowEntry.matchDstMac()
// - flowEntry.matchEthernetFrameType()
// - flowEntry.matchVlanId()
// - flowEntry.matchVlanPriority()
// - flowEntry.matchSrcIPv4Net()
// - flowEntry.matchDstIPv4Net()
// - flowEntry.matchIpProto()
// - flowEntry.matchIpToS()
// - flowEntry.matchSrcTcpUdpPort()
// - flowEntry.matchDstTcpUdpPort()
// - flowEntry.actionOutputPort()
// - flowEntry.actions()
//
ISwitchObject sw = dbHandler.searchSwitch(flowEntry.dpid().toString());
flowEntryObj.setIdleTimeout(flowEntry.idleTimeout());
flowEntryObj.setHardTimeout(flowEntry.hardTimeout());
flowEntryObj.setSwitchDpid(flowEntry.dpid().toString());
flowEntryObj.setSwitch(sw);
if (flowEntry.flowEntryMatch().matchInPort()) {
IPortObject inport =
dbHandler.searchPort(flowEntry.dpid().toString(),
flowEntry.flowEntryMatch().inPort().value());
flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value());
flowEntryObj.setInPort(inport);
}
if (flowEntry.flowEntryMatch().matchSrcMac()) {
flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString());
}
if (flowEntry.flowEntryMatch().matchDstMac()) {
flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString());
}
if (flowEntry.flowEntryMatch().matchEthernetFrameType()) {
flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType());
}
if (flowEntry.flowEntryMatch().matchVlanId()) {
flowEntryObj.setMatchVlanId(flowEntry.flowEntryMatch().vlanId());
}
if (flowEntry.flowEntryMatch().matchVlanPriority()) {
flowEntryObj.setMatchVlanPriority(flowEntry.flowEntryMatch().vlanPriority());
}
if (flowEntry.flowEntryMatch().matchSrcIPv4Net()) {
flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString());
}
if (flowEntry.flowEntryMatch().matchDstIPv4Net()) {
flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString());
}
if (flowEntry.flowEntryMatch().matchIpProto()) {
flowEntryObj.setMatchIpProto(flowEntry.flowEntryMatch().ipProto());
}
if (flowEntry.flowEntryMatch().matchIpToS()) {
flowEntryObj.setMatchIpToS(flowEntry.flowEntryMatch().ipToS());
}
if (flowEntry.flowEntryMatch().matchSrcTcpUdpPort()) {
flowEntryObj.setMatchSrcTcpUdpPort(flowEntry.flowEntryMatch().srcTcpUdpPort());
}
if (flowEntry.flowEntryMatch().matchDstTcpUdpPort()) {
flowEntryObj.setMatchDstTcpUdpPort(flowEntry.flowEntryMatch().dstTcpUdpPort());
}
for (FlowEntryAction fa : flowEntry.flowEntryActions().actions()) {
if (fa.actionOutput() != null) {
IPortObject outport =
dbHandler.searchPort(flowEntry.dpid().toString(),
fa.actionOutput().port().value());
flowEntryObj.setActionOutputPort(fa.actionOutput().port().value());
flowEntryObj.setOutPort(outport);
}
}
if (! flowEntry.flowEntryActions().isEmpty()) {
flowEntryObj.setActions(flowEntry.flowEntryActions().toString());
}
// TODO: Hacks with hard-coded state names!
if (found)
flowEntryObj.setUserState("FE_USER_MODIFY");
else
flowEntryObj.setUserState("FE_USER_ADD");
flowEntryObj.setSwitchState(flowEntry.flowEntrySwitchState().toString());
//
// TODO: Take care of the FlowEntryErrorState.
//
// Flow Entries edges:
// Flow
// NextFE (TODO)
if (! found) {
flowObj.addFlowEntry(flowEntryObj);
flowEntryObj.setFlow(flowObj);
}
return flowEntryObj;
}
/**
* Delete a flow entry from the Network MAP.
*
* @param dbHandler the Graph Database handler to use.
* @param flowObj the corresponding Flow Path object for the Flow Entry.
* @param flowEntry the Flow Entry to delete.
* @return true on success, otherwise false.
*/
static boolean deleteFlowEntry(GraphDBOperation dbHandler,
IFlowPath flowObj,
FlowEntry flowEntry) {
IFlowEntry flowEntryObj = null;
try {
flowEntryObj = dbHandler.searchFlowEntry(flowEntry.flowEntryId());
} catch (Exception e) {
log.error(":deleteFlowEntry FlowEntryId:{} failed",
flowEntry.flowEntryId().toString());
return false;
}
//
// TODO: Don't print an error for now, because multiple controller
// instances might be deleting the same flow entry.
//
/*
if (flowEntryObj == null) {
log.error(":deleteFlowEntry FlowEntryId:{} failed: FlowEntry object not found",
flowEntry.flowEntryId().toString());
return false;
}
*/
if (flowEntryObj == null)
return true;
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
return true;
}
/**
* Delete all previously added flows.
*
* @param dbHandler the Graph Database handler to use.
* @return true on success, otherwise false.
*/
static boolean deleteAllFlows(GraphDBOperation dbHandler) {
List<FlowId> allFlowIds = new LinkedList<FlowId>();
// Get all Flow IDs
Iterable<IFlowPath> allFlowPaths = dbHandler.getAllFlowPaths();
for (IFlowPath flowPathObj : allFlowPaths) {
if (flowPathObj == null)
continue;
String flowIdStr = flowPathObj.getFlowId();
if (flowIdStr == null)
continue;
FlowId flowId = new FlowId(flowIdStr);
allFlowIds.add(flowId);
}
// Delete all flows one-by-one
for (FlowId flowId : allFlowIds) {
deleteFlow(dbHandler, flowId);
}
return true;
}
/**
* Delete a previously added flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowId the Flow ID of the flow to delete.
* @return true on success, otherwise false.
*/
static boolean deleteFlow(GraphDBOperation dbHandler, FlowId flowId) {
IFlowPath flowObj = null;
try {
flowObj = dbHandler.searchFlowPath(flowId);
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":deleteFlow FlowId:{} failed", flowId.toString());
return false;
}
if (flowObj == null) {
dbHandler.commit();
return true; // OK: No such flow
}
//
// Remove all Flow Entries
//
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
for (IFlowEntry flowEntryObj : flowEntries) {
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
}
// Remove the Flow itself
dbHandler.removeFlowPath(flowObj);
dbHandler.commit();
return true;
}
/**
* Get a previously added flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowId the Flow ID of the flow to get.
* @return the Flow Path if found, otherwise null.
*/
static FlowPath getFlow(GraphDBOperation dbHandler, FlowId flowId) {
IFlowPath flowObj = null;
try {
flowObj = dbHandler.searchFlowPath(flowId);
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":getFlow FlowId:{} failed", flowId.toString());
return null;
}
if (flowObj == null) {
dbHandler.commit();
return null; // Flow not found
}
//
// Extract the Flow state
//
FlowPath flowPath = extractFlowPath(flowObj);
dbHandler.commit();
return flowPath;
}
/**
* Get all installed flows by all installers.
*
* @param dbHandler the Graph Database handler to use.
* @return the Flow Paths if found, otherwise null.
*/
static ArrayList<FlowPath> getAllFlows(GraphDBOperation dbHandler) {
Iterable<IFlowPath> flowPathsObj = null;
ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
try {
flowPathsObj = dbHandler.getAllFlowPaths();
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":getAllFlowPaths failed");
return flowPaths;
}
if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
dbHandler.commit();
return flowPaths; // No Flows found
}
for (IFlowPath flowObj : flowPathsObj) {
//
// Extract the Flow state
//
FlowPath flowPath = extractFlowPath(flowObj);
if (flowPath != null)
flowPaths.add(flowPath);
}
dbHandler.commit();
return flowPaths;
}
/**
* Extract Flow Path State from a Titan Database Object @ref IFlowPath.
*
* @param flowObj the object to extract the Flow Path State from.
* @return the extracted Flow Path State.
*/
private static FlowPath extractFlowPath(IFlowPath flowObj) {
//
// Extract the Flow state
//
String flowIdStr = flowObj.getFlowId();
String installerIdStr = flowObj.getInstallerId();
String flowPathType = flowObj.getFlowPathType();
String flowPathUserState = flowObj.getFlowPathUserState();
Long flowPathFlags = flowObj.getFlowPathFlags();
Integer idleTimeout = flowObj.getIdleTimeout();
Integer hardTimeout = flowObj.getHardTimeout();
String srcSwitchStr = flowObj.getSrcSwitch();
Short srcPortShort = flowObj.getSrcPort();
String dstSwitchStr = flowObj.getDstSwitch();
Short dstPortShort = flowObj.getDstPort();
if ((flowIdStr == null) ||
(installerIdStr == null) ||
(flowPathType == null) ||
(flowPathUserState == null) ||
(flowPathFlags == null) ||
(idleTimeout == null) ||
(hardTimeout == null) ||
(srcSwitchStr == null) ||
(srcPortShort == null) ||
(dstSwitchStr == null) ||
(dstPortShort == null)) {
// TODO: A work-around, becauuse of some bogus database objects
return null;
}
FlowPath flowPath = new FlowPath();
flowPath.setFlowId(new FlowId(flowIdStr));
flowPath.setInstallerId(new CallerId(installerIdStr));
flowPath.setFlowPathType(FlowPathType.valueOf(flowPathType));
flowPath.setFlowPathUserState(FlowPathUserState.valueOf(flowPathUserState));
flowPath.setFlowPathFlags(new FlowPathFlags(flowPathFlags));
flowPath.setIdleTimeout(idleTimeout);
flowPath.setHardTimeout(hardTimeout);
flowPath.dataPath().srcPort().setDpid(new Dpid(srcSwitchStr));
flowPath.dataPath().srcPort().setPort(new Port(srcPortShort));
flowPath.dataPath().dstPort().setDpid(new Dpid(dstSwitchStr));
flowPath.dataPath().dstPort().setPort(new Port(dstPortShort));
//
// Extract the match conditions common for all Flow Entries
//
{
FlowEntryMatch match = new FlowEntryMatch();
String matchSrcMac = flowObj.getMatchSrcMac();
if (matchSrcMac != null)
match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
String matchDstMac = flowObj.getMatchDstMac();
if (matchDstMac != null)
match.enableDstMac(MACAddress.valueOf(matchDstMac));
Short matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
if (matchEthernetFrameType != null)
match.enableEthernetFrameType(matchEthernetFrameType);
Short matchVlanId = flowObj.getMatchVlanId();
if (matchVlanId != null)
match.enableVlanId(matchVlanId);
Byte matchVlanPriority = flowObj.getMatchVlanPriority();
if (matchVlanPriority != null)
match.enableVlanPriority(matchVlanPriority);
String matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
if (matchSrcIPv4Net != null)
match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
String matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
if (matchDstIPv4Net != null)
match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
Byte matchIpProto = flowObj.getMatchIpProto();
if (matchIpProto != null)
match.enableIpProto(matchIpProto);
Byte matchIpToS = flowObj.getMatchIpToS();
if (matchIpToS != null)
match.enableIpToS(matchIpToS);
Short matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
if (matchSrcTcpUdpPort != null)
match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
Short matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
if (matchDstTcpUdpPort != null)
match.enableDstTcpUdpPort(matchDstTcpUdpPort);
flowPath.setFlowEntryMatch(match);
}
//
// Extract the actions for the first Flow Entry
//
{
String actionsStr = flowObj.getActions();
if (actionsStr != null) {
FlowEntryActions flowEntryActions = new FlowEntryActions(actionsStr);
flowPath.setFlowEntryActions(flowEntryActions);
}
}
//
// Extract all Flow Entries
//
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
for (IFlowEntry flowEntryObj : flowEntries) {
FlowEntry flowEntry = extractFlowEntry(flowEntryObj);
if (flowEntry == null)
continue;
flowPath.dataPath().flowEntries().add(flowEntry);
}
return flowPath;
}
/**
* Extract Flow Entry State from a Titan Database Object @ref IFlowEntry.
*
* @param flowEntryObj the object to extract the Flow Entry State from.
* @return the extracted Flow Entry State.
*/
public static FlowEntry extractFlowEntry(IFlowEntry flowEntryObj) {
IFlowPath flowObj = flowEntryObj.getFlow();
if (flowObj == null)
return null;
String flowIdStr = flowObj.getFlowId();
//
String flowEntryIdStr = flowEntryObj.getFlowEntryId();
Integer idleTimeout = flowEntryObj.getIdleTimeout();
Integer hardTimeout = flowEntryObj.getHardTimeout();
String switchDpidStr = flowEntryObj.getSwitchDpid();
String userState = flowEntryObj.getUserState();
String switchState = flowEntryObj.getSwitchState();
if ((flowIdStr == null) ||
(flowEntryIdStr == null) ||
(idleTimeout == null) ||
(hardTimeout == null) ||
(switchDpidStr == null) ||
(userState == null) ||
(switchState == null)) {
// TODO: A work-around, because of some bogus database objects
return null;
}
FlowEntry flowEntry = new FlowEntry();
flowEntry.setFlowEntryId(new FlowEntryId(flowEntryIdStr));
flowEntry.setFlowId(new FlowId(flowIdStr));
flowEntry.setDpid(new Dpid(switchDpidStr));
flowEntry.setIdleTimeout(idleTimeout);
flowEntry.setHardTimeout(hardTimeout);
//
// Extract the match conditions
//
FlowEntryMatch match = new FlowEntryMatch();
Short matchInPort = flowEntryObj.getMatchInPort();
if (matchInPort != null)
match.enableInPort(new Port(matchInPort));
String matchSrcMac = flowEntryObj.getMatchSrcMac();
if (matchSrcMac != null)
match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
String matchDstMac = flowEntryObj.getMatchDstMac();
if (matchDstMac != null)
match.enableDstMac(MACAddress.valueOf(matchDstMac));
Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
if (matchEthernetFrameType != null)
match.enableEthernetFrameType(matchEthernetFrameType);
Short matchVlanId = flowEntryObj.getMatchVlanId();
if (matchVlanId != null)
match.enableVlanId(matchVlanId);
Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
if (matchVlanPriority != null)
match.enableVlanPriority(matchVlanPriority);
String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
if (matchSrcIPv4Net != null)
match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
if (matchDstIPv4Net != null)
match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
Byte matchIpProto = flowEntryObj.getMatchIpProto();
if (matchIpProto != null)
match.enableIpProto(matchIpProto);
Byte matchIpToS = flowEntryObj.getMatchIpToS();
if (matchIpToS != null)
match.enableIpToS(matchIpToS);
Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
if (matchSrcTcpUdpPort != null)
match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
if (matchDstTcpUdpPort != null)
match.enableDstTcpUdpPort(matchDstTcpUdpPort);
flowEntry.setFlowEntryMatch(match);
//
// Extract the actions
//
FlowEntryActions actions = new FlowEntryActions();
String actionsStr = flowEntryObj.getActions();
if (actionsStr != null)
actions = new FlowEntryActions(actionsStr);
flowEntry.setFlowEntryActions(actions);
flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
//
// TODO: Take care of FlowEntryErrorState.
//
return flowEntry;
}
}
| src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java | package net.onrc.onos.ofcontroller.flowmanager;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import net.floodlightcontroller.util.MACAddress;
import net.onrc.onos.graph.GraphDBOperation;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IFlowPath;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.IPortObject;
import net.onrc.onos.ofcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.onrc.onos.ofcontroller.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for performing Flow-related operations on the Database.
*/
public class FlowDatabaseOperation {
private final static Logger log = LoggerFactory.getLogger(FlowDatabaseOperation.class);
/**
* Add a flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowPath the Flow Path to install.
* @return true on success, otherwise false.
*/
static boolean addFlow(GraphDBOperation dbHandler, FlowPath flowPath) {
IFlowPath flowObj = null;
boolean found = false;
try {
if ((flowObj = dbHandler.searchFlowPath(flowPath.flowId())) != null) {
found = true;
} else {
flowObj = dbHandler.newFlowPath();
}
} catch (Exception e) {
dbHandler.rollback();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
log.error(":addFlow FlowId:{} failed: {}",
flowPath.flowId().toString(),
stacktrace);
return false;
}
if (flowObj == null) {
log.error(":addFlow FlowId:{} failed: Flow object not created",
flowPath.flowId().toString());
dbHandler.rollback();
return false;
}
//
// Remove the old Flow Entries
//
if (found) {
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
LinkedList<IFlowEntry> deleteFlowEntries =
new LinkedList<IFlowEntry>();
for (IFlowEntry flowEntryObj : flowEntries)
deleteFlowEntries.add(flowEntryObj);
for (IFlowEntry flowEntryObj : deleteFlowEntries) {
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
}
}
//
// Set the Flow key:
// - flowId
//
flowObj.setFlowId(flowPath.flowId().toString());
flowObj.setType("flow");
//
// Set the Flow attributes:
// - flowPath.installerId()
// - flowPath.flowPathType()
// - flowPath.flowPathUserState()
// - flowPath.flowPathFlags()
// - flowPath.idleTimeout()
// - flowPath.hardTimeout()
// - flowPath.dataPath().srcPort()
// - flowPath.dataPath().dstPort()
// - flowPath.matchSrcMac()
// - flowPath.matchDstMac()
// - flowPath.matchEthernetFrameType()
// - flowPath.matchVlanId()
// - flowPath.matchVlanPriority()
// - flowPath.matchSrcIPv4Net()
// - flowPath.matchDstIPv4Net()
// - flowPath.matchIpProto()
// - flowPath.matchIpToS()
// - flowPath.matchSrcTcpUdpPort()
// - flowPath.matchDstTcpUdpPort()
// - flowPath.flowEntryActions()
//
flowObj.setInstallerId(flowPath.installerId().toString());
flowObj.setFlowPathType(flowPath.flowPathType().toString());
flowObj.setFlowPathUserState(flowPath.flowPathUserState().toString());
flowObj.setFlowPathFlags(flowPath.flowPathFlags().flags());
flowObj.setIdleTimeout(flowPath.idleTimeout());
flowObj.setHardTimeout(flowPath.hardTimeout());
flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString());
flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value());
flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString());
flowObj.setDstPort(flowPath.dataPath().dstPort().port().value());
if (flowPath.flowEntryMatch().matchSrcMac()) {
flowObj.setMatchSrcMac(flowPath.flowEntryMatch().srcMac().toString());
}
if (flowPath.flowEntryMatch().matchDstMac()) {
flowObj.setMatchDstMac(flowPath.flowEntryMatch().dstMac().toString());
}
if (flowPath.flowEntryMatch().matchEthernetFrameType()) {
flowObj.setMatchEthernetFrameType(flowPath.flowEntryMatch().ethernetFrameType());
}
if (flowPath.flowEntryMatch().matchVlanId()) {
flowObj.setMatchVlanId(flowPath.flowEntryMatch().vlanId());
}
if (flowPath.flowEntryMatch().matchVlanPriority()) {
flowObj.setMatchVlanPriority(flowPath.flowEntryMatch().vlanPriority());
}
if (flowPath.flowEntryMatch().matchSrcIPv4Net()) {
flowObj.setMatchSrcIPv4Net(flowPath.flowEntryMatch().srcIPv4Net().toString());
}
if (flowPath.flowEntryMatch().matchDstIPv4Net()) {
flowObj.setMatchDstIPv4Net(flowPath.flowEntryMatch().dstIPv4Net().toString());
}
if (flowPath.flowEntryMatch().matchIpProto()) {
flowObj.setMatchIpProto(flowPath.flowEntryMatch().ipProto());
}
if (flowPath.flowEntryMatch().matchIpToS()) {
flowObj.setMatchIpToS(flowPath.flowEntryMatch().ipToS());
}
if (flowPath.flowEntryMatch().matchSrcTcpUdpPort()) {
flowObj.setMatchSrcTcpUdpPort(flowPath.flowEntryMatch().srcTcpUdpPort());
}
if (flowPath.flowEntryMatch().matchDstTcpUdpPort()) {
flowObj.setMatchDstTcpUdpPort(flowPath.flowEntryMatch().dstTcpUdpPort());
}
if (! flowPath.flowEntryActions().actions().isEmpty()) {
flowObj.setActions(flowPath.flowEntryActions().toString());
}
flowObj.setDataPathSummary(flowPath.dataPath().dataPathSummary());
if (found)
flowObj.setFlowPathUserState("FP_USER_MODIFY");
else
flowObj.setFlowPathUserState("FP_USER_ADD");
// Flow edges:
// HeadFE
//
// Flow Entries:
// flowPath.dataPath().flowEntries()
//
for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
if (flowEntry.flowEntryUserState() == FlowEntryUserState.FE_USER_DELETE)
continue; // Skip: all Flow Entries were deleted earlier
if (addFlowEntry(dbHandler, flowObj, flowEntry) == null) {
dbHandler.rollback();
return false;
}
}
dbHandler.commit();
return true;
}
/**
* Add a flow entry to the Network MAP.
*
* @param dbHandler the Graph Database handler to use.
* @param flowObj the corresponding Flow Path object for the Flow Entry.
* @param flowEntry the Flow Entry to install.
* @return the added Flow Entry object on success, otherwise null.
*/
static IFlowEntry addFlowEntry(GraphDBOperation dbHandler,
IFlowPath flowObj,
FlowEntry flowEntry) {
// Flow edges
// HeadFE (TODO)
IFlowEntry flowEntryObj = null;
boolean found = false;
try {
if ((flowEntryObj =
dbHandler.searchFlowEntry(flowEntry.flowEntryId())) != null) {
found = true;
} else {
flowEntryObj = dbHandler.newFlowEntry();
}
} catch (Exception e) {
log.error(":addFlow FlowEntryId:{} failed",
flowEntry.flowEntryId().toString());
return null;
}
if (flowEntryObj == null) {
log.error(":addFlow FlowEntryId:{} failed: FlowEntry object not created",
flowEntry.flowEntryId().toString());
return null;
}
//
// Set the Flow Entry key:
// - flowEntry.flowEntryId()
//
flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString());
flowEntryObj.setType("flow_entry");
//
// Set the Flow Entry Edges and attributes:
// - Switch edge
// - InPort edge
// - OutPort edge
//
// - flowEntry.idleTimeout()
// - flowEntry.hardTimeout()
// - flowEntry.dpid()
// - flowEntry.flowEntryUserState()
// - flowEntry.flowEntrySwitchState()
// - flowEntry.flowEntryErrorState()
// - flowEntry.matchInPort()
// - flowEntry.matchSrcMac()
// - flowEntry.matchDstMac()
// - flowEntry.matchEthernetFrameType()
// - flowEntry.matchVlanId()
// - flowEntry.matchVlanPriority()
// - flowEntry.matchSrcIPv4Net()
// - flowEntry.matchDstIPv4Net()
// - flowEntry.matchIpProto()
// - flowEntry.matchIpToS()
// - flowEntry.matchSrcTcpUdpPort()
// - flowEntry.matchDstTcpUdpPort()
// - flowEntry.actionOutputPort()
// - flowEntry.actions()
//
ISwitchObject sw = dbHandler.searchSwitch(flowEntry.dpid().toString());
flowEntryObj.setIdleTimeout(flowEntry.idleTimeout());
flowEntryObj.setHardTimeout(flowEntry.hardTimeout());
flowEntryObj.setSwitchDpid(flowEntry.dpid().toString());
flowEntryObj.setSwitch(sw);
if (flowEntry.flowEntryMatch().matchInPort()) {
IPortObject inport =
dbHandler.searchPort(flowEntry.dpid().toString(),
flowEntry.flowEntryMatch().inPort().value());
flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value());
flowEntryObj.setInPort(inport);
}
if (flowEntry.flowEntryMatch().matchSrcMac()) {
flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString());
}
if (flowEntry.flowEntryMatch().matchDstMac()) {
flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString());
}
if (flowEntry.flowEntryMatch().matchEthernetFrameType()) {
flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType());
}
if (flowEntry.flowEntryMatch().matchVlanId()) {
flowEntryObj.setMatchVlanId(flowEntry.flowEntryMatch().vlanId());
}
if (flowEntry.flowEntryMatch().matchVlanPriority()) {
flowEntryObj.setMatchVlanPriority(flowEntry.flowEntryMatch().vlanPriority());
}
if (flowEntry.flowEntryMatch().matchSrcIPv4Net()) {
flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString());
}
if (flowEntry.flowEntryMatch().matchDstIPv4Net()) {
flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString());
}
if (flowEntry.flowEntryMatch().matchIpProto()) {
flowEntryObj.setMatchIpProto(flowEntry.flowEntryMatch().ipProto());
}
if (flowEntry.flowEntryMatch().matchIpToS()) {
flowEntryObj.setMatchIpToS(flowEntry.flowEntryMatch().ipToS());
}
if (flowEntry.flowEntryMatch().matchSrcTcpUdpPort()) {
flowEntryObj.setMatchSrcTcpUdpPort(flowEntry.flowEntryMatch().srcTcpUdpPort());
}
if (flowEntry.flowEntryMatch().matchDstTcpUdpPort()) {
flowEntryObj.setMatchDstTcpUdpPort(flowEntry.flowEntryMatch().dstTcpUdpPort());
}
for (FlowEntryAction fa : flowEntry.flowEntryActions().actions()) {
if (fa.actionOutput() != null) {
IPortObject outport =
dbHandler.searchPort(flowEntry.dpid().toString(),
fa.actionOutput().port().value());
flowEntryObj.setActionOutputPort(fa.actionOutput().port().value());
flowEntryObj.setOutPort(outport);
}
}
if (! flowEntry.flowEntryActions().isEmpty()) {
flowEntryObj.setActions(flowEntry.flowEntryActions().toString());
}
// TODO: Hacks with hard-coded state names!
if (found)
flowEntryObj.setUserState("FE_USER_MODIFY");
else
flowEntryObj.setUserState("FE_USER_ADD");
flowEntryObj.setSwitchState(flowEntry.flowEntrySwitchState().toString());
//
// TODO: Take care of the FlowEntryErrorState.
//
// Flow Entries edges:
// Flow
// NextFE (TODO)
if (! found) {
flowObj.addFlowEntry(flowEntryObj);
flowEntryObj.setFlow(flowObj);
}
return flowEntryObj;
}
/**
* Delete a flow entry from the Network MAP.
*
* @param dbHandler the Graph Database handler to use.
* @param flowObj the corresponding Flow Path object for the Flow Entry.
* @param flowEntry the Flow Entry to delete.
* @return true on success, otherwise false.
*/
static boolean deleteFlowEntry(GraphDBOperation dbHandler,
IFlowPath flowObj,
FlowEntry flowEntry) {
IFlowEntry flowEntryObj = null;
try {
flowEntryObj = dbHandler.searchFlowEntry(flowEntry.flowEntryId());
} catch (Exception e) {
log.error(":deleteFlowEntry FlowEntryId:{} failed",
flowEntry.flowEntryId().toString());
return false;
}
//
// TODO: Don't print an error for now, because multiple controller
// instances might be deleting the same flow entry.
//
/*
if (flowEntryObj == null) {
log.error(":deleteFlowEntry FlowEntryId:{} failed: FlowEntry object not found",
flowEntry.flowEntryId().toString());
return false;
}
*/
if (flowEntryObj == null)
return true;
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
return true;
}
/**
* Delete all previously added flows.
*
* @param dbHandler the Graph Database handler to use.
* @return true on success, otherwise false.
*/
static boolean deleteAllFlows(GraphDBOperation dbHandler) {
List<FlowId> allFlowIds = new LinkedList<FlowId>();
// Get all Flow IDs
Iterable<IFlowPath> allFlowPaths = dbHandler.getAllFlowPaths();
for (IFlowPath flowPathObj : allFlowPaths) {
if (flowPathObj == null)
continue;
String flowIdStr = flowPathObj.getFlowId();
if (flowIdStr == null)
continue;
FlowId flowId = new FlowId(flowIdStr);
allFlowIds.add(flowId);
}
// Delete all flows one-by-one
for (FlowId flowId : allFlowIds) {
deleteFlow(dbHandler, flowId);
}
return true;
}
/**
* Delete a previously added flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowId the Flow ID of the flow to delete.
* @return true on success, otherwise false.
*/
static boolean deleteFlow(GraphDBOperation dbHandler, FlowId flowId) {
IFlowPath flowObj = null;
try {
flowObj = dbHandler.searchFlowPath(flowId);
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":deleteFlow FlowId:{} failed", flowId.toString());
return false;
}
if (flowObj == null) {
dbHandler.commit();
return true; // OK: No such flow
}
//
// Remove all Flow Entries
//
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
for (IFlowEntry flowEntryObj : flowEntries) {
flowObj.removeFlowEntry(flowEntryObj);
dbHandler.removeFlowEntry(flowEntryObj);
}
// Remove the Flow itself
dbHandler.removeFlowPath(flowObj);
dbHandler.commit();
return true;
}
/**
* Get a previously added flow.
*
* @param dbHandler the Graph Database handler to use.
* @param flowId the Flow ID of the flow to get.
* @return the Flow Path if found, otherwise null.
*/
static FlowPath getFlow(GraphDBOperation dbHandler, FlowId flowId) {
IFlowPath flowObj = null;
try {
flowObj = dbHandler.searchFlowPath(flowId);
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":getFlow FlowId:{} failed", flowId.toString());
return null;
}
if (flowObj == null) {
dbHandler.commit();
return null; // Flow not found
}
//
// Extract the Flow state
//
FlowPath flowPath = extractFlowPath(flowObj);
dbHandler.commit();
return flowPath;
}
/**
* Get all installed flows by all installers.
*
* @param dbHandler the Graph Database handler to use.
* @return the Flow Paths if found, otherwise null.
*/
static ArrayList<FlowPath> getAllFlows(GraphDBOperation dbHandler) {
Iterable<IFlowPath> flowPathsObj = null;
ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
try {
flowPathsObj = dbHandler.getAllFlowPaths();
} catch (Exception e) {
// TODO: handle exceptions
dbHandler.rollback();
log.error(":getAllFlowPaths failed");
return flowPaths;
}
if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) {
dbHandler.commit();
return flowPaths; // No Flows found
}
for (IFlowPath flowObj : flowPathsObj) {
//
// Extract the Flow state
//
FlowPath flowPath = extractFlowPath(flowObj);
if (flowPath != null)
flowPaths.add(flowPath);
}
dbHandler.commit();
return flowPaths;
}
/**
* Extract Flow Path State from a Titan Database Object @ref IFlowPath.
*
* @param flowObj the object to extract the Flow Path State from.
* @return the extracted Flow Path State.
*/
private static FlowPath extractFlowPath(IFlowPath flowObj) {
//
// Extract the Flow state
//
String flowIdStr = flowObj.getFlowId();
String installerIdStr = flowObj.getInstallerId();
String flowPathType = flowObj.getFlowPathType();
String flowPathUserState = flowObj.getFlowPathUserState();
Long flowPathFlags = flowObj.getFlowPathFlags();
Integer idleTimeout = flowObj.getIdleTimeout();
Integer hardTimeout = flowObj.getHardTimeout();
String srcSwitchStr = flowObj.getSrcSwitch();
Short srcPortShort = flowObj.getSrcPort();
String dstSwitchStr = flowObj.getDstSwitch();
Short dstPortShort = flowObj.getDstPort();
if ((flowIdStr == null) ||
(installerIdStr == null) ||
(flowPathType == null) ||
(flowPathUserState == null) ||
(flowPathFlags == null) ||
(idleTimeout == null) ||
(hardTimeout == null) ||
(srcSwitchStr == null) ||
(srcPortShort == null) ||
(dstSwitchStr == null) ||
(dstPortShort == null)) {
// TODO: A work-around, becauuse of some bogus database objects
return null;
}
FlowPath flowPath = new FlowPath();
flowPath.setFlowId(new FlowId(flowIdStr));
flowPath.setInstallerId(new CallerId(installerIdStr));
flowPath.setFlowPathType(FlowPathType.valueOf(flowPathType));
flowPath.setFlowPathUserState(FlowPathUserState.valueOf(flowPathUserState));
flowPath.setFlowPathFlags(new FlowPathFlags(flowPathFlags));
flowPath.setIdleTimeout(idleTimeout);
flowPath.setHardTimeout(hardTimeout);
flowPath.dataPath().srcPort().setDpid(new Dpid(srcSwitchStr));
flowPath.dataPath().srcPort().setPort(new Port(srcPortShort));
flowPath.dataPath().dstPort().setDpid(new Dpid(dstSwitchStr));
flowPath.dataPath().dstPort().setPort(new Port(dstPortShort));
//
// Extract the match conditions common for all Flow Entries
//
{
FlowEntryMatch match = new FlowEntryMatch();
String matchSrcMac = flowObj.getMatchSrcMac();
if (matchSrcMac != null)
match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
String matchDstMac = flowObj.getMatchDstMac();
if (matchDstMac != null)
match.enableDstMac(MACAddress.valueOf(matchDstMac));
Short matchEthernetFrameType = flowObj.getMatchEthernetFrameType();
if (matchEthernetFrameType != null)
match.enableEthernetFrameType(matchEthernetFrameType);
Short matchVlanId = flowObj.getMatchVlanId();
if (matchVlanId != null)
match.enableVlanId(matchVlanId);
Byte matchVlanPriority = flowObj.getMatchVlanPriority();
if (matchVlanPriority != null)
match.enableVlanPriority(matchVlanPriority);
String matchSrcIPv4Net = flowObj.getMatchSrcIPv4Net();
if (matchSrcIPv4Net != null)
match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
String matchDstIPv4Net = flowObj.getMatchDstIPv4Net();
if (matchDstIPv4Net != null)
match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
Byte matchIpProto = flowObj.getMatchIpProto();
if (matchIpProto != null)
match.enableIpProto(matchIpProto);
Byte matchIpToS = flowObj.getMatchIpToS();
if (matchIpToS != null)
match.enableIpToS(matchIpToS);
Short matchSrcTcpUdpPort = flowObj.getMatchSrcTcpUdpPort();
if (matchSrcTcpUdpPort != null)
match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
Short matchDstTcpUdpPort = flowObj.getMatchDstTcpUdpPort();
if (matchDstTcpUdpPort != null)
match.enableDstTcpUdpPort(matchDstTcpUdpPort);
flowPath.setFlowEntryMatch(match);
}
//
// Extract the actions for the first Flow Entry
//
{
String actionsStr = flowObj.getActions();
if (actionsStr != null) {
FlowEntryActions flowEntryActions = new FlowEntryActions(actionsStr);
flowPath.setFlowEntryActions(flowEntryActions);
}
}
//
// Extract all Flow Entries
//
Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
for (IFlowEntry flowEntryObj : flowEntries) {
FlowEntry flowEntry = extractFlowEntry(flowEntryObj);
if (flowEntry == null)
continue;
flowPath.dataPath().flowEntries().add(flowEntry);
}
return flowPath;
}
/**
* Extract Flow Entry State from a Titan Database Object @ref IFlowEntry.
*
* @param flowEntryObj the object to extract the Flow Entry State from.
* @return the extracted Flow Entry State.
*/
public static FlowEntry extractFlowEntry(IFlowEntry flowEntryObj) {
String flowEntryIdStr = flowEntryObj.getFlowEntryId();
Integer idleTimeout = flowEntryObj.getIdleTimeout();
Integer hardTimeout = flowEntryObj.getHardTimeout();
String switchDpidStr = flowEntryObj.getSwitchDpid();
String userState = flowEntryObj.getUserState();
String switchState = flowEntryObj.getSwitchState();
if ((flowEntryIdStr == null) ||
(idleTimeout == null) ||
(hardTimeout == null) ||
(switchDpidStr == null) ||
(userState == null) ||
(switchState == null)) {
// TODO: A work-around, because of some bogus database objects
return null;
}
FlowEntry flowEntry = new FlowEntry();
flowEntry.setFlowEntryId(new FlowEntryId(flowEntryIdStr));
flowEntry.setDpid(new Dpid(switchDpidStr));
flowEntry.setIdleTimeout(idleTimeout);
flowEntry.setHardTimeout(hardTimeout);
//
// Extract the match conditions
//
FlowEntryMatch match = new FlowEntryMatch();
Short matchInPort = flowEntryObj.getMatchInPort();
if (matchInPort != null)
match.enableInPort(new Port(matchInPort));
String matchSrcMac = flowEntryObj.getMatchSrcMac();
if (matchSrcMac != null)
match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
String matchDstMac = flowEntryObj.getMatchDstMac();
if (matchDstMac != null)
match.enableDstMac(MACAddress.valueOf(matchDstMac));
Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
if (matchEthernetFrameType != null)
match.enableEthernetFrameType(matchEthernetFrameType);
Short matchVlanId = flowEntryObj.getMatchVlanId();
if (matchVlanId != null)
match.enableVlanId(matchVlanId);
Byte matchVlanPriority = flowEntryObj.getMatchVlanPriority();
if (matchVlanPriority != null)
match.enableVlanPriority(matchVlanPriority);
String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
if (matchSrcIPv4Net != null)
match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
if (matchDstIPv4Net != null)
match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
Byte matchIpProto = flowEntryObj.getMatchIpProto();
if (matchIpProto != null)
match.enableIpProto(matchIpProto);
Byte matchIpToS = flowEntryObj.getMatchIpToS();
if (matchIpToS != null)
match.enableIpToS(matchIpToS);
Short matchSrcTcpUdpPort = flowEntryObj.getMatchSrcTcpUdpPort();
if (matchSrcTcpUdpPort != null)
match.enableSrcTcpUdpPort(matchSrcTcpUdpPort);
Short matchDstTcpUdpPort = flowEntryObj.getMatchDstTcpUdpPort();
if (matchDstTcpUdpPort != null)
match.enableDstTcpUdpPort(matchDstTcpUdpPort);
flowEntry.setFlowEntryMatch(match);
//
// Extract the actions
//
FlowEntryActions actions = new FlowEntryActions();
String actionsStr = flowEntryObj.getActions();
if (actionsStr != null)
actions = new FlowEntryActions(actionsStr);
flowEntry.setFlowEntryActions(actions);
flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
//
// TODO: Take care of FlowEntryErrorState.
//
return flowEntry;
}
}
| Fix a bug inside FlowDatabaseOperation.extractFlowEntry()
Explicitly assign the FlowId to the extracted FlowEntry.
| src/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java | Fix a bug inside FlowDatabaseOperation.extractFlowEntry() Explicitly assign the FlowId to the extracted FlowEntry. | <ide><path>rc/main/java/net/onrc/onos/ofcontroller/flowmanager/FlowDatabaseOperation.java
<ide> * @return the extracted Flow Entry State.
<ide> */
<ide> public static FlowEntry extractFlowEntry(IFlowEntry flowEntryObj) {
<add> IFlowPath flowObj = flowEntryObj.getFlow();
<add> if (flowObj == null)
<add> return null;
<add>
<add> String flowIdStr = flowObj.getFlowId();
<add> //
<ide> String flowEntryIdStr = flowEntryObj.getFlowEntryId();
<ide> Integer idleTimeout = flowEntryObj.getIdleTimeout();
<ide> Integer hardTimeout = flowEntryObj.getHardTimeout();
<ide> String userState = flowEntryObj.getUserState();
<ide> String switchState = flowEntryObj.getSwitchState();
<ide>
<del> if ((flowEntryIdStr == null) ||
<add> if ((flowIdStr == null) ||
<add> (flowEntryIdStr == null) ||
<ide> (idleTimeout == null) ||
<ide> (hardTimeout == null) ||
<ide> (switchDpidStr == null) ||
<ide>
<ide> FlowEntry flowEntry = new FlowEntry();
<ide> flowEntry.setFlowEntryId(new FlowEntryId(flowEntryIdStr));
<add> flowEntry.setFlowId(new FlowId(flowIdStr));
<ide> flowEntry.setDpid(new Dpid(switchDpidStr));
<ide> flowEntry.setIdleTimeout(idleTimeout);
<ide> flowEntry.setHardTimeout(hardTimeout); |
|
Java | apache-2.0 | 8f2da0aa4ffbbd2fad79b2c031430f412d41436b | 0 | Apelon-VA/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,Apelon-VA/ISAAC,Apelon-VA/ISAAC,DongwonChoi/ISAAC,vaskaloidis/va-isaac-gui,vaskaloidis/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/ISAAC | /**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gov.va.isaac.workflow.gui;
import gov.va.isaac.AppContext;
import gov.va.isaac.gui.dialog.BusyPopover;
import gov.va.isaac.gui.util.Images;
import gov.va.isaac.interfaces.gui.ApplicationMenus;
import gov.va.isaac.interfaces.gui.MenuItemI;
import gov.va.isaac.interfaces.gui.constants.SharedServiceNames;
import gov.va.isaac.interfaces.gui.views.DockedViewI;
import gov.va.isaac.interfaces.gui.views.IsaacViewWithMenusI;
import gov.va.isaac.util.Utility;
import gov.va.isaac.workflow.engine.RemoteSynchronizer;
import gov.va.isaac.workflow.engine.SynchronizeResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.stage.Window;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link WorkflowInbox}
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
@Service @Named(SharedServiceNames.DOCKED)
@Singleton
public class WorkflowInbox implements DockedViewI, IsaacViewWithMenusI
{
private static final Logger LOG = LoggerFactory.getLogger(WorkflowInbox.class);
WorkflowInboxController controller_;
private final Logger logger = LoggerFactory.getLogger(WorkflowInbox.class);
private WorkflowInbox() throws IOException
{
}
/**
* @see gov.va.isaac.interfaces.gui.views.IsaacViewI#getMenuBarMenus()
*/
@Override
public List<MenuItemI> getMenuBarMenus()
{
ArrayList<MenuItemI> menus = new ArrayList<>();
MenuItemI mi = new MenuItemI()
{
@Override
public void handleMenuSelection(Window parent)
{
final BusyPopover synchronizePopover = BusyPopover.createBusyPopover("Synchronizing workflow...", parent.getScene().getRoot());
Utility.execute(() -> {
try
{
SynchronizeResult sr = AppContext.getService(RemoteSynchronizer.class).blockingSynchronize();
if (sr.hasError())
{
AppContext.getCommonDialogs().showErrorDialog("Error Synchronizing", "There were errors during synchronization", sr.getErrorSummary());
}
}
catch (Exception e)
{
logger.error("Unexpected error synchronizing workflow", e);
}
finally
{
Platform.runLater(() -> { synchronizePopover.hide(); });
}
});
}
@Override
public int getSortOrder()
{
return 15;
}
@Override
public String getParentMenuId()
{
return ApplicationMenus.ACTIONS.getMenuId();
}
@Override
public String getMenuName()
{
return "Synchronize Workflow";
}
@Override
public String getMenuId()
{
return "synchronizeWorkflowMenu";
}
/**
* @see gov.va.isaac.interfaces.gui.MenuItemI#getImage()
*/
@Override
public Image getImage()
{
return Images.SYNC_BLUE.getImage();
}
@Override
public boolean enableMnemonicParsing()
{
return false;
}
};
menus.add(mi);
return menus;
}
/**
* @see gov.va.isaac.interfaces.gui.views.ViewI#getView()
*/
@Override
public Region getView() {
//init had to be delayed, because the current init runs way to slow, and hits the DB in the JavaFX thread.
if (controller_ == null)
{
synchronized (this)
{
if (controller_ == null)
{
try
{
controller_ = WorkflowInboxController.init();
}
catch (IOException e)
{
LOG.error("Unexpected error initializing the Workflow Inbox View", e);
return new Label("oops - check logs");
}
}
}
}
return controller_.getView();
}
/**
* @see gov.va.isaac.interfaces.gui.views.DockedViewI#getMenuBarMenuToShowView()
*/
@Override
public MenuItemI getMenuBarMenuToShowView() {
MenuItemI menuItem = new MenuItemI()
{
@Override
public void handleMenuSelection(Window parent)
{
//noop
}
@Override
public int getSortOrder()
{
return 5;
}
@Override
public String getParentMenuId()
{
return ApplicationMenus.PANELS.getMenuId();
}
@Override
public String getMenuName()
{
return "Workflow Inbox";
}
@Override
public String getMenuId()
{
return "workflowInboxMenuItem";
}
@Override
public boolean enableMnemonicParsing()
{
return false;
}
@Override
public Image getImage()
{
return Images.INBOX.getImage();
}
};
return menuItem;
}
/**
* @see gov.va.isaac.interfaces.gui.views.DockedViewI#getViewTitle()
*/
@Override
public String getViewTitle() {
return "Workflow Inbox";
}
/**
* Inform the view that the data in the datastore has changed, and it should refresh itself.
*/
public void reloadContent()
{
if (controller_ != null)
{
if (Platform.isFxApplicationThread())
{
controller_.loadContent();
}
else
{
Platform.runLater(() -> controller_.loadContent());
}
}
}
} | isaac-workflow/src/main/java/gov/va/isaac/workflow/gui/WorkflowInbox.java | /**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gov.va.isaac.workflow.gui;
import gov.va.isaac.AppContext;
import gov.va.isaac.gui.dialog.BusyPopover;
import gov.va.isaac.gui.util.Images;
import gov.va.isaac.interfaces.gui.ApplicationMenus;
import gov.va.isaac.interfaces.gui.MenuItemI;
import gov.va.isaac.interfaces.gui.constants.SharedServiceNames;
import gov.va.isaac.interfaces.gui.views.DockedViewI;
import gov.va.isaac.interfaces.gui.views.IsaacViewWithMenusI;
import gov.va.isaac.util.Utility;
import gov.va.isaac.workflow.engine.RemoteSynchronizer;
import gov.va.isaac.workflow.engine.SynchronizeResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.stage.Window;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link WorkflowInbox}
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
@Service @Named(SharedServiceNames.DOCKED)
@Singleton
public class WorkflowInbox implements DockedViewI, IsaacViewWithMenusI
{
private static final Logger LOG = LoggerFactory.getLogger(WorkflowInbox.class);
WorkflowInboxController controller_;
private final Logger logger = LoggerFactory.getLogger(WorkflowInbox.class);
private WorkflowInbox() throws IOException
{
}
/**
* @see gov.va.isaac.interfaces.gui.views.IsaacViewI#getMenuBarMenus()
*/
@Override
public List<MenuItemI> getMenuBarMenus()
{
ArrayList<MenuItemI> menus = new ArrayList<>();
MenuItemI mi = new MenuItemI()
{
@Override
public void handleMenuSelection(Window parent)
{
final BusyPopover synchronizePopover = BusyPopover.createBusyPopover("Synchronizing workflow...", parent.getScene().getRoot());
Utility.execute(() -> {
try
{
SynchronizeResult sr = AppContext.getService(RemoteSynchronizer.class).blockingSynchronize();
if (sr.hasError())
{
AppContext.getCommonDialogs().showErrorDialog("Error Synchronizing", "There were errors during synchronization", sr.getErrorSummary());
}
}
catch (Exception e)
{
logger.error("Unexpected error synchronizing workflow", e);
}
finally
{
Platform.runLater(() -> { synchronizePopover.hide(); });
}
});
}
@Override
public int getSortOrder()
{
return 15;
}
@Override
public String getParentMenuId()
{
return ApplicationMenus.ACTIONS.getMenuId();
}
@Override
public String getMenuName()
{
return "Synchronize Workflow";
}
@Override
public String getMenuId()
{
return "synchronizeWorkflowMenu";
}
@Override
public boolean enableMnemonicParsing()
{
return false;
}
};
menus.add(mi);
return menus;
}
/**
* @see gov.va.isaac.interfaces.gui.views.ViewI#getView()
*/
@Override
public Region getView() {
//init had to be delayed, because the current init runs way to slow, and hits the DB in the JavaFX thread.
if (controller_ == null)
{
synchronized (this)
{
if (controller_ == null)
{
try
{
controller_ = WorkflowInboxController.init();
}
catch (IOException e)
{
LOG.error("Unexpected error initializing the Workflow Inbox View", e);
return new Label("oops - check logs");
}
}
}
}
return controller_.getView();
}
/**
* @see gov.va.isaac.interfaces.gui.views.DockedViewI#getMenuBarMenuToShowView()
*/
@Override
public MenuItemI getMenuBarMenuToShowView() {
MenuItemI menuItem = new MenuItemI()
{
@Override
public void handleMenuSelection(Window parent)
{
//noop
}
@Override
public int getSortOrder()
{
return 5;
}
@Override
public String getParentMenuId()
{
return ApplicationMenus.PANELS.getMenuId();
}
@Override
public String getMenuName()
{
return "Workflow Inbox";
}
@Override
public String getMenuId()
{
return "workflowInboxMenuItem";
}
@Override
public boolean enableMnemonicParsing()
{
return false;
}
@Override
public Image getImage()
{
return Images.INBOX.getImage();
}
};
return menuItem;
}
/**
* @see gov.va.isaac.interfaces.gui.views.DockedViewI#getViewTitle()
*/
@Override
public String getViewTitle() {
return "Workflow Inbox";
}
/**
* Inform the view that the data in the datastore has changed, and it should refresh itself.
*/
public void reloadContent()
{
if (controller_ != null)
{
if (Platform.isFxApplicationThread())
{
controller_.loadContent();
}
else
{
Platform.runLater(() -> controller_.loadContent());
}
}
}
} | add sync image | isaac-workflow/src/main/java/gov/va/isaac/workflow/gui/WorkflowInbox.java | add sync image | <ide><path>saac-workflow/src/main/java/gov/va/isaac/workflow/gui/WorkflowInbox.java
<ide> return "synchronizeWorkflowMenu";
<ide> }
<ide>
<add> /**
<add> * @see gov.va.isaac.interfaces.gui.MenuItemI#getImage()
<add> */
<add> @Override
<add> public Image getImage()
<add> {
<add> return Images.SYNC_BLUE.getImage();
<add> }
<add>
<ide> @Override
<ide> public boolean enableMnemonicParsing()
<ide> { |
|
Java | mit | e668c2b9b297ce78d799e735deed78363e5c548e | 0 | TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,Onuzimoyr/dAndroid,Onuzimoyr/dAndroid,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,ssdwa/android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android | /*
HostMediaPlayerProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.host.profile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.deviceconnect.android.deviceplugin.host.BuildConfig;
import org.deviceconnect.android.deviceplugin.host.HostDeviceService;
import org.deviceconnect.android.event.EventError;
import org.deviceconnect.android.event.EventManager;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.MediaPlayerProfile;
import org.deviceconnect.android.provider.FileManager;
import org.deviceconnect.message.DConnectMessage;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
/**
* Media Player Profile.
*
* @author NTT DOCOMO, INC.
*/
public class HostMediaPlayerProfile extends MediaPlayerProfile {
/** Debug Tag. */
private static final String TAG = "HOST";
/** Error. */
private static final int ERROR_VALUE_IS_NULL = 100;
/** ミリ秒 - 秒オーダー変換用. */
private static final int UNIT_SEC = 1000;
/** Sort flag. */
enum SortOrder {
/** Title (asc). */
TITLE_ASC,
/** Title (desc). */
TITLE_DESC,
/** Duration (asc). */
DURATION_ASC,
/** Duration (desc). */
DURATION_DESC,
/** Artist (asc). */
ARTIST_ASC,
/** Artist (desc). */
ARTIST_DESC,
/** Mime (asc). */
MIME_ASC,
/** Mime (desc). */
MIME_DESC,
/** Id (asc). */
ID_ASC,
/** Id (desc). */
ID_DESC,
/** Composer (asc). */
COMPOSER_ASC,
/** Composer (desc). */
COMPOSER_DESC,
/** Language (asc). */
LANGUAGE_ASC,
/** Language (desc). */
LANGUAGE_DESC
};
/**
* AudioのContentProviderのキー一覧を定義する.
*/
private static final String[] AUDIO_TABLE_KEYS = {
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.COMPOSER,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.DATE_ADDED,
MediaStore.Audio.Media.DISPLAY_NAME
};
/**
* VideoのContentProviderのキー一覧を定義する.
*/
private static final String[] VIDEO_TABLE_KEYS = {
MediaStore.Video.Media.ALBUM,
MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media.LANGUAGE,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media._ID,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.DISPLAY_NAME
};
/** Mute Status. */
private static Boolean sIsMute = false;
@Override
protected boolean onPutPlay(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).playMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutStop(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).stopMedia(response);
return false;
}
return true;
}
@Override
protected boolean onPutPause(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).pauseMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutResume(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).resumeMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onGetPlayStatus(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else {
((HostDeviceService) getContext()).getPlayStatus(response);
return false;
}
}
@Override
protected boolean onPutMedia(final Intent request, final Intent response, final String serviceId,
final String mediaId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (TextUtils.isEmpty(mediaId)) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
if (checkInteger(mediaId)) {
((HostDeviceService) getContext()).putMediaId(response, mediaId);
} else {
FileManager mFileManager = new FileManager(this.getContext());
long newMediaId = mediaIdFromPath(this.getContext(), mFileManager.getBasePath() + mediaId);
if (newMediaId == -1) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
((HostDeviceService) getContext()).putMediaId(response, "" + newMediaId);
}
return false;
}
return true;
}
@Override
protected boolean onGetMedia(final Intent request, final Intent response, final String serviceId,
final String mediaId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (TextUtils.isEmpty(mediaId)) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
// Query table parameter.
String[] param = null;
// URI
Uri uriType = null;
// Query filter.
String filter = "_display_name=?";
// Query cursor.
Cursor cursor = null;
// Get media path.
Uri uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));
String fileName = getDisplayNameFromUri(uri);
if (fileName == null) {
uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));
fileName = getDisplayNameFromUri(uri);
if (fileName == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
param = AUDIO_TABLE_KEYS;
uriType = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else {
param = VIDEO_TABLE_KEYS;
uriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
ContentResolver cresolver = getContext()
.getApplicationContext().getContentResolver();
try {
cursor = cresolver.query(uriType, param, filter, new String[] {fileName}, null);
if (cursor.moveToFirst()) {
loadMediaData(uriType, cursor, response);
}
setResult(response, DConnectMessage.RESULT_OK);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
return true;
}
/**
* cursorからMediaDataを読み込みBundleに格納して返却する.
* @param uriType メディアタイプ
* @param cursor データが格納されているCursor
* @param response response.
*/
private void loadMediaData(final Uri uriType, final Cursor cursor, final Intent response) {
String mId = null;
String mType = null;
String mTitle = null;
int mDuration = 0;
String mArtist = null;
String mComp = null;
if (uriType == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) {
mId = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
mType = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));
mTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
mDuration = (cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))) / UNIT_SEC;
mArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
mComp = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.COMPOSER));
setType(response, "Music");
// Make creator
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creator = new Bundle();
setCreator(creator, mArtist);
setRole(creator, "Artist");
dataList.add((Bundle) creator.clone());
setCreator(creator, mComp);
setRole(creator, "Composer");
dataList.add((Bundle) creator.clone());
setCreators(response, dataList.toArray(new Bundle[dataList.size()]));
} else {
mId = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
mType = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE));
mTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
mDuration = (cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))) / UNIT_SEC;
mArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ARTIST));
String mLang = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.LANGUAGE));
setLanguage(response, mLang);
setType(response, "Video");
// Make creator
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creatorVideo = new Bundle();
setCreator(creatorVideo, mArtist);
setRole(creatorVideo, "Artist");
dataList.add((Bundle) creatorVideo.clone());
setCreators(response, dataList.toArray(new Bundle[dataList.size()]));
}
setMediaId(response, mId);
setMIMEType(response, mType);
setTitle(response, mTitle);
setDuration(response, mDuration);
return;
}
/**
* Get display name from URI.
*
* @param mUri URI
* @return name display name.
*/
private String getDisplayNameFromUri(final Uri mUri) {
Cursor c = null;
try {
ContentResolver mContentResolver = getContext()
.getApplicationContext().getContentResolver();
c = mContentResolver.query(mUri, null, null, null, null);
if (c.moveToFirst()) {
int index = c.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
if (index != -1) {
return c.getString(index);
}
}
} finally {
if (c != null) {
c.close();
}
}
return null;
}
@Override
protected boolean onGetMediaList(final Intent request, final Intent response,
final String serviceId, final String query,
final String mimeType, final String[] orders, final Integer offset, final Integer limit) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
Bundle b = request.getExtras();
if (b.getString(PARAM_LIMIT) != null) {
if (parseInteger(b.get(PARAM_LIMIT)) == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
}
if (b.getString(PARAM_OFFSET) != null) {
if (parseInteger(b.get(PARAM_OFFSET)) == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
}
getMediaList(response, query, mimeType, orders, offset, limit);
}
return true;
}
/**
* Get Media List.
* @param response Response
* @param query Query
* @param mimeType MIME Type
* @param orders Order
* @param offset Offset
* @param limit Limit
*/
private void getMediaList(final Intent response, final String query,
final String mimeType, final String[] orders, final Integer offset,
final Integer limit) {
SortOrder mSort = SortOrder.TITLE_ASC;
int counter = 0;
if (limit != null) {
if (limit < 0) {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
}
if (offset != null) {
if (offset < 0) {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
}
// 音楽用のテーブルの項目.
String[] mMusicParam = null;
String[] mVideoParam = null;
// URI
Uri mMusicUriType = null;
Uri mVideoUriType = null;
// 検索用 Filterを作成.
String mVideoFilter = "";
String mMusicFilter = "";
// Orderの処理
String mOrderBy = "";
// 検索用Cursor.
Cursor cursorMusic = null;
Cursor cursorVideo = null;
if (mimeType != null) {
mVideoFilter = "" + MediaStore.Video.Media.MIME_TYPE + "='" + mimeType + "'";
mMusicFilter = "" + MediaStore.Audio.Media.MIME_TYPE + "='" + mimeType + "'";
}
if (query != null) {
if (!mVideoFilter.equals("")) {
mVideoFilter += " AND ";
}
mVideoFilter += MediaStore.Video.Media.TITLE + " LIKE '%" + query + "%'";
if (!mMusicFilter.equals("")) {
mMusicFilter += " AND ";
}
mMusicFilter += "(" + MediaStore.Audio.Media.TITLE + " LIKE '%" + query + "%'";
mMusicFilter += " OR " + MediaStore.Audio.Media.COMPOSER + " LIKE '%" + query + "%')";
}
if (orders != null) {
if (orders.length == 2) {
mOrderBy = orders[0] + " " + orders[1];
mSort = getSortOrder(orders[0], orders[1]);
} else {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
} else {
mOrderBy = "title asc";
mSort = SortOrder.TITLE_ASC;
}
// 音楽用のテーブルキー設定.
mMusicParam = new String[] {MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.COMPOSER, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.DATE_ADDED};
mMusicUriType = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// 動画用のテーブルキー設定.
mVideoParam = new String[] {MediaStore.Video.Media.ALBUM, MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media.LANGUAGE, MediaStore.Video.Media.TITLE, MediaStore.Video.Media.DURATION,
MediaStore.Video.Media._ID, MediaStore.Video.Media.MIME_TYPE, MediaStore.Video.Media.DATE_ADDED};
mVideoUriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = this.getContext().getApplicationContext().getContentResolver();
try {
cursorMusic = mContentResolver.query(mMusicUriType, mMusicParam, mMusicFilter, null, mOrderBy);
cursorMusic.moveToFirst();
} catch (Exception e) {
MessageUtils.setInvalidRequestParameterError(response);
if (cursorMusic != null) {
cursorMusic.close();
}
return;
}
ArrayList<MediaList> mList = new ArrayList<MediaList>();
if (cursorMusic.getCount() > 0) {
counter = getMusicList(cursorMusic, mList);
}
try {
cursorVideo = mContentResolver.query(mVideoUriType, mVideoParam, mVideoFilter, null, mOrderBy);
cursorVideo.moveToFirst();
} catch (Exception e) {
MessageUtils.setInvalidRequestParameterError(response);
if (cursorMusic != null) {
cursorMusic.close();
}
if (cursorVideo != null) {
cursorVideo.close();
}
return;
}
if (cursorVideo.getCount() > 0) {
counter = getVideoList(cursorVideo, mList);
}
List<Bundle> list = new ArrayList<Bundle>();
counter = getMediaDataList(mList, list, offset, limit, mSort);
setCount(response, counter);
setMedia(response, list.toArray(new Bundle[list.size()]));
setResult(response, DConnectMessage.RESULT_OK);
cursorMusic.close();
cursorVideo.close();
return;
}
/**
* Get Music List.
* @param cursorMusic Cursor Music
* @param list List
* @return counter Music data count.
*/
private int getMusicList(final Cursor cursorMusic, final ArrayList<MediaList> list) {
int counter = 0;
do {
String mId = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media._ID));
String mType = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));
String mTitle = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.TITLE));
int mDuration = (cursorMusic.getInt(cursorMusic.getColumnIndex(MediaStore.Audio.Media.DURATION)))
/ UNIT_SEC;
String mArtist = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String mComp = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.COMPOSER));
list.add(new MediaList(mId, mType, mTitle, mArtist, mDuration, mComp, null, false));
counter++;
} while (cursorMusic.moveToNext());
return counter;
}
/**
* Get Video List.
* @param cursorVideo Cursor Video
* @param list List
* @return counter Video data count.
*/
private int getVideoList(final Cursor cursorVideo, final ArrayList<MediaList> list) {
int counter = 0;
do {
String mLang = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.LANGUAGE));
String mId = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media._ID));
String mType = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.MIME_TYPE));
String mTitle = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.TITLE));
int mDuration = (cursorVideo.getInt(cursorVideo.getColumnIndex(MediaStore.Video.Media.DURATION)))
/ UNIT_SEC;
String mArtist = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.ARTIST));
list.add(new MediaList(mId, mType, mTitle, mArtist, mDuration, null, mLang, true));
counter++;
} while (cursorVideo.moveToNext());
return counter;
}
/**
* Get Media List.
* @param orglist original list.
* @param medialist Media list.
* @param offset Offset.
* @param limit Limit.
* @param sortflag Sort flag.
* @return counter Video data count.
*/
private int getMediaDataList(final ArrayList<MediaList> orglist, final List<Bundle> medialist,
final Integer offset, final Integer limit, final SortOrder sortflag) {
switch (sortflag) {
case DURATION_ASC:
case DURATION_DESC:
Collections.sort(orglist, new MediaListDurationComparator());
break;
case ARTIST_ASC:
case ARTIST_DESC:
Collections.sort(orglist, new MediaListArtistComparator());
break;
case MIME_ASC:
case MIME_DESC:
Collections.sort(orglist, new MediaListTypeComparator());
break;
case ID_ASC:
case ID_DESC:
Collections.sort(orglist, new MediaListIdComparator());
break;
case COMPOSER_ASC:
case COMPOSER_DESC:
Collections.sort(orglist, new MediaListComposerComparator());
break;
case LANGUAGE_ASC:
case LANGUAGE_DESC:
Collections.sort(orglist, new MediaListLanguageComparator());
break;
case TITLE_ASC:
case TITLE_DESC:
default:
Collections.sort(orglist, new MediaListTitleComparator());
break;
}
switch (sortflag) {
case TITLE_DESC:
case DURATION_DESC:
case ARTIST_DESC:
case MIME_DESC:
case ID_DESC:
case COMPOSER_DESC:
case LANGUAGE_DESC:
Collections.reverse(orglist);
break;
default:
break;
}
int mOffset = 0;
if (offset == null) {
mOffset = 0;
} else {
mOffset = offset;
}
int mLimit = 0;
if (limit == null) {
mLimit = orglist.size();
} else {
mLimit = limit + mOffset;
}
for (int i = mOffset; i < mLimit; i++) {
Bundle medium = new Bundle();
String mComp = null;
String mId = orglist.get(i).getId();
String mType = orglist.get(i).getType();
String mTitle = orglist.get(i).getTitle();
String mArtist = orglist.get(i).getArtist();
int mDuration = orglist.get(i).getDuration();
setMediaId(medium, mId);
setMIMEType(medium, mType);
setTitle(medium, mTitle);
setDuration(medium, mDuration);
if (orglist.get(i).isVideo()) {
String mLang = orglist.get(i).getLanguage();
setType(medium, "Video");
setLanguage(medium, mLang);
} else {
mComp = orglist.get(i).getComposer();
setType(medium, "Music");
}
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creator = new Bundle();
setCreator(creator, mArtist);
setRole(creator, "Artist");
dataList.add((Bundle) creator.clone());
if (!(orglist.get(i).isVideo())) {
setCreator(creator, mComp);
setRole(creator, "Composer");
dataList.add((Bundle) creator.clone());
}
setCreators(medium, dataList.toArray(new Bundle[dataList.size()]));
medialist.add(medium);
}
return orglist.size();
}
@Override
protected boolean onPutVolume(final Intent request, final Intent response, final String serviceId,
final Double volume) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (volume == null) {
MessageUtils.setInvalidRequestParameterError(response);
} else if (0.0 > volume || volume > 1.0) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
double maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (maxVolume * volume), 1);
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("volume");
}
return true;
}
@Override
protected boolean onGetVolume(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
double maxVolume = 1;
double mVolume = 0;
mVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
setVolume(response, mVolume / maxVolume);
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutSeek(final Intent request, final Intent response,
final String serviceId, final Integer pos) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (pos == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else if (0 > pos) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
((HostDeviceService) getContext()).setMediaPos(response, pos);
return false;
}
@Override
protected boolean onGetSeek(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
int pos = ((HostDeviceService) getContext()).getMediaPos();
if (pos < 0) {
setPos(response, 0);
MessageUtils.setError(response, DConnectMessage.RESULT_ERROR, "Position acquisition failure.");
} else if (pos == Integer.MAX_VALUE) {
((HostDeviceService) getContext()).setVideoMediaPosRes(response);
return false;
} else {
setPos(response, pos);
setResult(response, DConnectMessage.RESULT_OK);
}
}
return true;
}
@Override
protected boolean onPutMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
sIsMute = true;
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("mute");
}
return true;
}
@Override
protected boolean onDeleteMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
sIsMute = false;
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("unmute");
}
return true;
}
@Override
protected boolean onGetMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
setMute(response, sIsMute);
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutOnStatusChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else if (sessionKey == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else {
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
((HostDeviceService) getContext()).registerOnStatusChange(response, serviceId);
return false;
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not register event.");
return true;
}
}
}
@Override
protected boolean onDeleteOnStatusChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else if (sessionKey == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
((HostDeviceService) getContext()).unregisterOnStatusChange(response);
return false;
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not unregister event.");
return true;
}
}
}
/**
* ファイル名からMIMEタイプ取得.
*
* @param path パス
* @return MIME-TYPE
*/
public String getMIMEType(final String path) {
if (BuildConfig.DEBUG) {
Log.i(TAG, path);
}
// 拡張子を取得
String ext = MimeTypeMap.getFileExtensionFromUrl(path);
// 小文字に変換
ext = ext.toLowerCase(Locale.getDefault());
// MIME Typeを返す
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
/**
* 数値かどうかをチェックする.
*
* @param value チェックしたいID
* @return 数値の場合はtrue、そうでない場合はfalse
*/
private boolean checkInteger(final String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* サービスIDをチェックする.
*
* @param serviceId サービスID
* @return <code>serviceId</code>がテスト用サービスIDに等しい場合はtrue、そうでない場合はfalse
*/
private boolean checkServiceId(final String serviceId) {
return HostServiceDiscoveryProfile.SERVICE_ID.equals(serviceId);
}
/**
* サービスIDが空の場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createEmptyServiceId(final Intent response) {
setResult(response, DConnectMessage.RESULT_ERROR);
}
/**
* デバイスが発見できなかった場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createNotFoundService(final Intent response) {
setResult(response, DConnectMessage.RESULT_ERROR);
}
/**
* ファイルパスからメディアIDを取得する.
*
* @param context コンテキスト
* @param path パス
* @return MediaID
*/
public static long mediaIdFromPath(final Context context, final String path) {
long id = 0;
String[] mParam = {BaseColumns._ID};
String[] mArgs = new String[] {path};
Cursor mAudioCursor = null;
// Audio
Uri mAudioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String mFilter = MediaStore.Audio.AudioColumns.DATA + " LIKE ?";
// Search Contents Provider
ContentResolver mAudioContentsProvider = context.getContentResolver();
try {
mAudioCursor = mAudioContentsProvider.query(mAudioUri, mParam, mFilter, mArgs, null);
if (mAudioCursor.moveToFirst()) {
int mIdField = mAudioCursor.getColumnIndex(mParam[0]);
id = mAudioCursor.getLong(mIdField);
}
mAudioCursor.close();
} catch (NullPointerException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mAudioCursor != null) {
mAudioCursor.close();
}
} catch (Exception e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mAudioCursor != null) {
mAudioCursor.close();
}
return -1;
}
// Search video
if (id == 0) {
Cursor mVideoCursor = null;
Uri mViodeUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
mFilter = MediaStore.Video.VideoColumns.DATA + " LIKE ?";
// Search Contents Provider
ContentResolver mVideoContentsProvider = context.getContentResolver();
try {
mVideoCursor = mVideoContentsProvider.query(mViodeUri, mParam, mFilter, mArgs, null);
if (mVideoCursor.moveToFirst()) {
int mIdField = mVideoCursor.getColumnIndex(mParam[0]);
id = mVideoCursor.getLong(mIdField);
} else {
id = -1;
}
mVideoCursor.close();
} catch (NullPointerException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mVideoCursor != null) {
mVideoCursor.close();
}
} catch (Exception e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mVideoCursor != null) {
mVideoCursor.close();
}
return -1;
}
}
return id;
}
/**
* Media list class.
*/
public class MediaList {
/** ID. */
private String mId;
/** Mime Type. */
private String mType;
/** Title. */
private String mTitle;
/** Artist. */
private String mArtist;
/** Duration. */
private int mDuration;
/** Composer(Audio only). */
private String mComposer;
/** Language(Video only). */
private String mLanguage;
/** Video flag. */
private boolean mIsVideo;
/**
* Constructor.
*
* @param id Id.
* @param type Mime type.
* @param title Title.
* @param artist Artist.
* @param duration Duration.
* @param composer Composer(Audio only).
* @param language Language(Video only).
* @param isvideo Video flag.
*/
public MediaList(final String id, final String type, final String title, final String artist,
final int duration, final String composer, final String language, final boolean isvideo) {
this.setId(id);
this.setType(type);
this.setTitle(title);
this.setArtist(artist);
this.setDuration(duration);
this.setComposer(composer);
this.setLanguage(language);
this.setVideo(isvideo);
}
/**
* Get Id.
*
* @return Id.
*/
public String getId() {
return mId;
}
/**
* Set Id.
*
* @param id Id.
*/
public void setId(final String id) {
this.mId = id;
}
/**
* Get mime type.
*
* @return Mime type.
*/
public String getType() {
return mType;
}
/**
* Set mime type.
* @param type mime type.
*/
public void setType(final String type) {
this.mType = type;
}
/**
* Get title.
*
* @return Title.
*/
public String getTitle() {
return mTitle;
}
/**
* Set title.
*
* @param title Title.
*/
public void setTitle(final String title) {
this.mTitle = title;
}
/**
* Get artist.
*
* @return Artist.
*/
public String getArtist() {
return mArtist;
}
/**
* Set artist.
*
* @param artist Artist.
*/
public void setArtist(final String artist) {
this.mArtist = artist;
}
/**
* Get duration.
*
* @return Duration.
*/
public int getDuration() {
return mDuration;
}
/**
* Set duration.
*
* @param duration Duration.
*/
public void setDuration(final int duration) {
this.mDuration = duration;
}
/**
* Get composer.
*
* @return Composer.
*/
public String getComposer() {
return mComposer;
}
/**
* Set composer.
*
* @param composer Composer.
*/
public void setComposer(final String composer) {
this.mComposer = composer;
}
/**
* Get language.
*
* @return Language.
*/
public String getLanguage() {
return mLanguage;
}
/**
* Set language.
*
* @param language Language.
*/
public void setLanguage(final String language) {
this.mLanguage = language;
}
/**
* Get Video flag.
* @return the mIsVideo.
*/
public boolean isVideo() {
return mIsVideo;
}
/**
* Set video flag.
* @param isvideo the isVideo to set.
*/
public void setVideo(final boolean isvideo) {
this.mIsVideo = isvideo;
}
}
/**
* Duration sorting comparator.
*/
public class MediaListDurationComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
int mData1 = lhs.getDuration();
int mData2 = rhs.getDuration();
if (mData1 > mData2) {
return 1;
} else if (mData1 == mData2) {
return 0;
} else {
return -1;
}
}
}
/**
* Title sorting comparator.
*/
public class MediaListTitleComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getTitle(), rhs.getTitle());
}
}
/**
* Artist sorting comparator.
*/
public class MediaListArtistComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getArtist(), rhs.getArtist());
}
}
/**
* Composer sorting comparator.
*/
public class MediaListComposerComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getComposer(), rhs.getComposer());
}
}
/**
* Language sorting comparator.
*/
public class MediaListLanguageComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getLanguage(), rhs.getLanguage());
}
}
/**
* ID sorting comparator.
*/
public class MediaListIdComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getId(), rhs.getId());
}
}
/**
* Type sorting comparator.
*/
public class MediaListTypeComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getType(), rhs.getType());
}
}
/**
* Data compare.
*
* @param data1 Data1.
* @param data2 Data2.
* @return result.
*/
public int compareData(final String data1, final String data2) {
if (data1 == null && data2 == null) {
return 0;
} else if (data1 != null && data2 == null) {
return 1;
} else if (data1 == null && data2 != null) {
return -1;
}
if (data1.compareTo(data2) > 0) {
return 1;
} else if (data1.compareTo(data2) == 0) {
return 0;
} else {
return -1;
}
}
/**
* Get sort order.
*
* @param order1 sort column.
* @param order2 asc / desc.
* @return SortOrder flag.
*/
public SortOrder getSortOrder(final String order1, final String order2) {
if (order1.compareToIgnoreCase("id") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.ID_DESC;
} else if (order1.compareToIgnoreCase("id") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.ID_ASC;
} else if (order1.compareToIgnoreCase("duration") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.DURATION_DESC;
} else if (order1.compareToIgnoreCase("duration") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.DURATION_ASC;
} else if (order1.compareToIgnoreCase("artist") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.ARTIST_DESC;
} else if (order1.compareToIgnoreCase("artist") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.ARTIST_ASC;
} else if (order1.compareToIgnoreCase("composer") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.COMPOSER_DESC;
} else if (order1.compareToIgnoreCase("composer") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.COMPOSER_ASC;
} else if (order1.compareToIgnoreCase("language") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.LANGUAGE_DESC;
} else if (order1.compareToIgnoreCase("language") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.LANGUAGE_ASC;
} else if (order1.compareToIgnoreCase("mime") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.MIME_DESC;
} else if (order1.compareToIgnoreCase("mime") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.MIME_ASC;
} else if (order1.compareToIgnoreCase("title") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.TITLE_DESC;
} else {
return SortOrder.TITLE_ASC;
}
}
}
| dConnectDevicePlugin/dConnectDeviceHost/src/org/deviceconnect/android/deviceplugin/host/profile/HostMediaPlayerProfile.java | /*
HostMediaPlayerProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.host.profile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.deviceconnect.android.deviceplugin.host.BuildConfig;
import org.deviceconnect.android.deviceplugin.host.HostDeviceService;
import org.deviceconnect.android.event.EventError;
import org.deviceconnect.android.event.EventManager;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.MediaPlayerProfile;
import org.deviceconnect.android.provider.FileManager;
import org.deviceconnect.message.DConnectMessage;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
/**
* Media Player Profile.
*
* @author NTT DOCOMO, INC.
*/
public class HostMediaPlayerProfile extends MediaPlayerProfile {
/** Debug Tag. */
private static final String TAG = "HOST";
/** Error. */
private static final int ERROR_VALUE_IS_NULL = 100;
/** ミリ秒 - 秒オーダー変換用. */
private static final int UNIT_SEC = 1000;
/** Sort flag. */
enum SortOrder {
/** Title (asc). */
TITLE_ASC,
/** Title (desc). */
TITLE_DESC,
/** Duration (asc). */
DURATION_ASC,
/** Duration (desc). */
DURATION_DESC,
/** Artist (asc). */
ARTIST_ASC,
/** Artist (desc). */
ARTIST_DESC,
/** Mime (asc). */
MIME_ASC,
/** Mime (desc). */
MIME_DESC,
/** Id (asc). */
ID_ASC,
/** Id (desc). */
ID_DESC,
/** Composer (asc). */
COMPOSER_ASC,
/** Composer (desc). */
COMPOSER_DESC,
/** Language (asc). */
LANGUAGE_ASC,
/** Language (desc). */
LANGUAGE_DESC
};
/**
* AudioのContentProviderのキー一覧を定義する.
*/
private static final String[] AUDIO_TABLE_KEYS = {
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.COMPOSER,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.DATE_ADDED,
MediaStore.Audio.Media.DISPLAY_NAME
};
/**
* VideoのContentProviderのキー一覧を定義する.
*/
private static final String[] VIDEO_TABLE_KEYS = {
MediaStore.Video.Media.ALBUM,
MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media.LANGUAGE,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media._ID,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.DISPLAY_NAME
};
/** Mute Status. */
private static Boolean sIsMute = false;
@Override
protected boolean onPutPlay(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).playMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutStop(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).stopMedia(response);
return false;
}
return true;
}
@Override
protected boolean onPutPause(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).pauseMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutResume(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
((HostDeviceService) getContext()).resumeMedia();
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onGetPlayStatus(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else {
((HostDeviceService) getContext()).getPlayStatus(response);
return false;
}
}
@Override
protected boolean onPutMedia(final Intent request, final Intent response, final String serviceId,
final String mediaId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (TextUtils.isEmpty(mediaId)) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
if (checkInteger(mediaId)) {
((HostDeviceService) getContext()).putMediaId(response, mediaId);
} else {
FileManager mFileManager = new FileManager(this.getContext());
long newMediaId = mediaIdFromPath(this.getContext(), mFileManager.getBasePath() + mediaId);
if (newMediaId == -1) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
((HostDeviceService) getContext()).putMediaId(response, "" + newMediaId);
}
return false;
}
return true;
}
@Override
protected boolean onGetMedia(final Intent request, final Intent response, final String serviceId,
final String mediaId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (TextUtils.isEmpty(mediaId)) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
// Query table parameter.
String[] param = null;
// URI
Uri uriType = null;
// Query filter.
String filter = "_display_name=?";
// Query cursor.
Cursor cursor = null;
// Get media path.
Uri uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));
String fileName = getDisplayNameFromUri(uri);
if (fileName == null) {
uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));
fileName = getDisplayNameFromUri(uri);
if (fileName == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
param = AUDIO_TABLE_KEYS;
uriType = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else {
param = VIDEO_TABLE_KEYS;
uriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
ContentResolver cresolver = getContext()
.getApplicationContext().getContentResolver();
try {
cursor = cresolver.query(uriType, param, filter, new String[] {fileName}, null);
if (cursor.moveToFirst()) {
loadMediaData(uriType, cursor, response);
}
setResult(response, DConnectMessage.RESULT_OK);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
return true;
}
/**
* cursorからMediaDataを読み込みBundleに格納して返却する.
* @param uriType メディアタイプ
* @param cursor データが格納されているCursor
* @param response response.
*/
private void loadMediaData(final Uri uriType, final Cursor cursor, final Intent response) {
String mId = null;
String mType = null;
String mTitle = null;
int mDuration = 0;
String mArtist = null;
String mComp = null;
if (uriType == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) {
mId = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
mType = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));
mTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
mDuration = (cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))) / UNIT_SEC;
mArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
mComp = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.COMPOSER));
setType(response, "Music");
// Make creator
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creator = new Bundle();
setCreator(creator, mArtist);
setRole(creator, "Artist");
dataList.add((Bundle) creator.clone());
setCreator(creator, mComp);
setRole(creator, "Composer");
dataList.add((Bundle) creator.clone());
setCreators(response, dataList.toArray(new Bundle[dataList.size()]));
} else {
mId = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
mType = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE));
mTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
mDuration = (cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))) / UNIT_SEC;
mArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ARTIST));
String mLang = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.LANGUAGE));
setLanguage(response, mLang);
setType(response, "Video");
// Make creator
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creatorVideo = new Bundle();
setCreator(creatorVideo, mArtist);
setRole(creatorVideo, "Artist");
dataList.add((Bundle) creatorVideo.clone());
setCreators(response, dataList.toArray(new Bundle[dataList.size()]));
}
setMediaId(response, mId);
setMIMEType(response, mType);
setTitle(response, mTitle);
setDuration(response, mDuration);
return;
}
/**
* Get display name from URI.
*
* @param mUri URI
* @return name display name.
*/
private String getDisplayNameFromUri(final Uri mUri) {
Cursor c = null;
try {
ContentResolver mContentResolver = getContext()
.getApplicationContext().getContentResolver();
c = mContentResolver.query(mUri, null, null, null, null);
if (c.moveToFirst()) {
int index = c.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
if (index != -1) {
return c.getString(index);
}
}
} finally {
if (c != null) {
c.close();
}
}
return null;
}
@Override
protected boolean onGetMediaList(final Intent request, final Intent response,
final String serviceId, final String query,
final String mimeType, final String[] orders, final Integer offset, final Integer limit) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
Bundle b = request.getExtras();
if (b.getString(PARAM_LIMIT) != null) {
if (parseInteger(b.get(PARAM_LIMIT)) == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
}
if (b.getString(PARAM_OFFSET) != null) {
if (parseInteger(b.get(PARAM_OFFSET)) == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
}
getMediaList(response, query, mimeType, orders, offset, limit);
}
return true;
}
/**
* Get Media List.
* @param response Response
* @param query Query
* @param mimeType MIME Type
* @param orders Order
* @param offset Offset
* @param limit Limit
*/
private void getMediaList(final Intent response, final String query,
final String mimeType, final String[] orders, final Integer offset,
final Integer limit) {
SortOrder mSort = SortOrder.TITLE_ASC;
int counter = 0;
if (limit != null) {
if (limit < 0) {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
}
if (offset != null) {
if (offset < 0) {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
}
// 音楽用のテーブルの項目.
String[] mMusicParam = null;
String[] mVideoParam = null;
// URI
Uri mMusicUriType = null;
Uri mVideoUriType = null;
// 検索用 Filterを作成.
String mVideoFilter = "";
String mMusicFilter = "";
// Orderの処理
String mOrderBy = "";
// 検索用Cursor.
Cursor cursorMusic = null;
Cursor cursorVideo = null;
if (mimeType != null) {
mVideoFilter = "" + MediaStore.Video.Media.MIME_TYPE + "='" + mimeType + "'";
mMusicFilter = "" + MediaStore.Audio.Media.MIME_TYPE + "='" + mimeType + "'";
}
if (query != null) {
if (!mVideoFilter.equals("")) {
mVideoFilter += " AND ";
}
mVideoFilter += MediaStore.Video.Media.TITLE + " LIKE '%" + query + "%'";
if (!mMusicFilter.equals("")) {
mMusicFilter += " AND ";
}
mMusicFilter += "(" + MediaStore.Audio.Media.TITLE + " LIKE '%" + query + "%'";
mMusicFilter += " OR " + MediaStore.Audio.Media.COMPOSER + " LIKE '%" + query + "%')";
}
if (orders != null) {
if (orders.length == 2) {
mOrderBy = orders[0] + " " + orders[1];
mSort = getSortOrder(orders[0], orders[1]);
} else {
MessageUtils.setInvalidRequestParameterError(response);
return;
}
} else {
mOrderBy = "title asc";
mSort = SortOrder.TITLE_ASC;
}
// 音楽用のテーブルキー設定.
mMusicParam = new String[] {MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.COMPOSER, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.DATE_ADDED};
mMusicUriType = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// 動画用のテーブルキー設定.
mVideoParam = new String[] {MediaStore.Video.Media.ALBUM, MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media.LANGUAGE, MediaStore.Video.Media.TITLE, MediaStore.Video.Media.DURATION,
MediaStore.Video.Media._ID, MediaStore.Video.Media.MIME_TYPE, MediaStore.Video.Media.DATE_ADDED};
mVideoUriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = this.getContext().getApplicationContext().getContentResolver();
try {
cursorMusic = mContentResolver.query(mMusicUriType, mMusicParam, mMusicFilter, null, mOrderBy);
cursorMusic.moveToFirst();
} catch (Exception e) {
MessageUtils.setInvalidRequestParameterError(response);
if (cursorMusic != null) {
cursorMusic.close();
}
return;
}
ArrayList<MediaList> mList = new ArrayList<MediaList>();
if (cursorMusic.getCount() > 0) {
counter = getMusicList(cursorMusic, mList);
}
try {
cursorVideo = mContentResolver.query(mVideoUriType, mVideoParam, mVideoFilter, null, mOrderBy);
cursorVideo.moveToFirst();
} catch (Exception e) {
MessageUtils.setInvalidRequestParameterError(response);
if (cursorMusic != null) {
cursorMusic.close();
}
if (cursorVideo != null) {
cursorVideo.close();
}
return;
}
if (cursorVideo.getCount() > 0) {
counter = getVideoList(cursorVideo, mList);
}
List<Bundle> list = new ArrayList<Bundle>();
counter = getMediaDataList(mList, list, offset, limit, mSort);
setCount(response, counter);
setMedia(response, list.toArray(new Bundle[list.size()]));
setResult(response, DConnectMessage.RESULT_OK);
cursorMusic.close();
cursorVideo.close();
return;
}
/**
* Get Music List.
* @param cursorMusic Cursor Music
* @param list List
* @return counter Music data count.
*/
private int getMusicList(final Cursor cursorMusic, final ArrayList<MediaList> list) {
int counter = 0;
do {
String mId = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media._ID));
String mType = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));
String mTitle = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.TITLE));
int mDuration = (cursorMusic.getInt(cursorMusic.getColumnIndex(MediaStore.Audio.Media.DURATION)))
/ UNIT_SEC;
String mArtist = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String mComp = cursorMusic.getString(cursorMusic.getColumnIndex(MediaStore.Audio.Media.COMPOSER));
list.add(new MediaList(mId, mType, mTitle, mArtist, mDuration, mComp, null, false));
counter++;
} while (cursorMusic.moveToNext());
return counter;
}
/**
* Get Video List.
* @param cursorVideo Cursor Video
* @param list List
* @return counter Video data count.
*/
private int getVideoList(final Cursor cursorVideo, final ArrayList<MediaList> list) {
int counter = 0;
do {
String mLang = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.LANGUAGE));
String mId = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media._ID));
String mType = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.MIME_TYPE));
String mTitle = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.TITLE));
int mDuration = (cursorVideo.getInt(cursorVideo.getColumnIndex(MediaStore.Video.Media.DURATION)))
/ UNIT_SEC;
String mArtist = cursorVideo.getString(cursorVideo.getColumnIndex(MediaStore.Video.Media.ARTIST));
list.add(new MediaList(mId, mType, mTitle, mArtist, mDuration, null, mLang, true));
counter++;
} while (cursorVideo.moveToNext());
return counter;
}
/**
* Get Media List.
* @param orglist original list.
* @param medialist Media list.
* @param offset Offset.
* @param limit Limit.
* @param sortflag Sort flag.
* @return counter Video data count.
*/
private int getMediaDataList(final ArrayList<MediaList> orglist, final List<Bundle> medialist,
final Integer offset, final Integer limit, final SortOrder sortflag) {
switch (sortflag) {
case DURATION_ASC:
case DURATION_DESC:
Collections.sort(orglist, new MediaListDurationComparator());
break;
case ARTIST_ASC:
case ARTIST_DESC:
Collections.sort(orglist, new MediaListArtistComparator());
break;
case MIME_ASC:
case MIME_DESC:
Collections.sort(orglist, new MediaListTypeComparator());
break;
case ID_ASC:
case ID_DESC:
Collections.sort(orglist, new MediaListIdComparator());
break;
case COMPOSER_ASC:
case COMPOSER_DESC:
Collections.sort(orglist, new MediaListComposerComparator());
break;
case LANGUAGE_ASC:
case LANGUAGE_DESC:
Collections.sort(orglist, new MediaListLanguageComparator());
break;
case TITLE_ASC:
case TITLE_DESC:
default:
Collections.sort(orglist, new MediaListTitleComparator());
break;
}
switch (sortflag) {
case TITLE_DESC:
case DURATION_DESC:
case ARTIST_DESC:
case MIME_DESC:
case ID_DESC:
case COMPOSER_DESC:
case LANGUAGE_DESC:
Collections.reverse(orglist);
break;
default:
break;
}
int mOffset = 0;
if (offset == null) {
mOffset = 0;
} else {
mOffset = offset;
}
int mLimit = 0;
if (limit == null) {
mLimit = orglist.size();
} else {
mLimit = limit + mOffset;
}
for (int i = mOffset; i < mLimit; i++) {
Bundle medium = new Bundle();
String mComp = null;
String mId = orglist.get(i).getId();
String mType = orglist.get(i).getType();
String mTitle = orglist.get(i).getTitle();
String mArtist = orglist.get(i).getArtist();
int mDuration = orglist.get(i).getDuration();
setMediaId(medium, mId);
setMIMEType(medium, mType);
setTitle(medium, mTitle);
setDuration(medium, mDuration);
if (orglist.get(i).isVideo()) {
String mLang = orglist.get(i).getLanguage();
setType(medium, "Video");
setLanguage(medium, mLang);
} else {
mComp = orglist.get(i).getComposer();
setType(medium, "Music");
}
List<Bundle> dataList = new ArrayList<Bundle>();
Bundle creator = new Bundle();
setCreator(creator, mArtist);
setRole(creator, "Artist");
dataList.add((Bundle) creator.clone());
if (!(orglist.get(i).isVideo())) {
setCreator(creator, mComp);
setRole(creator, "Composer");
dataList.add((Bundle) creator.clone());
}
setCreators(medium, dataList.toArray(new Bundle[dataList.size()]));
medialist.add(medium);
}
return orglist.size();
}
@Override
protected boolean onPutVolume(final Intent request, final Intent response, final String serviceId,
final Double volume) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (volume == null) {
MessageUtils.setInvalidRequestParameterError(response);
} else if (0.0 > volume || volume > 1.0) {
MessageUtils.setInvalidRequestParameterError(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
double maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (maxVolume * volume), 1);
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("volume");
}
return true;
}
@Override
protected boolean onGetVolume(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
double maxVolume = 1;
double mVolume = 0;
mVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
setVolume(response, mVolume / maxVolume);
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutSeek(final Intent request, final Intent response,
final String serviceId, final Integer pos) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else if (pos == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else if (0 > pos) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
}
((HostDeviceService) getContext()).setMediaPos(response, pos);
return false;
}
@Override
protected boolean onGetSeek(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
int pos = ((HostDeviceService) getContext()).getMediaPos();
if (pos < 0) {
setPos(response, 0);
MessageUtils.setError(response, DConnectMessage.RESULT_ERROR, "Position acquisition failure.");
} else if (pos == Integer.MAX_VALUE) {
((HostDeviceService) getContext()).setVideoMediaPosRes(response);
return false;
} else {
setPos(response, pos);
setResult(response, DConnectMessage.RESULT_OK);
}
}
return true;
}
@Override
protected boolean onPutMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
sIsMute = true;
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("mute");
}
return true;
}
@Override
protected boolean onDeleteMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
sIsMute = false;
setResult(response, DConnectMessage.RESULT_OK);
((HostDeviceService) getContext()).sendOnStatusChangeEvent("unmute");
}
return true;
}
@Override
protected boolean onGetMute(final Intent request, final Intent response, final String serviceId) {
if (serviceId == null) {
createEmptyServiceId(response);
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
} else {
setMute(response, sIsMute);
setResult(response, DConnectMessage.RESULT_OK);
}
return true;
}
@Override
protected boolean onPutOnStatusChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else if (sessionKey == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else {
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
((HostDeviceService) getContext()).registerOnStatusChange(response, serviceId);
return false;
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not register event.");
return true;
}
}
}
@Override
protected boolean onDeleteOnStatusChange(final Intent request, final Intent response, final String serviceId,
final String sessionKey) {
if (serviceId == null) {
createEmptyServiceId(response);
return true;
} else if (!checkServiceId(serviceId)) {
createNotFoundService(response);
return true;
} else if (sessionKey == null) {
MessageUtils.setInvalidRequestParameterError(response);
return true;
} else {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
((HostDeviceService) getContext()).unregisterOnStatusChange(response);
return false;
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "Can not unregister event.");
return true;
}
}
}
/**
* ファイル名からMIMEタイプ取得.
*
* @param path パス
* @return MIME-TYPE
*/
public String getMIMEType(final String path) {
if (BuildConfig.DEBUG) {
Log.i(TAG, path);
}
// 拡張子を取得
String ext = MimeTypeMap.getFileExtensionFromUrl(path);
// 小文字に変換
ext = ext.toLowerCase(Locale.getDefault());
// MIME Typeを返す
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
/**
* 数値かどうかをチェックする.
*
* @param value チェックしたいID
* @return 数値の場合はtrue、そうでない場合はfalse
*/
private boolean checkInteger(final String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* サービスIDをチェックする.
*
* @param serviceId サービスID
* @return <code>serviceId</code>がテスト用サービスIDに等しい場合はtrue、そうでない場合はfalse
*/
private boolean checkServiceId(final String serviceId) {
return HostServiceDiscoveryProfile.SERVICE_ID.equals(serviceId);
}
/**
* サービスIDが空の場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createEmptyServiceId(final Intent response) {
setResult(response, DConnectMessage.RESULT_ERROR);
}
/**
* デバイスが発見できなかった場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createNotFoundService(final Intent response) {
setResult(response, DConnectMessage.RESULT_ERROR);
}
/**
* ファイルパスからメディアIDを取得する.
*
* @param context コンテキスト
* @param path パス
* @return MediaID
*/
public static long mediaIdFromPath(final Context context, final String path) {
long id = 0;
String[] mParam = {BaseColumns._ID};
String[] mArgs = new String[] {path};
Cursor mAudioCursor = null;
// Audio
Uri mAudioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String mFilter = MediaStore.Audio.AudioColumns.DATA + " LIKE ?";
// Search Contents Provider
ContentResolver mAudioContentsProvider = context.getContentResolver();
try {
mAudioCursor = mAudioContentsProvider.query(mAudioUri, mParam, mFilter, mArgs, null);
mAudioCursor.moveToFirst();
int mIdField = mAudioCursor.getColumnIndex(mParam[0]);
id = mAudioCursor.getLong(mIdField);
mAudioCursor.close();
} catch (NullPointerException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mAudioCursor != null) {
mAudioCursor.close();
}
} catch (Exception e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mAudioCursor != null) {
mAudioCursor.close();
}
return -1;
}
// Search video
if (id == 0) {
Cursor mVideoCursor = null;
Uri mViodeUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
mFilter = MediaStore.Video.VideoColumns.DATA + " LIKE ?";
// Search Contents Provider
ContentResolver mVideoContentsProvider = context.getContentResolver();
try {
mVideoCursor = mVideoContentsProvider.query(mViodeUri, mParam, mFilter, mArgs, null);
mVideoCursor.moveToFirst();
int mIdField = mVideoCursor.getColumnIndex(mParam[0]);
id = mVideoCursor.getLong(mIdField);
mVideoCursor.close();
} catch (NullPointerException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mVideoCursor != null) {
mVideoCursor.close();
}
} catch (Exception e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
if (mVideoCursor != null) {
mVideoCursor.close();
}
return -1;
}
}
return id;
}
/**
* Media list class.
*/
public class MediaList {
/** ID. */
private String mId;
/** Mime Type. */
private String mType;
/** Title. */
private String mTitle;
/** Artist. */
private String mArtist;
/** Duration. */
private int mDuration;
/** Composer(Audio only). */
private String mComposer;
/** Language(Video only). */
private String mLanguage;
/** Video flag. */
private boolean mIsVideo;
/**
* Constructor.
*
* @param id Id.
* @param type Mime type.
* @param title Title.
* @param artist Artist.
* @param duration Duration.
* @param composer Composer(Audio only).
* @param language Language(Video only).
* @param isvideo Video flag.
*/
public MediaList(final String id, final String type, final String title, final String artist,
final int duration, final String composer, final String language, final boolean isvideo) {
this.setId(id);
this.setType(type);
this.setTitle(title);
this.setArtist(artist);
this.setDuration(duration);
this.setComposer(composer);
this.setLanguage(language);
this.setVideo(isvideo);
}
/**
* Get Id.
*
* @return Id.
*/
public String getId() {
return mId;
}
/**
* Set Id.
*
* @param id Id.
*/
public void setId(final String id) {
this.mId = id;
}
/**
* Get mime type.
*
* @return Mime type.
*/
public String getType() {
return mType;
}
/**
* Set mime type.
* @param type mime type.
*/
public void setType(final String type) {
this.mType = type;
}
/**
* Get title.
*
* @return Title.
*/
public String getTitle() {
return mTitle;
}
/**
* Set title.
*
* @param title Title.
*/
public void setTitle(final String title) {
this.mTitle = title;
}
/**
* Get artist.
*
* @return Artist.
*/
public String getArtist() {
return mArtist;
}
/**
* Set artist.
*
* @param artist Artist.
*/
public void setArtist(final String artist) {
this.mArtist = artist;
}
/**
* Get duration.
*
* @return Duration.
*/
public int getDuration() {
return mDuration;
}
/**
* Set duration.
*
* @param duration Duration.
*/
public void setDuration(final int duration) {
this.mDuration = duration;
}
/**
* Get composer.
*
* @return Composer.
*/
public String getComposer() {
return mComposer;
}
/**
* Set composer.
*
* @param composer Composer.
*/
public void setComposer(final String composer) {
this.mComposer = composer;
}
/**
* Get language.
*
* @return Language.
*/
public String getLanguage() {
return mLanguage;
}
/**
* Set language.
*
* @param language Language.
*/
public void setLanguage(final String language) {
this.mLanguage = language;
}
/**
* Get Video flag.
* @return the mIsVideo.
*/
public boolean isVideo() {
return mIsVideo;
}
/**
* Set video flag.
* @param isvideo the isVideo to set.
*/
public void setVideo(final boolean isvideo) {
this.mIsVideo = isvideo;
}
}
/**
* Duration sorting comparator.
*/
public class MediaListDurationComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
int mData1 = lhs.getDuration();
int mData2 = rhs.getDuration();
if (mData1 > mData2) {
return 1;
} else if (mData1 == mData2) {
return 0;
} else {
return -1;
}
}
}
/**
* Title sorting comparator.
*/
public class MediaListTitleComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getTitle(), rhs.getTitle());
}
}
/**
* Artist sorting comparator.
*/
public class MediaListArtistComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getArtist(), rhs.getArtist());
}
}
/**
* Composer sorting comparator.
*/
public class MediaListComposerComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getComposer(), rhs.getComposer());
}
}
/**
* Language sorting comparator.
*/
public class MediaListLanguageComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getLanguage(), rhs.getLanguage());
}
}
/**
* ID sorting comparator.
*/
public class MediaListIdComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getId(), rhs.getId());
}
}
/**
* Type sorting comparator.
*/
public class MediaListTypeComparator implements Comparator<MediaList> {
@Override
public int compare(final MediaList lhs, final MediaList rhs) {
return compareData(lhs.getType(), rhs.getType());
}
}
/**
* Data compare.
*
* @param data1 Data1.
* @param data2 Data2.
* @return result.
*/
public int compareData(final String data1, final String data2) {
if (data1 == null && data2 == null) {
return 0;
} else if (data1 != null && data2 == null) {
return 1;
} else if (data1 == null && data2 != null) {
return -1;
}
if (data1.compareTo(data2) > 0) {
return 1;
} else if (data1.compareTo(data2) == 0) {
return 0;
} else {
return -1;
}
}
/**
* Get sort order.
*
* @param order1 sort column.
* @param order2 asc / desc.
* @return SortOrder flag.
*/
public SortOrder getSortOrder(final String order1, final String order2) {
if (order1.compareToIgnoreCase("id") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.ID_DESC;
} else if (order1.compareToIgnoreCase("id") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.ID_ASC;
} else if (order1.compareToIgnoreCase("duration") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.DURATION_DESC;
} else if (order1.compareToIgnoreCase("duration") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.DURATION_ASC;
} else if (order1.compareToIgnoreCase("artist") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.ARTIST_DESC;
} else if (order1.compareToIgnoreCase("artist") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.ARTIST_ASC;
} else if (order1.compareToIgnoreCase("composer") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.COMPOSER_DESC;
} else if (order1.compareToIgnoreCase("composer") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.COMPOSER_ASC;
} else if (order1.compareToIgnoreCase("language") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.LANGUAGE_DESC;
} else if (order1.compareToIgnoreCase("language") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.LANGUAGE_ASC;
} else if (order1.compareToIgnoreCase("mime") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.MIME_DESC;
} else if (order1.compareToIgnoreCase("mime") == 0
&& order2.compareToIgnoreCase("asc") == 0) {
return SortOrder.MIME_ASC;
} else if (order1.compareToIgnoreCase("title") == 0
&& order2.compareToIgnoreCase("desc") == 0) {
return SortOrder.TITLE_DESC;
} else {
return SortOrder.TITLE_ASC;
}
}
}
| Bug fix Host MediaPlayer Profile.
Error Handling additional if the specified file does not exist.
| dConnectDevicePlugin/dConnectDeviceHost/src/org/deviceconnect/android/deviceplugin/host/profile/HostMediaPlayerProfile.java | Bug fix Host MediaPlayer Profile. Error Handling additional if the specified file does not exist. | <ide><path>ConnectDevicePlugin/dConnectDeviceHost/src/org/deviceconnect/android/deviceplugin/host/profile/HostMediaPlayerProfile.java
<ide> ContentResolver mAudioContentsProvider = context.getContentResolver();
<ide> try {
<ide> mAudioCursor = mAudioContentsProvider.query(mAudioUri, mParam, mFilter, mArgs, null);
<del> mAudioCursor.moveToFirst();
<del> int mIdField = mAudioCursor.getColumnIndex(mParam[0]);
<del> id = mAudioCursor.getLong(mIdField);
<add> if (mAudioCursor.moveToFirst()) {
<add> int mIdField = mAudioCursor.getColumnIndex(mParam[0]);
<add> id = mAudioCursor.getLong(mIdField);
<add> }
<ide> mAudioCursor.close();
<ide>
<ide> } catch (NullPointerException e) {
<ide> try {
<ide> mVideoCursor = mVideoContentsProvider.query(mViodeUri, mParam, mFilter, mArgs, null);
<ide>
<del> mVideoCursor.moveToFirst();
<del> int mIdField = mVideoCursor.getColumnIndex(mParam[0]);
<del> id = mVideoCursor.getLong(mIdField);
<add> if (mVideoCursor.moveToFirst()) {
<add> int mIdField = mVideoCursor.getColumnIndex(mParam[0]);
<add> id = mVideoCursor.getLong(mIdField);
<add> } else {
<add> id = -1;
<add> }
<ide> mVideoCursor.close();
<ide>
<ide> } catch (NullPointerException e) { |
|
Java | apache-2.0 | ac69f4d034a7fcf677e6eb22fc8d876b5b61508e | 0 | ianngiaw/HubTurbo,ianngiaw/HubTurbo,Honoo/HubTurbo,Honoo/HubTurbo,HyungJon/HubTurbo,Sumei1009/HubTurbo,saav/HubTurbo,HyungJon/HubTurbo,saav/HubTurbo,gaieepo/HubTurbo,Sumei1009/HubTurbo,gaieepo/HubTurbo | package browserview;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.NoSuchElementException;
// acts as a middleman for ChromeDriver when not in testing mode,
// and as a stub when testing
public class ChromeDriverEx {
private static final Logger logger = LogManager.getLogger(ChromeDriverEx.class.getName());
private boolean isTestChromeDriver;
private ChromeDriver driver;
ChromeDriverEx(ChromeOptions options, boolean isTestChromeDriver) {
this.isTestChromeDriver = isTestChromeDriver;
initialise(options);
}
private void initialise(ChromeOptions options) {
if (!isTestChromeDriver) driver = new ChromeDriver(options);
}
public WebDriver.Options manage() {
return !isTestChromeDriver ? driver.manage() : null;
}
public void quit() {
if (!isTestChromeDriver) driver.quit();
}
public void get(String url) throws WebDriverException {
if (isTestChromeDriver) {
logger.info("Test loading page: " + url);
testGet();
} else {
if (driver.getCurrentUrl().equals(url)) {
logger.info("Already on page: " + url + " will not load it again. ");
} else {
logger.info("Loading page: " + url);
driver.get(url);
}
}
}
public void testGet() throws WebDriverException {
double chance = Math.random();
if (chance < 0.25) {
throw new WebDriverException("no such window");
} else if (chance < 0.5) {
throw new WebDriverException("no such element");
} else if (chance < 0.75) {
throw new WebDriverException("unexpected alert open");
}
}
public String getCurrentUrl() {
return !isTestChromeDriver ? driver.getCurrentUrl() :
"https://github.com/HubTurbo/HubTurbo/issues/1";
}
public WebElement findElementById(String id) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElementById(id);
throw new NoSuchElementException();
}
public WebElement findElementByTagName(String tag) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElementByTagName(tag);
throw new NoSuchElementException();
}
public WebDriver.TargetLocator switchTo() throws WebDriverException {
if (!isTestChromeDriver) {
return driver.switchTo();
} else {
// ~25% chance to throw an exception which is used to test resetBrowser
if (Math.random() < 0.25) {
throw new WebDriverException();
}
}
return null;
}
public String getWindowHandle() {
return !isTestChromeDriver ? driver.getWindowHandle() : "";
}
public WebElement findElement(By by) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElement(by);
throw new NoSuchElementException();
}
public Object executeScript(String script) {
return !isTestChromeDriver ? driver.executeScript(script) : "";
}
}
| src/main/java/browserview/ChromeDriverEx.java | package browserview;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.NoSuchElementException;
// acts as a middleman for ChromeDriver when not in testing mode,
// and as a stub when testing
public class ChromeDriverEx {
private boolean isTestChromeDriver;
private ChromeDriver driver;
ChromeDriverEx(ChromeOptions options, boolean isTestChromeDriver) {
this.isTestChromeDriver = isTestChromeDriver;
initialise(options);
}
private void initialise(ChromeOptions options) {
if (!isTestChromeDriver) driver = new ChromeDriver(options);
}
public WebDriver.Options manage() {
return !isTestChromeDriver ? driver.manage() : null;
}
public void quit() {
if (!isTestChromeDriver) driver.quit();
}
public void get(String url) throws WebDriverException {
if (isTestChromeDriver) {
testGet();
} else {
driver.get(url);
}
}
public void testGet() throws WebDriverException {
double chance = Math.random();
if (chance < 0.25) {
throw new WebDriverException("no such window");
} else if (chance < 0.5) {
throw new WebDriverException("no such element");
} else if (chance < 0.75) {
throw new WebDriverException("unexpected alert open");
}
}
public String getCurrentUrl() {
return !isTestChromeDriver ? driver.getCurrentUrl() :
"https://github.com/HubTurbo/HubTurbo/issues/1";
}
public WebElement findElementById(String id) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElementById(id);
throw new NoSuchElementException();
}
public WebElement findElementByTagName(String tag) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElementByTagName(tag);
throw new NoSuchElementException();
}
public WebDriver.TargetLocator switchTo() throws WebDriverException {
if (!isTestChromeDriver) {
return driver.switchTo();
} else {
// ~25% chance to throw an exception which is used to test resetBrowser
if (Math.random() < 0.25) {
throw new WebDriverException();
}
}
return null;
}
public String getWindowHandle() {
return !isTestChromeDriver ? driver.getWindowHandle() : "";
}
public WebElement findElement(By by) throws NoSuchElementException {
if (!isTestChromeDriver) return driver.findElement(by);
throw new NoSuchElementException();
}
public Object executeScript(String script) {
return !isTestChromeDriver ? driver.executeScript(script) : "";
}
}
| put logging and same url checking in ChromeDriverEx
| src/main/java/browserview/ChromeDriverEx.java | put logging and same url checking in ChromeDriverEx | <ide><path>rc/main/java/browserview/ChromeDriverEx.java
<ide> package browserview;
<ide>
<add>import org.apache.logging.log4j.LogManager;
<add>import org.apache.logging.log4j.Logger;
<ide> import org.openqa.selenium.By;
<ide> import org.openqa.selenium.WebDriver;
<ide> import org.openqa.selenium.WebDriverException;
<ide> // and as a stub when testing
<ide>
<ide> public class ChromeDriverEx {
<add>
<add> private static final Logger logger = LogManager.getLogger(ChromeDriverEx.class.getName());
<ide>
<ide> private boolean isTestChromeDriver;
<ide> private ChromeDriver driver;
<ide>
<ide> public void get(String url) throws WebDriverException {
<ide> if (isTestChromeDriver) {
<add> logger.info("Test loading page: " + url);
<ide> testGet();
<ide> } else {
<del> driver.get(url);
<add> if (driver.getCurrentUrl().equals(url)) {
<add> logger.info("Already on page: " + url + " will not load it again. ");
<add> } else {
<add> logger.info("Loading page: " + url);
<add> driver.get(url);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 8522189f4dc8885dba5d24b8f8f870e6f48c6b87 | 0 | jpechane/debezium,debezium/debezium,jpechane/debezium,debezium/debezium,jpechane/debezium,debezium/debezium,jpechane/debezium,debezium/debezium | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.testing.openshift.tools.databases;
import static io.debezium.testing.openshift.tools.WaitConditions.scaled;
import static org.awaitility.Awaitility.await;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Jakub Cechacek
*/
public class SqlDatabaseClient implements DatabaseClient<Connection, SQLException> {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabaseClient.class);
private final String url;
private final String username;
private final String password;
public SqlDatabaseClient(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
private boolean doExecute(Commands<Connection, SQLException> commands) throws SQLException {
try (Connection con = DriverManager.getConnection(url, username, password)) {
commands.execute(con);
}
return true;
}
public void execute(Commands<Connection, SQLException> commands) throws SQLException {
await()
.atMost(scaled(2), TimeUnit.MINUTES)
.pollInterval(5, TimeUnit.SECONDS)
.ignoreExceptions()
.until(() -> doExecute(commands));
}
public void execute(String database, Commands<Connection, SQLException> commands) throws SQLException {
Commands<Connection, SQLException> withDatabase = con -> con.setCatalog(database);
execute(con -> withDatabase.andThen(commands).execute(con));
}
public void execute(String database, String command) throws SQLException {
LOGGER.info("Running SQL Command [" + database + "]: " + command);
execute(database, con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(command);
}
});
}
public void execute(String command) throws SQLException {
LOGGER.info("Running SQL Command: " + command);
execute(con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(command);
}
});
}
}
| debezium-testing/debezium-testing-openshift/src/main/java/io/debezium/testing/openshift/tools/databases/SqlDatabaseClient.java | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.testing.openshift.tools.databases;
import static io.debezium.testing.openshift.tools.WaitConditions.scaled;
import static org.awaitility.Awaitility.await;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Jakub Cechacek
*/
public class SqlDatabaseClient implements DatabaseClient<Connection, SQLException> {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractOcpDatabaseController.class);
private final String url;
private final String username;
private final String password;
public SqlDatabaseClient(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
private boolean doExecute(Commands<Connection, SQLException> commands) throws SQLException {
try (Connection con = DriverManager.getConnection(url, username, password)) {
commands.execute(con);
}
return true;
}
public void execute(Commands<Connection, SQLException> commands) throws SQLException {
await()
.atMost(scaled(2), TimeUnit.MINUTES)
.pollInterval(5, TimeUnit.SECONDS)
.ignoreExceptions()
.until(() -> doExecute(commands));
}
public void execute(String database, Commands<Connection, SQLException> commands) throws SQLException {
Commands<Connection, SQLException> withDatabase = con -> con.setCatalog(database);
execute(con -> withDatabase.andThen(commands).execute(con));
}
public void execute(String database, String command) throws SQLException {
LOGGER.info("Running SQL Command [" + database + "]: " + command);
execute(database, con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(command);
}
});
}
public void execute(String command) throws SQLException {
LOGGER.info("Running SQL Command: " + command);
execute(con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(command);
}
});
}
}
| DBZ-3566 Fixed LOGGER instantiation in SqlDatabaseClient
| debezium-testing/debezium-testing-openshift/src/main/java/io/debezium/testing/openshift/tools/databases/SqlDatabaseClient.java | DBZ-3566 Fixed LOGGER instantiation in SqlDatabaseClient | <ide><path>ebezium-testing/debezium-testing-openshift/src/main/java/io/debezium/testing/openshift/tools/databases/SqlDatabaseClient.java
<ide> */
<ide> public class SqlDatabaseClient implements DatabaseClient<Connection, SQLException> {
<ide>
<del> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractOcpDatabaseController.class);
<add> private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabaseClient.class);
<ide>
<ide> private final String url;
<ide> private final String username; |
|
Java | agpl-3.0 | 07f070cc4b0bdd143ea9359297332338cc092e70 | 0 | alcarraz/jPOS,alcarraz/jPOS,alcarraz/jPOS,jpos/jPOS,barspi/jPOS,jpos/jPOS,jpos/jPOS,barspi/jPOS,barspi/jPOS | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2018 jPOS Software SRL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.iso;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Vector;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.util.LogEvent;
import org.jpos.util.LogSource;
import org.jpos.util.Loggeable;
import org.jpos.util.Logger;
import org.jpos.util.NameRegistrar;
import org.jpos.util.ThreadPool;
/**
* Accept ServerChannel sessions and forwards them to ISORequestListeners
* @author Alejandro P. Revilla
* @author Bharavi Gade
* @version $Revision$ $Date$
*/
@SuppressWarnings("unchecked")
public class ISOServer extends Observable
implements LogSource, Runnable, Observer, ISOServerMBean, Configurable,
Loggeable, ISOServerSocketFactory
{
private enum PermLogPolicy {
ALLOW_NOLOG, DENY_LOG, ALLOW_LOG, DENY_LOGWARNING
}
int port;
private InetAddress bindAddr;
private Map<String,Boolean> specificIPPerms= new HashMap<>(); // TRUE means allow; FALSE means deny
private List<String> wildcardAllow;
private List<String> wildcardDeny;
private PermLogPolicy ipPermLogPolicy= PermLogPolicy.ALLOW_NOLOG;
protected ISOChannel clientSideChannel;
ISOPackager clientPackager;
protected Collection clientOutgoingFilters, clientIncomingFilters, listeners;
ThreadPool pool;
public static final int DEFAULT_MAX_THREADS = 100;
public static final String LAST = ":last";
String name;
protected long lastTxn = 0l;
protected Logger logger;
protected String realm;
protected String realmChannel;
protected ISOServerSocketFactory socketFactory = null;
public static final int CONNECT = 0;
public static final int SIZEOF_CNT = 1;
private int[] cnt;
private int backlog;
protected Configuration cfg;
private boolean shutdown = false;
private ServerSocket serverSocket;
private Map channels;
protected boolean ignoreISOExceptions;
protected List<ISOServerEventListener> serverListeners = null;
/**
* @param port port to listen
* @param clientSide client side ISOChannel (where we accept connections)
* @param pool ThreadPool (created if null)
*/
public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) {
super();
this.port = port;
this.clientSideChannel = clientSide;
this.clientPackager = clientSide.getPackager();
if (clientSide instanceof FilteredChannel) {
FilteredChannel fc = (FilteredChannel) clientSide;
this.clientOutgoingFilters = fc.getOutgoingFilters();
this.clientIncomingFilters = fc.getIncomingFilters();
}
this.pool = pool == null ?
new ThreadPool (1, DEFAULT_MAX_THREADS) : pool;
listeners = new Vector();
name = "";
channels = new HashMap();
cnt = new int[SIZEOF_CNT];
serverListeners = new ArrayList<ISOServerEventListener>();
}
@Override
public void setConfiguration (Configuration cfg) throws ConfigurationException {
this.cfg = cfg;
configureConnectionPerms();
backlog = cfg.getInt ("backlog", 0);
ignoreISOExceptions = cfg.getBoolean("ignore-iso-exceptions");
String ip = cfg.get ("bind-address", null);
if (ip != null) {
try {
bindAddr = InetAddress.getByName (ip);
} catch (UnknownHostException e) {
throw new ConfigurationException ("Invalid bind-address " + ip, e);
}
}
if (socketFactory == null) {
socketFactory = this;
}
if (socketFactory != this && socketFactory instanceof Configurable) {
((Configurable)socketFactory).setConfiguration (cfg);
}
}
// Helper method to setConfiguration. Handles "allow" and "deny" params
private void configureConnectionPerms() throws ConfigurationException
{
boolean hasAllows= false, hasDenies= false;
String[] allows= cfg.getAll ("allow");
if (allows != null && allows.length > 0) {
hasAllows= true;
for (String allowIP : allows) {
allowIP= allowIP.trim();
if (allowIP.indexOf('*') == -1) { // specific IP with no wildcards
specificIPPerms.put(allowIP, true);
} else { // there's a wildcard
wildcardAllow= (wildcardAllow == null) ? new ArrayList<>() : wildcardAllow;
String[] parts= allowIP.split("[*]");
wildcardAllow.add(parts[0]); // keep only the first part
}
}
}
String[] denies= cfg.getAll ("deny");
if (denies != null && denies.length > 0) {
hasDenies= true;
for (String denyIP : denies) {
boolean conflict= false; // used for a little sanity check
denyIP= denyIP.trim();
if (denyIP.indexOf('*') == -1) { // specific IP with no wildcards
Boolean oldVal= specificIPPerms.put(denyIP, false);
conflict= (oldVal == Boolean.TRUE);
} else { // there's a wildcard
wildcardDeny= (wildcardDeny == null) ? new ArrayList<>() : wildcardDeny;
String[] parts= denyIP.split("[*]");
if (wildcardAllow != null && wildcardAllow.contains(parts[0]))
conflict= true;
else
wildcardDeny.add(parts[0]); // keep only the first part
}
if (conflict) {
throw new ConfigurationException(
"Conflicting IP permission in '"+getName()+"' configuration: 'deny' "
+denyIP+" while having an identical previous 'allow'.");
}
}
}
// sum up permission policy and logging type
ipPermLogPolicy= (!hasAllows && !hasDenies) ? PermLogPolicy.ALLOW_NOLOG : // default when no permissions specified
( hasAllows && !hasDenies) ? PermLogPolicy.DENY_LOG :
(!hasAllows && hasDenies) ? PermLogPolicy.ALLOW_LOG :
PermLogPolicy.DENY_LOGWARNING; // mixed allows & denies, if nothing matches we'll DENY and log a warning
}
/**
* add an ISORequestListener
* @param l request listener to be added
* @see ISORequestListener
*/
public void addISORequestListener(ISORequestListener l) {
listeners.add (l);
}
/**
* remove an ISORequestListener
* @param l a request listener to be removed
* @see ISORequestListener
*/
public void removeISORequestListener(ISORequestListener l) {
listeners.remove (l);
}
/**
* Shutdown this server
*/
public void shutdown () {
shutdown = true;
new Thread ("ISOServer-shutdown") {
@Override
public void run () {
shutdownServer ();
if (!cfg.getBoolean ("keep-channels")) {
shutdownChannels ();
}
}
}.start();
}
private void shutdownServer () {
try {
if (serverSocket != null) {
serverSocket.close ();
fireEvent(new ISOServerShutdownEvent(this));
}
if (pool != null) {
pool.close();
}
} catch (IOException e) {
fireEvent(new ISOServerShutdownEvent(this));
Logger.log (new LogEvent (this, "shutdown", e));
}
}
private void shutdownChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null) {
try {
c.disconnect ();
fireEvent(new ISOServerClientDisconnectEvent(this));
} catch (IOException e) {
Logger.log (new LogEvent (this, "shutdown", e));
}
}
}
}
private void purgeChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c == null || !c.isConnected()) {
iter.remove ();
}
}
}
@Override
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket();
try {
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(bindAddr, port), backlog);
} catch(SecurityException e) {
ss.close();
fireEvent(new ISOServerShutdownEvent(this));
throw e;
} catch(IOException e) {
ss.close();
fireEvent(new ISOServerShutdownEvent(this));
throw e;
}
return ss;
}
//-----------------------------------------------------------------------------
// -- Helper Session inner class. It's a Runnable, running in its own
// -- thread and handling a connection to this ISOServer
// --
protected Session createSession (ServerChannel channel) {
return new Session (channel);
}
protected class Session implements Runnable, LogSource {
ServerChannel channel;
String realm;
protected Session(ServerChannel channel) {
this.channel = channel;
realm = ISOServer.this.getRealm() + ".session";
}
@Override
public void run() {
setChanged ();
notifyObservers ();
if (channel instanceof BaseChannel) {
LogEvent ev = new LogEvent (this, "session-start");
Socket socket = ((BaseChannel)channel).getSocket ();
realm = realm + "/" + socket.getInetAddress().getHostAddress() + ":"
+ socket.getPort();
try {
checkPermission (socket, ev);
} catch (ISOException e) {
try {
int delay = 1000 + new Random().nextInt (4000);
ev.addMessage (e.getMessage());
ev.addMessage ("delay=" + delay);
ISOUtil.sleep (delay);
socket.close ();
fireEvent(new ISOServerShutdownEvent(ISOServer.this));
} catch (IOException ioe) {
ev.addMessage (ioe);
}
return;
} finally {
Logger.log (ev);
}
}
try {
for (;;) {
try {
ISOMsg m = channel.receive();
lastTxn = System.currentTimeMillis();
Iterator iter = listeners.iterator();
while (iter.hasNext()) {
if (((ISORequestListener)iter.next()).process
(channel, m)) {
break;
}
}
}
catch (ISOFilter.VetoException e) {
Logger.log (new LogEvent (this, "VetoException", e.getMessage()));
}
catch (ISOException e) {
if (ignoreISOExceptions) {
Logger.log (new LogEvent (this, "ISOException", e.getMessage()));
}
else {
throw e;
}
}
}
} catch (EOFException e) {
// Logger.log (new LogEvent (this, "session-warning", "<eof/>"));
} catch (SocketException e) {
// if (!shutdown)
// Logger.log (new LogEvent (this, "session-warning", e));
} catch (InterruptedIOException e) {
// nothing to log
} catch (Throwable e) {
Logger.log (new LogEvent (this, "session-error", e));
}
try {
channel.disconnect();
fireEvent(new ISOServerClientDisconnectEvent(ISOServer.this));
} catch (IOException ex) {
Logger.log (new LogEvent (this, "session-error", ex));
fireEvent(new ISOServerClientDisconnectEvent(ISOServer.this));
}
Logger.log (new LogEvent (this, "session-end"));
}
@Override
public void setLogger (Logger logger, String realm) {
}
@Override
public String getRealm () {
return realm;
}
@Override
public Logger getLogger() {
return ISOServer.this.getLogger();
}
public void checkPermission (Socket socket, LogEvent evt) throws ISOException
{
// if there are no allow/deny params, just return without doing any checks
// (i.e.: "silent allow policy", keeping backward compatibility)
if (specificIPPerms.isEmpty() && wildcardAllow == null && wildcardDeny == null)
return;
String ip= socket.getInetAddress().getHostAddress (); // The remote IP
// first, check allows or denies for specific/whole IPs (no wildcards)
Boolean specificAllow= specificIPPerms.get(ip);
if (specificAllow == Boolean.TRUE) { // specific IP allow
evt.addMessage("access granted, ip=" + ip);
return;
} else if (specificAllow == Boolean.FALSE) { // specific IP deny
throw new ISOException("access denied, ip=" + ip);
} else { // no specific match under the specificIPPerms Map
// We check the wildcard lists, deny first
if (wildcardDeny != null) {
for (String wdeny : wildcardDeny) {
if (ip.startsWith(wdeny)) {
throw new ISOException ("access denied, ip=" + ip);
}
}
}
if (wildcardAllow != null) {
for (String wallow : wildcardAllow) {
if (ip.startsWith(wallow)) {
evt.addMessage("access granted, ip=" + ip);
return;
}
}
}
// Reaching this point means that nothing matched our specific or wildcard rules, so we fall
// back on the default permission policies and log type
switch (ipPermLogPolicy) {
case DENY_LOG: // only allows were specified, default policy is to deny non-matches and log the issue
throw new ISOException ("access denied, ip=" + ip);
// break;
case ALLOW_LOG: // only denies were specified, default policy is to allow non-matches and log the issue
evt.addMessage("access granted, ip=" + ip);
break;
case DENY_LOGWARNING: // mix of allows and denies were specified, but the IP matched no rules!
// so we adopt a deny policy but give a special warning
throw new ISOException ("access denied, ip=" + ip + " (WARNING: the IP did not match any rules!)");
// break;
case ALLOW_NOLOG: // this is the default case when no allow/deny are specified
// the method will abort early on the first "if", so this is here just for completion
break;
}
}
// we should never reach this point!! :-)
}
} // inner class Session
//-------------------------------------------------------------------------------
//-- This is the main run for this ISOServer's Thread
@Override
public void run() {
ServerChannel channel;
if (socketFactory == null) {
socketFactory = this;
}
serverLoop : while (!shutdown) {
try {
serverSocket = socketFactory.createServerSocket(port);
Logger.log (new LogEvent (this, "iso-server",
"listening on " + (bindAddr != null ? bindAddr + ":" : "port ") + port
+ (backlog > 0 ? " backlog="+backlog : "")
));
while (!shutdown) {
try {
if (pool.getAvailableCount() <= 0) {
try {
serverSocket.close();
fireEvent(new ISOServerShutdownEvent(this));
} catch (IOException e){
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
for (int i=0; pool.getIdleCount() == 0; i++) {
if (shutdown) {
break serverLoop;
}
if (i % 240 == 0 && cfg.getBoolean("pool-exhaustion-warning", true)) {
LogEvent evt = new LogEvent (this, "warn");
evt.addMessage (
"pool exhausted " + serverSocket.toString()
);
evt.addMessage (pool);
Logger.log (evt);
}
ISOUtil.sleep (250);
}
serverSocket = socketFactory.createServerSocket(port);
}
channel = (ServerChannel) clientSideChannel.clone();
channel.accept (serverSocket);
if (cnt[CONNECT]++ % 100 == 0) {
purgeChannels ();
}
WeakReference wr = new WeakReference (channel);
channels.put (channel.getName(), wr);
channels.put (LAST, wr);
pool.execute (createSession(channel));
setChanged ();
notifyObservers (this);
fireEvent(new ISOServerAcceptEvent(this));
if (channel instanceof Observable) {
((Observable)channel).addObserver (this);
}
} catch (SocketException e) {
if (!shutdown) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
continue serverLoop;
}
} catch (IOException e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
} // while !shutdown
} catch (Throwable e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
}
} // ISOServer's run()
//-------------------------------------------------------------------------------
private void relax() {
try {
Thread.sleep (5000);
} catch (InterruptedException e) { }
}
/**
* associates this ISOServer with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
this.name = name;
NameRegistrar.register ("server."+name, this);
}
/**
* @return ISOServer instance with given name.
* @throws NameRegistrar.NotFoundException;
* @see NameRegistrar
*/
public static ISOServer getServer (String name)
throws NameRegistrar.NotFoundException
{
return (ISOServer) NameRegistrar.get ("server."+name);
}
/**
* @return this ISOServer's name ("" if no name was set)
*/
public String getName() {
return this.name;
}
@Override
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
this.realmChannel = realm + ".channel";
}
@Override
public String getRealm () {
return realm;
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public void update(Observable o, Object arg) {
setChanged ();
notifyObservers (arg);
}
/**
* Gets the ISOClientSocketFactory (may be null)
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public ISOServerSocketFactory getSocketFactory() {
return socketFactory;
}
/**
* Sets the specified Socket Factory to create sockets
* @param socketFactory the ISOClientSocketFactory
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public void setSocketFactory(ISOServerSocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
@Override
public int getPort () {
return port;
}
@Override
public void resetCounters () {
cnt = new int[SIZEOF_CNT];
lastTxn = 0l;
}
/**
* @return number of connections accepted by this server
*/
@Override
public int getConnectionCount () {
return cnt[CONNECT];
}
// ThreadPoolMBean implementation (delegate calls to pool)
@Override
public int getJobCount () {
return pool.getJobCount();
}
@Override
public int getPoolSize () {
return pool.getPoolSize();
}
@Override
public int getMaxPoolSize () {
return pool.getMaxPoolSize();
}
@Override
public int getIdleCount() {
return pool.getIdleCount();
}
@Override
public int getPendingCount () {
return pool.getPendingCount();
}
public int getActiveConnections () {
return pool.getActiveCount();
}
/**
* @return most recently connected ISOChannel or null
*/
public ISOChannel getLastConnectedISOChannel () {
return getISOChannel (LAST);
}
/**
* @return ISOChannel under the given name
*/
public ISOChannel getISOChannel (String name) {
WeakReference ref = (WeakReference) channels.get (name);
if (ref != null) {
return (ISOChannel) ref.get ();
}
return null;
}
@Override
public String getISOChannelNames () {
StringBuilder sb = new StringBuilder ();
Iterator iter = channels.entrySet().iterator();
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
if (i > 0) {
sb.append (' ');
}
sb.append (entry.getKey());
}
}
return sb.toString();
}
public String getCountersAsString () {
StringBuilder sb = new StringBuilder ();
int cnt[] = getCounters();
sb.append ("connected=");
sb.append (Integer.toString(cnt[2]));
sb.append (", rx=");
sb.append (Integer.toString(cnt[0]));
sb.append (", tx=");
sb.append (Integer.toString(cnt[1]));
sb.append (", last=");
sb.append (lastTxn);
if (lastTxn > 0) {
sb.append (", idle=");
sb.append(System.currentTimeMillis() - lastTxn);
sb.append ("ms");
}
return sb.toString();
}
public int[] getCounters()
{
Iterator iter = channels.entrySet().iterator();
int[] cnt = new int[3];
cnt[2] = 0;
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
cnt[2]++;
if (c instanceof BaseChannel) {
int[] cc = ((BaseChannel)c).getCounters();
cnt[0] += cc[ISOChannel.RX];
cnt[1] += cc[ISOChannel.TX];
}
}
}
return cnt;
}
@Override
public int getTXCounter() {
int cnt[] = getCounters();
return cnt[1];
}
@Override
public int getRXCounter() {
int cnt[] = getCounters();
return cnt[0];
}
public int getConnections () {
int cnt[] = getCounters();
return cnt[2];
}
@Override
public long getLastTxnTimestampInMillis() {
return lastTxn;
}
@Override
public long getIdleTimeInMillis() {
return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L;
}
@Override
public String getCountersAsString (String isoChannelName) {
ISOChannel channel = getISOChannel(isoChannelName);
StringBuffer sb = new StringBuffer();
if (channel instanceof BaseChannel) {
int[] counters = ((BaseChannel)channel).getCounters();
append (sb, "rx=", counters[ISOChannel.RX]);
append (sb, ", tx=", counters[ISOChannel.TX]);
append (sb, ", connects=", counters[ISOChannel.CONNECT]);
}
return sb.toString();
}
@Override
public void dump (PrintStream p, String indent) {
p.println (indent + getCountersAsString());
Iterator iter = channels.entrySet().iterator();
String inner = indent + " ";
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected() && c instanceof BaseChannel) {
StringBuilder sb = new StringBuilder ();
int[] cc = ((BaseChannel)c).getCounters();
sb.append (inner);
sb.append (entry.getKey());
sb.append (": rx=");
sb.append (Integer.toString (cc[ISOChannel.RX]));
sb.append (", tx=");
sb.append (Integer.toString (cc[ISOChannel.TX]));
sb.append (", last=");
sb.append (Long.toString(lastTxn));
p.println (sb.toString());
}
}
}
private void append (StringBuffer sb, String name, int value) {
sb.append (name);
sb.append (value);
}
public synchronized void addServerEventListener(ISOServerEventListener listener) {
serverListeners.add(listener);
}
public synchronized void removeServerEventListener(ISOServerEventListener listener) {
serverListeners.remove(listener);
}
public synchronized void fireEvent(EventObject event) {
for (ISOServerEventListener l : serverListeners) {
try {
l.handleISOServerEvent(event);
}
catch (Exception ignore) {
/*
* Don't want an exception from a handler to exit the loop or
* let it bubble up.
* If it bubbles up it can cause side effects like getting caught
* in the throwable catch leading to server trying to listen on
* the same port.
* We don't want a side effect in jpos caused by custom user
* handler code.
*/
}
}
}
| jpos/src/main/java/org/jpos/iso/ISOServer.java | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2018 jPOS Software SRL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.iso;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Vector;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.util.LogEvent;
import org.jpos.util.LogSource;
import org.jpos.util.Loggeable;
import org.jpos.util.Logger;
import org.jpos.util.NameRegistrar;
import org.jpos.util.ThreadPool;
/**
* Accept ServerChannel sessions and forwards them to ISORequestListeners
* @author Alejandro P. Revilla
* @author Bharavi Gade
* @version $Revision$ $Date$
*/
@SuppressWarnings("unchecked")
public class ISOServer extends Observable
implements LogSource, Runnable, Observer, ISOServerMBean, Configurable,
Loggeable, ISOServerSocketFactory
{
private enum PermLogPolicy {
ALLOW_NOLOG, DENY_LOG, ALLOW_LOG, DENY_LOGWARNING
}
int port;
private InetAddress bindAddr;
private Map<String,Boolean> specificIPPerms= new HashMap<>(); // TRUE means allow; FALSE means deny
private List<String> wildcardAllow;
private List<String> wildcardDeny;
private PermLogPolicy ipPermLogPolicy= PermLogPolicy.ALLOW_NOLOG;
protected ISOChannel clientSideChannel;
ISOPackager clientPackager;
protected Collection clientOutgoingFilters, clientIncomingFilters, listeners;
ThreadPool pool;
public static final int DEFAULT_MAX_THREADS = 100;
public static final String LAST = ":last";
String name;
protected long lastTxn = 0l;
protected Logger logger;
protected String realm;
protected String realmChannel;
protected ISOServerSocketFactory socketFactory = null;
public static final int CONNECT = 0;
public static final int SIZEOF_CNT = 1;
private int[] cnt;
private int backlog;
protected Configuration cfg;
private boolean shutdown = false;
private ServerSocket serverSocket;
private Map channels;
protected boolean ignoreISOExceptions;
protected List<ISOServerEventListener> serverListeners = null;
/**
* @param port port to listen
* @param clientSide client side ISOChannel (where we accept connections)
* @param pool ThreadPool (created if null)
*/
public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) {
super();
this.port = port;
this.clientSideChannel = clientSide;
this.clientPackager = clientSide.getPackager();
if (clientSide instanceof FilteredChannel) {
FilteredChannel fc = (FilteredChannel) clientSide;
this.clientOutgoingFilters = fc.getOutgoingFilters();
this.clientIncomingFilters = fc.getIncomingFilters();
}
this.pool = pool == null ?
new ThreadPool (1, DEFAULT_MAX_THREADS) : pool;
listeners = new Vector();
name = "";
channels = new HashMap();
cnt = new int[SIZEOF_CNT];
serverListeners = new ArrayList<ISOServerEventListener>();
}
@Override
public void setConfiguration (Configuration cfg) throws ConfigurationException {
this.cfg = cfg;
configureConnectionPerms();
backlog = cfg.getInt ("backlog", 0);
ignoreISOExceptions = cfg.getBoolean("ignore-iso-exceptions");
String ip = cfg.get ("bind-address", null);
if (ip != null) {
try {
bindAddr = InetAddress.getByName (ip);
} catch (UnknownHostException e) {
throw new ConfigurationException ("Invalid bind-address " + ip, e);
}
}
if (socketFactory == null) {
socketFactory = this;
}
if (socketFactory != this && socketFactory instanceof Configurable) {
((Configurable)socketFactory).setConfiguration (cfg);
}
}
// Helper method to setConfiguration. Handles "allow" and "deny" params
private void configureConnectionPerms() throws ConfigurationException
{
boolean hasAllows= false, hasDenies= false;
String[] allows= cfg.getAll ("allow");
if (allows != null && allows.length > 0) {
hasAllows= true;
for (String allowIP : allows) {
allowIP= allowIP.trim();
if (allowIP.indexOf('*') == -1) { // specific IP with no wildcards
specificIPPerms.put(allowIP, true);
} else { // there's a wildcard
wildcardAllow= (wildcardAllow == null) ? new ArrayList<>() : wildcardAllow;
String[] parts= allowIP.split("[*]");
wildcardAllow.add(parts[0]); // keep only the first part
}
}
}
String[] denies= cfg.getAll ("deny");
if (denies != null && denies.length > 0) {
hasDenies= true;
for (String denyIP : denies) {
boolean conflict= false; // used for a little sanity check
denyIP= denyIP.trim();
if (denyIP.indexOf('*') == -1) { // specific IP with no wildcards
Boolean oldVal= specificIPPerms.put(denyIP, false);
conflict= (oldVal == Boolean.TRUE);
} else { // there's a wildcard
wildcardDeny= (wildcardDeny == null) ? new ArrayList<>() : wildcardDeny;
String[] parts= denyIP.split("[*]");
if (wildcardAllow != null && wildcardAllow.contains(parts[0]))
conflict= true;
else
wildcardDeny.add(parts[0]); // keep only the first part
}
if (conflict) {
throw new ConfigurationException(
"Conflicting IP permission in '"+getName()+"' configuration: 'deny' "
+denyIP+" while having an identical previous 'allow'.");
}
}
}
// sum up permission policy and logging type
ipPermLogPolicy= (!hasAllows && !hasDenies) ? PermLogPolicy.ALLOW_NOLOG : // default when no permissions specified
( hasAllows && !hasDenies) ? PermLogPolicy.DENY_LOG :
(!hasAllows && hasDenies) ? PermLogPolicy.ALLOW_LOG :
PermLogPolicy.DENY_LOGWARNING; // mixed allows & denies, if nothing matches we'll DENY and log a warning
}
/**
* add an ISORequestListener
* @param l request listener to be added
* @see ISORequestListener
*/
public void addISORequestListener(ISORequestListener l) {
listeners.add (l);
}
/**
* remove an ISORequestListener
* @param l a request listener to be removed
* @see ISORequestListener
*/
public void removeISORequestListener(ISORequestListener l) {
listeners.remove (l);
}
/**
* Shutdown this server
*/
public void shutdown () {
shutdown = true;
new Thread ("ISOServer-shutdown") {
@Override
public void run () {
shutdownServer ();
if (!cfg.getBoolean ("keep-channels")) {
shutdownChannels ();
}
}
}.start();
}
private void shutdownServer () {
try {
if (serverSocket != null) {
serverSocket.close ();
fireEvent(new ISOServerShutdownEvent(this));
}
if (pool != null) {
pool.close();
}
} catch (IOException e) {
fireEvent(new ISOServerShutdownEvent(this));
Logger.log (new LogEvent (this, "shutdown", e));
}
}
private void shutdownChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null) {
try {
c.disconnect ();
fireEvent(new ISOServerClientDisconnectEvent(this));
} catch (IOException e) {
Logger.log (new LogEvent (this, "shutdown", e));
}
}
}
}
private void purgeChannels () {
Iterator iter = channels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c == null || !c.isConnected()) {
iter.remove ();
}
}
}
@Override
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket();
try {
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(bindAddr, port), backlog);
} catch(SecurityException e) {
ss.close();
fireEvent(new ISOServerShutdownEvent(this));
throw e;
} catch(IOException e) {
ss.close();
fireEvent(new ISOServerShutdownEvent(this));
throw e;
}
return ss;
}
//-----------------------------------------------------------------------------
// -- Helper Session inner class. It's a Runnable, running in its own
// -- thread and handling a connection to this ISOServer
// --
protected Session createSession (ServerChannel channel) {
return new Session (channel);
}
protected class Session implements Runnable, LogSource {
ServerChannel channel;
String realm;
protected Session(ServerChannel channel) {
this.channel = channel;
realm = ISOServer.this.getRealm() + ".session";
}
@Override
public void run() {
setChanged ();
notifyObservers ();
if (channel instanceof BaseChannel) {
LogEvent ev = new LogEvent (this, "session-start");
Socket socket = ((BaseChannel)channel).getSocket ();
realm = realm + "/" + socket.getInetAddress().getHostAddress() + ":"
+ socket.getPort();
try {
checkPermission (socket, ev);
} catch (ISOException e) {
try {
int delay = 1000 + new Random().nextInt (4000);
ev.addMessage (e.getMessage());
ev.addMessage ("delay=" + delay);
ISOUtil.sleep (delay);
socket.close ();
fireEvent(new ISOServerShutdownEvent(ISOServer.this));
} catch (IOException ioe) {
ev.addMessage (ioe);
}
return;
} finally {
Logger.log (ev);
}
}
try {
for (;;) {
try {
ISOMsg m = channel.receive();
lastTxn = System.currentTimeMillis();
Iterator iter = listeners.iterator();
while (iter.hasNext()) {
if (((ISORequestListener)iter.next()).process
(channel, m)) {
break;
}
}
}
catch (ISOFilter.VetoException e) {
Logger.log (new LogEvent (this, "VetoException", e.getMessage()));
}
catch (ISOException e) {
if (ignoreISOExceptions) {
Logger.log (new LogEvent (this, "ISOException", e.getMessage()));
}
else {
throw e;
}
}
}
} catch (EOFException e) {
// Logger.log (new LogEvent (this, "session-warning", "<eof/>"));
} catch (SocketException e) {
// if (!shutdown)
// Logger.log (new LogEvent (this, "session-warning", e));
} catch (InterruptedIOException e) {
// nothing to log
} catch (Throwable e) {
Logger.log (new LogEvent (this, "session-error", e));
}
try {
channel.disconnect();
fireEvent(new ISOServerClientDisconnectEvent(ISOServer.this));
} catch (IOException ex) {
Logger.log (new LogEvent (this, "session-error", ex));
fireEvent(new ISOServerClientDisconnectEvent(ISOServer.this));
}
Logger.log (new LogEvent (this, "session-end"));
}
@Override
public void setLogger (Logger logger, String realm) {
}
@Override
public String getRealm () {
return realm;
}
@Override
public Logger getLogger() {
return ISOServer.this.getLogger();
}
public void checkPermission (Socket socket, LogEvent evt) throws ISOException
{
// if there are no allow/deny params, just return without doing any checks
// (i.e.: "silent allow policy", keeping backward compatibility)
if (specificIPPerms.isEmpty() && wildcardAllow == null && wildcardDeny == null)
return;
String ip= socket.getInetAddress().getHostAddress (); // The remote IP
// first, check allows or denies for specific/whole IPs (no wildcards)
Boolean specificAllow= specificIPPerms.get(ip);
if (specificAllow == Boolean.TRUE) { // specific IP allow
evt.addMessage("access granted, ip=" + ip);
return;
} else if (specificAllow == Boolean.FALSE) { // specific IP deny
throw new ISOException("access denied, ip=" + ip);
} else { // no specific match under the specificIPPerms Map
// We check the wildcard lists, deny first
if (wildcardDeny != null) {
for (String wdeny : wildcardDeny) {
if (ip.startsWith(wdeny)) {
throw new ISOException ("access denied, ip=" + ip);
}
}
}
if (wildcardAllow != null) {
for (String wallow : wildcardAllow) {
if (ip.startsWith(wallow)) {
evt.addMessage("access granted, ip=" + ip);
return;
}
}
}
// Reaching this point means that nothing matched our specific or wildcard rules, so we fall
// back on the default permission policies and log type
switch (ipPermLogPolicy) {
case DENY_LOG: // only allows were specified, default policy is to deny non-matches and log the issue
throw new ISOException ("access denied, ip=" + ip);
// break;
case ALLOW_LOG: // only denies were specified, default policy is to allow non-matches and log the issue
evt.addMessage("access granted, ip=" + ip);
break;
case DENY_LOGWARNING: // mix of allows and denies were specified, but the IP matched no rules!
// so we adopt a deny policy but give a special warning
throw new ISOException ("access denied, ip=" + ip + " (WARNING: the IP did not match any rules!)");
// break;
case ALLOW_NOLOG: // this is the default case when no allow/deny are specified
// the method will abort early on the first "if", so this is here just for completion
break;
}
}
// we should never reach this point!! :-)
}
} // inner class Session
//-------------------------------------------------------------------------------
//-- This is the main run for this ISOServer's Thread
@Override
public void run() {
ServerChannel channel;
if (socketFactory == null) {
socketFactory = this;
}
serverLoop : while (!shutdown) {
try {
serverSocket = socketFactory.createServerSocket(port);
Logger.log (new LogEvent (this, "iso-server",
"listening on " + (bindAddr != null ? bindAddr + ":" : "port ") + port
+ (backlog > 0 ? " backlog="+backlog : "")
));
while (!shutdown) {
try {
if (pool.getAvailableCount() <= 0) {
try {
serverSocket.close();
fireEvent(new ISOServerShutdownEvent(this));
} catch (IOException e){
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
for (int i=0; pool.getIdleCount() == 0; i++) {
if (shutdown) {
break serverLoop;
}
if (i % 240 == 0 && cfg.getBoolean("pool-exhaustion-warning", true)) {
LogEvent evt = new LogEvent (this, "warn");
evt.addMessage (
"pool exhausted " + serverSocket.toString()
);
evt.addMessage (pool);
Logger.log (evt);
}
ISOUtil.sleep (250);
}
serverSocket = socketFactory.createServerSocket(port);
}
channel = (ServerChannel) clientSideChannel.clone();
channel.accept (serverSocket);
if (cnt[CONNECT]++ % 100 == 0) {
purgeChannels ();
}
WeakReference wr = new WeakReference (channel);
channels.put (channel.getName(), wr);
channels.put (LAST, wr);
pool.execute (createSession(channel));
setChanged ();
notifyObservers (this);
fireEvent(new ISOServerAcceptEvent(this));
if (channel instanceof Observable) {
((Observable)channel).addObserver (this);
}
} catch (SocketException e) {
if (!shutdown) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
continue serverLoop;
}
} catch (IOException e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
} // while !shutdown
} catch (Throwable e) {
Logger.log (new LogEvent (this, "iso-server", e));
relax();
}
}
} // ISOServer's run()
//-------------------------------------------------------------------------------
private void relax() {
try {
Thread.sleep (5000);
} catch (InterruptedException e) { }
}
/**
* associates this ISOServer with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
this.name = name;
NameRegistrar.register ("server."+name, this);
}
/**
* @return ISOServer instance with given name.
* @throws NameRegistrar.NotFoundException;
* @see NameRegistrar
*/
public static ISOServer getServer (String name)
throws NameRegistrar.NotFoundException
{
return (ISOServer) NameRegistrar.get ("server."+name);
}
/**
* @return this ISOServer's name ("" if no name was set)
*/
public String getName() {
return this.name;
}
@Override
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
this.realmChannel = realm + ".channel";
}
@Override
public String getRealm () {
return realm;
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public void update(Observable o, Object arg) {
setChanged ();
notifyObservers (arg);
}
/**
* Gets the ISOClientSocketFactory (may be null)
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public ISOServerSocketFactory getSocketFactory() {
return socketFactory;
}
/**
* Sets the specified Socket Factory to create sockets
* @param socketFactory the ISOClientSocketFactory
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public void setSocketFactory(ISOServerSocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
@Override
public int getPort () {
return port;
}
@Override
public void resetCounters () {
cnt = new int[SIZEOF_CNT];
lastTxn = 0l;
}
/**
* @return number of connections accepted by this server
*/
@Override
public int getConnectionCount () {
return cnt[CONNECT];
}
// ThreadPoolMBean implementation (delegate calls to pool)
@Override
public int getJobCount () {
return pool.getJobCount();
}
@Override
public int getPoolSize () {
return pool.getPoolSize();
}
@Override
public int getMaxPoolSize () {
return pool.getMaxPoolSize();
}
@Override
public int getIdleCount() {
return pool.getIdleCount();
}
@Override
public int getPendingCount () {
return pool.getPendingCount();
}
public int getActiveConnections () {
return pool.getActiveCount();
}
/**
* @return most recently connected ISOChannel or null
*/
public ISOChannel getLastConnectedISOChannel () {
return getISOChannel (LAST);
}
/**
* @return ISOChannel under the given name
*/
public ISOChannel getISOChannel (String name) {
WeakReference ref = (WeakReference) channels.get (name);
if (ref != null) {
return (ISOChannel) ref.get ();
}
return null;
}
@Override
public String getISOChannelNames () {
StringBuilder sb = new StringBuilder ();
Iterator iter = channels.entrySet().iterator();
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
if (i > 0) {
sb.append (' ');
}
sb.append (entry.getKey());
}
}
return sb.toString();
}
public String getCountersAsString () {
StringBuilder sb = new StringBuilder ();
int cnt[] = getCounters();
sb.append ("connected=");
sb.append (Integer.toString(cnt[2]));
sb.append (", rx=");
sb.append (Integer.toString(cnt[0]));
sb.append (", tx=");
sb.append (Integer.toString(cnt[1]));
sb.append (", last=");
sb.append (lastTxn);
if (lastTxn > 0) {
sb.append (", idle=");
sb.append(System.currentTimeMillis() - lastTxn);
sb.append ("ms");
}
return sb.toString();
}
public int[] getCounters()
{
Iterator iter = channels.entrySet().iterator();
int[] cnt = new int[3];
cnt[2] = 0;
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected()) {
cnt[2]++;
if (c instanceof BaseChannel) {
int[] cc = ((BaseChannel)c).getCounters();
cnt[0] += cc[ISOChannel.RX];
cnt[1] += cc[ISOChannel.TX];
}
}
}
return cnt;
}
@Override
public int getTXCounter() {
int cnt[] = getCounters();
return cnt[1];
}
@Override
public int getRXCounter() {
int cnt[] = getCounters();
return cnt[0];
}
public int getConnections () {
int cnt[] = getCounters();
return cnt[2];
}
@Override
public long getLastTxnTimestampInMillis() {
return lastTxn;
}
@Override
public long getIdleTimeInMillis() {
return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L;
}
@Override
public String getCountersAsString (String isoChannelName) {
ISOChannel channel = getISOChannel(isoChannelName);
StringBuffer sb = new StringBuffer();
if (channel instanceof BaseChannel) {
int[] counters = ((BaseChannel)channel).getCounters();
append (sb, "rx=", counters[ISOChannel.RX]);
append (sb, ", tx=", counters[ISOChannel.TX]);
append (sb, ", connects=", counters[ISOChannel.CONNECT]);
}
return sb.toString();
}
@Override
public void dump (PrintStream p, String indent) {
p.println (indent + getCountersAsString());
Iterator iter = channels.entrySet().iterator();
String inner = indent + " ";
for (int i=0; iter.hasNext(); i++) {
Map.Entry entry = (Map.Entry) iter.next();
WeakReference ref = (WeakReference) entry.getValue();
ISOChannel c = (ISOChannel) ref.get ();
if (c != null && !LAST.equals (entry.getKey()) && c.isConnected() && c instanceof BaseChannel) {
StringBuilder sb = new StringBuilder ();
int[] cc = ((BaseChannel)c).getCounters();
sb.append (inner);
sb.append (entry.getKey());
sb.append (": rx=");
sb.append (Integer.toString (cc[ISOChannel.RX]));
sb.append (", tx=");
sb.append (Integer.toString (cc[ISOChannel.TX]));
sb.append (", last=");
sb.append (Long.toString(lastTxn));
p.println (sb.toString());
}
}
}
private void append (StringBuffer sb, String name, int value) {
sb.append (name);
sb.append (value);
}
public synchronized void addServerEventListener(ISOServerEventListener listener) {
serverListeners.add(listener);
}
public synchronized void removeServerEventListener(ISOServerEventListener listener) {
serverListeners.remove(listener);
}
public synchronized void fireEvent(EventObject event) {
for (ISOServerEventListener l : serverListeners)
l.handleISOServerEvent(event);
}
}
| ISOServer side effects by bad end user code
Don't want an exception from a handler to exit the loop or
let it bubble up.
If it bubbles up it can cause side effects like getting caught
in the throwable catch leading to server trying to listen on
the same port.
We don't want a side effect in jpos caused by custom user
handler code. | jpos/src/main/java/org/jpos/iso/ISOServer.java | ISOServer side effects by bad end user code | <ide><path>pos/src/main/java/org/jpos/iso/ISOServer.java
<ide> }
<ide>
<ide> public synchronized void fireEvent(EventObject event) {
<del> for (ISOServerEventListener l : serverListeners)
<del> l.handleISOServerEvent(event);
<del> }
<add> for (ISOServerEventListener l : serverListeners) {
<add> try {
<add> l.handleISOServerEvent(event);
<add> }
<add> catch (Exception ignore) {
<add> /*
<add> * Don't want an exception from a handler to exit the loop or
<add> * let it bubble up.
<add> * If it bubbles up it can cause side effects like getting caught
<add> * in the throwable catch leading to server trying to listen on
<add> * the same port.
<add> * We don't want a side effect in jpos caused by custom user
<add> * handler code.
<add> */
<add> }
<add>
<add> }
<add>
<ide> }
<ide> |
|
Java | agpl-3.0 | 9544138622fe52db4b9fced1c04c0ed0a9448102 | 0 | splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine | /*
Derby - Class org.apache.derby.impl.sql.compile.WindowResultSetNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.reference.ClassName;
import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.io.FormatableArrayHolder;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.sql.LanguageFactory;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.iapi.sql.compile.C_NodeTypes;
import org.apache.derby.iapi.sql.compile.CostEstimate;
import org.apache.derby.iapi.sql.compile.Optimizable;
import org.apache.derby.iapi.sql.compile.OptimizablePredicate;
import org.apache.derby.iapi.sql.compile.OptimizablePredicateList;
import org.apache.derby.iapi.sql.compile.Optimizer;
import org.apache.derby.iapi.sql.compile.RequiredRowOrdering;
import org.apache.derby.iapi.sql.compile.RowOrdering;
import org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.impl.sql.execute.AggregatorInfo;
import org.apache.derby.impl.sql.execute.AggregatorInfoList;
/**
* A WindowResultSetNode represents a result set for a window partitioning operation
* on a select. Note that this includes a SELECT with aggregates
* and no grouping columns (in which case the select list is null)
* It has the same description as its input result set.
* <p/>
* For the most part, it simply delegates operations to its bottomPRSet,
* which is currently expected to be a ProjectRestrictResultSet generated
* for a SelectNode.
* <p/>
* NOTE: A WindowResultSetNode extends FromTable since it can exist in a FromList.
* <p/>
* Modelled on the code in GroupByNode.
*/
public class WindowResultSetNode extends SingleChildResultSetNode {
WindowDefinitionNode wdn;
/**
* The Partition clause
*/
Partition partition;
/**
* The list of all window functions in the query block
* that contains this partition.
*/
Vector windowFunctions;
/**
* The list of aggregate nodes we've processed as
* window functions
*/
Vector<AggregateNode> processedAggregates = new Vector<AggregateNode>();
/**
* Information that is used at execution time to
* process aggregates.
*/
private AggregatorInfoList aggInfo;
/**
* The parent to the WindowResultSetNode. We generate a ProjectRestrict
* over the windowing node and parent is set to that node.
*/
FromTable parent;
// Is the source in sorted order
private boolean isInSortedOrder;
/**
* Intializer for a WindowResultSetNode.
*
* @param bottomPR The child FromTable
* @param windowDef The window definition
* @param windowFunctions The vector of aggregates from
* the query block. Since aggregation is done
* at the same time as grouping, we need them
* here.
* @param tableProperties Properties list associated with the table
* @param nestingLevel nestingLevel of this group by node. This is used for
* error checking of group by queries with having clause.
* @throws StandardException Thrown on error
*/
public void init(
Object bottomPR,
Object windowDef,
Object windowFunctions,
Object tableProperties,
Object nestingLevel)
throws StandardException {
super.init(bottomPR, tableProperties);
setLevel(((Integer) nestingLevel).intValue());
/* Group by without aggregates gets xformed into distinct */
if (SanityManager.DEBUG) {
SanityManager.ASSERT(((Vector) windowFunctions).size() > 0,
"windowFunctions expected to be non-empty");
if (!(childResult instanceof Optimizable)) {
SanityManager.THROWASSERT("childResult, " + childResult.getClass().getName() +
", expected to be instanceof Optimizable");
}
if (!(childResult instanceof FromTable)) {
SanityManager.THROWASSERT("childResult, " + childResult.getClass().getName() +
", expected to be instanceof FromTable");
}
}
this.wdn = (WindowDefinitionNode) windowDef;
this.partition = wdn.getPartition();
this.windowFunctions = (Vector) windowFunctions;
this.parent = this;
/*
** The first thing we do is put ourselves on
** top of the SELECT. The select becomes the
** childResult. So our RCL becomes its RCL (so
** nodes above it now point to us). Map our
** RCL to its columns.
*/
ResultColumnList newBottomRCL;
newBottomRCL = childResult.getResultColumns().copyListAndObjects();
resultColumns = childResult.getResultColumns();
childResult.setResultColumns(newBottomRCL);
/*
** We have aggregates, so we need to add
** an extra PRNode and we also have to muck around
** with our trees a might.
*/
addAggregates();
/*
* Check to see if the source is in sorted order on any permutation
* of the grouping columns.
*/
if (partition != null) {
ColumnReference[] crs =
new ColumnReference[this.partition.size()];
// Now populate the CR array and see if ordered
int glSize = this.partition.size();
int index;
for (index = 0; index < glSize; index++) {
GroupByColumn gc = (GroupByColumn) this.partition.elementAt(index);
if (gc.getColumnExpression() instanceof ColumnReference) {
crs[index] = (ColumnReference) gc.getColumnExpression();
} else {
isInSortedOrder = false;
break;
}
}
if (index == glSize) {
isInSortedOrder = childResult.isOrderedOn(crs, true, (Vector) null);
}
}
}
/**
* Get the aggregates that were processed as window function
*
* @return list of aggregates processed as window functions
*/
Vector<AggregateNode> getProcessedAggregates() {
return this.processedAggregates;
}
/**
* Get whether or not the source is in sorted order.
*
* @return Whether or not the source is in sorted order.
*/
boolean getIsInSortedOrder() {
return isInSortedOrder;
}
/**
* Add the extra result columns required by the aggregates
* to the result list.
*
* @throws StandardException
*/
private void addAggregates() throws StandardException {
addNewPRNode();
addNewColumnsForAggregation();
}
/**
* Add a new PR node for aggregation. Put the
* new PR under the sort.
*
* @throws StandardException
*/
private void addNewPRNode() throws StandardException {
/*
** Get the new PR, put above the GroupBy.
*/
ResultColumnList rclNew = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
int sz = resultColumns.size();
for (int i = 0; i < sz; i++) {
ResultColumn rc = (ResultColumn) resultColumns.elementAt(i);
if (!rc.isGenerated()) {
rclNew.addElement(rc);
}
}
// if any columns in the source RCL were generated for an order by
// remember it in the new RCL as well. After the sort is done it will
// have to be projected out upstream.
rclNew.copyOrderBySelect(resultColumns);
parent = (FromTable) getNodeFactory().getNode(
C_NodeTypes.PROJECT_RESTRICT_NODE,
this, // child
rclNew,
null, //havingClause,
null, // restriction list
null, // project subqueries
null, // having subqueries
tableProperties,
getContextManager());
/*
** Reset the bottom RCL to be empty.
*/
childResult.setResultColumns((ResultColumnList)
getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager()));
/*
* Set the Windowing RCL to be empty
*/
resultColumns = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
}
/**
* In the query rewrite for partition, add the columns on which we are doing
* the partition.
*
* @see #addNewColumnsForAggregation
*/
private void addUnAggColumns() throws StandardException {
ResultColumnList bottomRCL = childResult.getResultColumns();
ResultColumnList groupByRCL = resultColumns;
ArrayList referencesToSubstitute = new ArrayList();
int sz = partition.size();
for (int i = 0; i < sz; i++) {
GroupByColumn gbc = (GroupByColumn) partition.elementAt(i);
ResultColumn newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##PartitionColumn",
gbc.getColumnExpression(),
getContextManager());
// add this result column to the bottom rcl
bottomRCL.addElement(newRC);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
newRC.setVirtualColumnId(bottomRCL.size());
// now add this column to the groupbylist
ResultColumn gbRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##PartitionColumn",
gbc.getColumnExpression(),
getContextManager());
groupByRCL.addElement(gbRC);
gbRC.markGenerated();
gbRC.bindResultColumnToExpression();
gbRC.setVirtualColumnId(groupByRCL.size());
/*
** Reset the original node to point to the
** Group By result set.
*/
VirtualColumnNode vc = (VirtualColumnNode) getNodeFactory().getNode(
C_NodeTypes.VIRTUAL_COLUMN_NODE,
this, // source result set.
gbRC,
new Integer(groupByRCL.size()),
getContextManager());
// we replace each group by expression
// in the projection list with a virtual column node
// that effectively points to a result column
// in the result set doing the group by
//
// Note that we don't perform the replacements
// immediately, but instead we accumulate them
// until the end of the loop. This allows us to
// sort the expressions and process them in
// descending order of complexity, necessary
// because a compound expression may contain a
// reference to a simple grouped column, but in
// such a case we want to process the expression
// as an expression, not as individual column
// references. E.g., if the statement was:
// SELECT ... GROUP BY C1, C1 * (C2 / 100), C3
// then we don't want the replacement of the
// simple column reference C1 to affect the
// compound expression C1 * (C2 / 100). DERBY-3094.
//
ValueNode vn = gbc.getColumnExpression();
SubstituteExpressionVisitor vis =
new SubstituteExpressionVisitor(vn, vc,
AggregateNode.class);
referencesToSubstitute.add(vis);
// Since we always need a PR node on top of the GB
// node to perform projection we can use it to perform
// the having clause restriction as well.
// To evaluate the having clause correctly, we need to
// convert each aggregate and expression to point
// to the appropriate result column in the group by node.
// This is no different from the transformations we do to
// correctly evaluate aggregates and expressions in the
// projection list.
//
//
// For this query:
// SELECT c1, SUM(c2), MAX(c3)
// FROM t1
// HAVING c1+max(c3) > 0;
// PRSN RCL -> (ptr(gbn:rcl[0]), ptr(gbn:rcl[1]), ptr(gbn:rcl[4]))
// Restriction: (> (+ ptr(gbn:rcl[0]) ptr(gbn:rcl[4])) 0)
// |
// GBN (RCL) -> (C1, SUM(C2), <input>, <aggregator>, MAX(C3), <input>, <aggregator>
// |
// FBT (C1, C2)
gbc.setColumnPosition(bottomRCL.size());
}
Comparator sorter = new ExpressionSorter();
Collections.sort(referencesToSubstitute, sorter);
for (int r = 0; r < referencesToSubstitute.size(); r++)
parent.getResultColumns().accept(
(SubstituteExpressionVisitor) referencesToSubstitute.get(r));
}
/**
* Add a whole slew of columns needed for
* aggregation. Basically, for each aggregate we add
* 3 columns: the aggregate input expression
* and the aggregator column and a column where the aggregate
* result is stored. The input expression is
* taken directly from the aggregator node. The aggregator
* is the run time aggregator. We add it to the RC list
* as a new object coming into the sort node.
* <p/>
* At this point this is invoked, we have the following
* tree: <UL>
* PR - (PARENT): RCL is the original select list
* |
* PR - GROUP BY: RCL is empty
* |
* PR - FROM TABLE: RCL is empty </UL> <P>
* <p/>
* For each ColumnReference in PR RCL <UL>
* <LI> clone the ref </LI>
* <LI> create a new RC in the bottom RCL and set it
* to the col ref </LI>
* <LI> create a new RC in the GROUPBY RCL and set it to
* point to the bottom RC </LI>
* <LI> reset the top PR ref to point to the new GROUPBY
* RC</LI></UL>
* <p/>
* For each aggregate in windowFunctions <UL>
* <LI> create RC in FROM TABLE. Fill it with
* aggs Operator.
* <LI> create RC in FROM TABLE for agg result</LI>
* <LI> create RC in FROM TABLE for aggregator</LI>
* <LI> create RC in GROUPBY for agg input, set it
* to point to FROM TABLE RC </LI>
* <LI> create RC in GROUPBY for agg result</LI>
* <LI> create RC in GROUPBY for aggregator</LI>
* <LI> replace Agg with reference to RC for agg result </LI></UL>.
* <p/>
* For a query like,
* <pre>
* select c1, sum(c2), max(c3)
* from t1
* group by c1;
* </pre>
* the query tree ends up looking like this:
* <pre>
* ProjectRestrictNode RCL -> (ptr to GBN(column[0]), ptr to GBN(column[1]), ptr to GBN(column[4]))
* |
* GroupByNode RCL->(C1, SUM(C2), <agg-input>, <aggregator>, MAX(C3), <agg-input>, <aggregator>)
* |
* ProjectRestrict RCL->(C1, C2, C3)
* |
* FromBaseTable
* </pre>
* <p/>
* The RCL of the GroupByNode contains all the unagg (or grouping columns)
* followed by 3 RC's for each aggregate in this order: the final computed
* aggregate value, the aggregate input and the aggregator function.
* <p/>
* The Aggregator function puts the results in the first of the 3 RC's
* and the PR resultset in turn picks up the value from there.
* <p/>
* The notation (ptr to GBN(column[0])) basically means that it is
* a pointer to the 0th RC in the RCL of the GroupByNode.
* <p/>
* The addition of these unagg and agg columns to the GroupByNode and
* to the PRN is performed in addUnAggColumns and addAggregateColumns.
* <p/>
* Note that that addition of the GroupByNode is done after the
* query is optimized (in SelectNode#modifyAccessPaths) which means a
* fair amount of patching up is needed to account for generated group by columns.
*
* @throws StandardException
*/
private void addNewColumnsForAggregation()
throws StandardException {
aggInfo = new AggregatorInfoList();
ArrayList havingRefsToSubstitute = null;
addUnAggColumns();
addAggregateColumns();
}
/**
* In the query rewrite involving aggregates, add the columns for
* aggregation.
*
* @see #addNewColumnsForAggregation
*/
private void addAggregateColumns() throws StandardException {
DataDictionary dd = getDataDictionary();
WindowFunctionNode aggregate = null;
ColumnReference newColumnRef;
ResultColumn newRC;
ResultColumn tmpRC;
ResultColumn aggResultRC;
ResultColumnList bottomRCL = childResult.getResultColumns();
ResultColumnList groupByRCL = resultColumns;
ResultColumnList aggRCL;
int aggregatorVColId;
int aggInputVColId;
int aggResultVColId;
/*
** Now process all of the aggregates. Replace
** every aggregate with an RC. We toss out
** the list of RCs, we need to get each RC
** as we process its corresponding aggregate.
*/
LanguageFactory lf = getLanguageConnectionContext().getLanguageFactory();
ReplaceAggregatesWithCRVisitor replaceAggsVisitor =
new ReplaceAggregatesWithCRVisitor(
(ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager()),
((FromTable) childResult).getTableNumber(),
ResultSetNode.class);
parent.getResultColumns().accept(replaceAggsVisitor);
/*
** For each aggregate
*/
int alSize = windowFunctions.size();
for (int index = 0; index < alSize; index++) {
aggregate = (WindowFunctionNode) windowFunctions.get(index);
/*
** AGG RESULT: Set the aggregate result to null in the
** bottom project restrict.
*/
newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##WindowResult",
aggregate.getNewNullResultExpression(),
getContextManager());
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggResultVColId = newRC.getVirtualColumnId();
/*
** Set the GB aggregate result column to
** point to this. The GB aggregate result
** was created when we called
** ReplaceAggregatesWithCRVisitor()
*/
newColumnRef = (ColumnReference) getNodeFactory().getNode(
C_NodeTypes.COLUMN_REFERENCE,
newRC.getName(),
null,
getContextManager());
newColumnRef.setSource(newRC);
newColumnRef.setNestingLevel(this.getLevel());
newColumnRef.setSourceLevel(this.getLevel());
tmpRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
newRC.getColumnName(),
newColumnRef,
getContextManager());
tmpRC.markGenerated();
tmpRC.bindResultColumnToExpression();
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** Set the column reference to point to
** this.
*/
newColumnRef = aggregate.getGeneratedRef();
newColumnRef.setSource(tmpRC);
/*
** AGG INPUT: Create a ResultColumn in the bottom
** project restrict that has the expression that is
** to be aggregated
*/
newRC = aggregate.getNewExpressionResultColumn(dd);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggInputVColId = newRC.getVirtualColumnId();
aggResultRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##WindowExpression",
aggregate.getNewNullResultExpression(),
getContextManager());
/*
** Add a reference to this column into the
** group by columns.
*/
tmpRC = getColumnReference(newRC, dd);
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** AGGREGATOR: Add a getAggregator method call
** to the bottom result column list.
*/
newRC = aggregate.getNewAggregatorResultColumn(dd);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggregatorVColId = newRC.getVirtualColumnId();
/*
** Add a reference to this column in the Group By result
** set.
*/
tmpRC = getColumnReference(newRC, dd);
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** Piece together a fake one column rcl that we will use
** to generate a proper result description for input
** to this agg if it is a user agg.
*/
aggRCL = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
aggRCL.addElement(aggResultRC);
/*
** Note that the column ids in the row are 0 based
** so we have to subtract 1.
*/
aggInfo.addElement(new AggregatorInfo(
aggregate.getAggregateName(),
aggregate.getAggregatorClassName(),
aggInputVColId - 1, // aggregate input column
aggResultVColId - 1, // the aggregate result column
aggregatorVColId - 1, // the aggregator column
aggregate.isDistinct(),
lf.getResultDescription(aggRCL.makeResultDescriptors(), "SELECT")
));
this.processedAggregates.add(aggregate.getWrappedAggregate());
}
}
/**
* Return the parent node to this one, if there is
* one. It will return 'this' if there is no generated
* node above this one.
*
* @return the parent node
*/
public FromTable getParent() {
return parent;
}
/*
* Optimizable interface
*/
/**
* @throws StandardException Thrown on error
* @see Optimizable#optimizeIt
*/
public CostEstimate optimizeIt(
Optimizer optimizer,
OptimizablePredicateList predList,
CostEstimate outerCost,
RowOrdering rowOrdering)
throws StandardException {
// RESOLVE: NEED TO FACTOR IN THE COST OF GROUPING (SORTING) HERE
CostEstimate childCost = ((Optimizable) childResult).optimizeIt(
optimizer,
predList,
outerCost,
rowOrdering);
CostEstimate retval = super.optimizeIt(
optimizer,
predList,
outerCost,
rowOrdering
);
return retval;
}
/**
* @throws StandardException Thrown on error
* @see Optimizable#estimateCost
*/
public CostEstimate estimateCost(OptimizablePredicateList predList,
ConglomerateDescriptor cd,
CostEstimate outerCost,
Optimizer optimizer,
RowOrdering rowOrdering
)
throws StandardException {
// RESOLVE: NEED TO FACTOR IN THE COST OF GROUPING (SORTING) HERE
//
CostEstimate childCost = ((Optimizable) childResult).estimateCost(
predList,
cd,
outerCost,
optimizer,
rowOrdering);
CostEstimate costEstimate = getCostEstimate(optimizer);
costEstimate.setCost(childCost.getEstimatedCost(),
childCost.rowCount(),
childCost.singleScanRowCount());
return costEstimate;
}
/**
* @throws StandardException Thrown on error
* @see org.apache.derby.iapi.sql.compile.Optimizable#pushOptPredicate
*/
public boolean pushOptPredicate(OptimizablePredicate optimizablePredicate)
throws StandardException {
return ((Optimizable) childResult).pushOptPredicate(optimizablePredicate);
}
/**
* Convert this object to a String. See comments in QueryTreeNode.java
* for how this should be done for tree printing.
*
* @return This object as a String
*/
public String toString() {
if (SanityManager.DEBUG) {
return wdn.toString()+ "\n" + super.toString();
} else {
return "";
}
}
/**
* Prints the sub-nodes of this object. See QueryTreeNode.java for
* how tree printing is supposed to work.
*
* @param depth The depth of this node in the tree
*/
public void printSubNodes(int depth) {
if (SanityManager.DEBUG) {
super.printSubNodes(depth);
printLabel(depth, "windowFunctions:\n");
for (int i = 0; i < windowFunctions.size(); i++) {
AggregateNode agg =
(AggregateNode) windowFunctions.get(i);
debugPrint(formatNodeString("[" + i + "]:", depth + 1));
agg.treePrint(depth + 1);
}
printLabel(depth, "windowDefintionNode: ");
wdn.treePrint(depth + 1);
}
}
/**
* Evaluate whether or not the subquery in a FromSubquery is flattenable.
* Currently, a FSqry is flattenable if all of the following are true:
* o Subquery is a SelectNode.
* o It contains no top level subqueries. (RESOLVE - we can relax this)
* o It does not contain a group by or having clause
* o It does not contain aggregates.
*
* @param fromList The outer from list
* @return boolean Whether or not the FromSubquery is flattenable.
*/
public boolean flattenableInFromSubquery(FromList fromList) {
/* Can't flatten a WindowResultSetNode */
return false;
}
/**
* Optimize this WindowResultSetNode.
*
* @param dataDictionary The DataDictionary to use for optimization
* @param predicates The PredicateList to optimize. This should
* be a join predicate.
* @param outerRows The number of outer joining rows
* @throws StandardException Thrown on error
* @return ResultSetNode The top of the optimized subtree
*/
public ResultSetNode optimize(DataDictionary dataDictionary,
PredicateList predicates,
double outerRows)
throws StandardException {
/* We need to implement this method since a PRN can appear above a
* SelectNode in a query tree.
*/
childResult = (ResultSetNode) childResult.optimize(
dataDictionary,
predicates,
outerRows);
Optimizer optimizer = getOptimizer(
(FromList) getNodeFactory().getNode(
C_NodeTypes.FROM_LIST,
getNodeFactory().doJoinOrderOptimization(),
getContextManager()),
predicates,
dataDictionary,
(RequiredRowOrdering) null);
// RESOLVE: NEED TO FACTOR IN COST OF SORTING AND FIGURE OUT HOW
// MANY ROWS HAVE BEEN ELIMINATED.
costEstimate = optimizer.newCostEstimate();
costEstimate.setCost(childResult.getCostEstimate().getEstimatedCost(),
childResult.getCostEstimate().rowCount(),
childResult.getCostEstimate().singleScanRowCount());
return this;
}
ResultColumnDescriptor[] makeResultDescriptors() {
return childResult.makeResultDescriptors();
}
/**
* Return whether or not the underlying ResultSet tree will return
* a single row, at most.
* This is important for join nodes where we can save the extra next
* on the right side if we know that it will return at most 1 row.
*
* @return Whether or not the underlying ResultSet tree will return a single row.
* @throws StandardException Thrown on error
*/
public boolean isOneRowResultSet() throws StandardException {
// Only consider scalar aggregates for now
return ((partition == null) || (partition.size() == 0));
}
/**
* generate the sort result set operating over the source
* resultset. Adds distinct aggregates to the sort if
* necessary.
*
* @throws StandardException Thrown on error
*/
public void generate(ActivationClassBuilder acb,
MethodBuilder mb)
throws StandardException {
int orderingItem = 0;
int aggInfoItem = 0;
FormatableArrayHolder orderingHolder;
/* Get the next ResultSet#, so we can number this ResultSetNode, its
* ResultColumnList and ResultSet.
*/
assignResultSetNumber();
// Get the final cost estimate from the child.
costEstimate = childResult.getFinalCostEstimate();
/*
** Get the column ordering for the sort from orderby list.
* getColumnOrdering does the right thing if orderby list is null empty.
*/
orderingHolder = acb.getColumnOrdering(wdn.getOrderByList());
if (SanityManager.DEBUG) {
if (SanityManager.DEBUG_ON("WindowTrace")) {
StringBuilder s = new StringBuilder();
s.append("Partition column ordering is (");
org.apache.derby.iapi.store.access.ColumnOrdering[] ordering =
(org.apache.derby.iapi.store.access.ColumnOrdering[]) orderingHolder.getArray(org.apache.derby
.iapi.store
.access
.ColumnOrdering
.class);
for (int i = 0; i < ordering.length; i++) {
s.append(ordering[i].getColumnId());
s.append(" ");
}
s.append(")");
SanityManager.DEBUG("WindowTrace", s.toString());
}
}
orderingItem = acb.addItem(orderingHolder);
/*
** We have aggregates, so save the aggInfo
** struct in the activation and store the number
*/
if (SanityManager.DEBUG) {
SanityManager.ASSERT(aggInfo != null,
"aggInfo not set up as expected");
}
aggInfoItem = acb.addItem(aggInfo);
acb.pushGetResultSetFactoryExpression(mb);
/* Generate the WindowResultSet:
* arg1: childExpress - Expression for childResult
* arg2: isInSortedOrder - true if source result set in sorted order
* arg3: aggInfoItem - entry in saved objects for the aggregates,
* arg4: orderingItem - entry in saved objects for the ordering
* arg5: Activation
* arg6: rowAllocator - method to construct rows for fetching
* from the sort
* arg7: row size
* arg8: resultSetNumber
*/
// Generate the child ResultSet
childResult.generate(acb, mb);
mb.push(isInSortedOrder);
mb.push(aggInfoItem);
mb.push(orderingItem);
resultColumns.generateHolder(acb, mb);
mb.push(resultColumns.getTotalColumnSize());
mb.push(resultSetNumber);
mb.push(costEstimate.rowCount());
mb.push(costEstimate.getEstimatedCost());
mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getWindowResultSet",
ClassName.NoPutResultSet, 9);
}
///////////////////////////////////////////////////////////////
//
// UTILITIES
//
///////////////////////////////////////////////////////////////
/**
* Method for creating a new result column referencing
* the one passed in.
*
* @return the new result column
* @throws StandardException on error
* @param targetRC the source
* @param dd
*/
private ResultColumn getColumnReference(ResultColumn targetRC,
DataDictionary dd)
throws StandardException {
ColumnReference tmpColumnRef;
ResultColumn newRC;
tmpColumnRef = (ColumnReference) getNodeFactory().getNode(
C_NodeTypes.COLUMN_REFERENCE,
targetRC.getName(),
null,
getContextManager());
tmpColumnRef.setSource(targetRC);
tmpColumnRef.setNestingLevel(this.getLevel());
tmpColumnRef.setSourceLevel(this.getLevel());
newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
targetRC.getColumnName(),
tmpColumnRef,
getContextManager());
newRC.markGenerated();
newRC.bindResultColumnToExpression();
return newRC;
}
/**
* Comparator class for GROUP BY expression substitution.
* <p/>
* This class enables the sorting of a collection of
* SubstituteExpressionVisitor instances. We sort the visitors
* during the tree manipulation processing in order to process
* expressions of higher complexity prior to expressions of
* lower complexity. Processing the expressions in this order ensures
* that we choose the best match for an expression, and thus avoids
* problems where we substitute a sub-expression instead of the
* full expression. For example, if the statement is:
* ... GROUP BY a+b, a, a*(a+b), a+b+c
* we'll process those expressions in the order: a*(a+b),
* a+b+c, a+b, then a.
*/
private static final class ExpressionSorter implements Comparator {
public int compare(Object o1, Object o2) {
try {
ValueNode v1 = ((SubstituteExpressionVisitor) o1).getSource();
ValueNode v2 = ((SubstituteExpressionVisitor) o2).getSource();
int refCount1, refCount2;
CollectNodesVisitor vis = new CollectNodesVisitor(
ColumnReference.class);
v1.accept(vis);
refCount1 = vis.getList().size();
vis = new CollectNodesVisitor(ColumnReference.class);
v2.accept(vis);
refCount2 = vis.getList().size();
// The ValueNode with the larger number of refs
// should compare lower. That way we are sorting
// the expressions in descending order of complexity.
return refCount2 - refCount1;
} catch (StandardException e) {
throw new RuntimeException(e);
}
}
}
}
| java/engine/org/apache/derby/impl/sql/compile/WindowResultSetNode.java | /*
Derby - Class org.apache.derby.impl.sql.compile.WindowResultSetNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.reference.ClassName;
import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.io.FormatableArrayHolder;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.sql.LanguageFactory;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.iapi.sql.compile.C_NodeTypes;
import org.apache.derby.iapi.sql.compile.CostEstimate;
import org.apache.derby.iapi.sql.compile.Optimizable;
import org.apache.derby.iapi.sql.compile.OptimizablePredicate;
import org.apache.derby.iapi.sql.compile.OptimizablePredicateList;
import org.apache.derby.iapi.sql.compile.Optimizer;
import org.apache.derby.iapi.sql.compile.RequiredRowOrdering;
import org.apache.derby.iapi.sql.compile.RowOrdering;
import org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.impl.sql.execute.AggregatorInfo;
import org.apache.derby.impl.sql.execute.AggregatorInfoList;
/**
* A WindowResultSetNode represents a result set for a window partitioning operation
* on a select. Note that this includes a SELECT with aggregates
* and no grouping columns (in which case the select list is null)
* It has the same description as its input result set.
* <p/>
* For the most part, it simply delegates operations to its bottomPRSet,
* which is currently expected to be a ProjectRestrictResultSet generated
* for a SelectNode.
* <p/>
* NOTE: A WindowResultSetNode extends FromTable since it can exist in a FromList.
* <p/>
* Modelled on the code in GroupByNode.
*/
public class WindowResultSetNode extends SingleChildResultSetNode {
WindowDefinitionNode wdn;
/**
* The Partition clause
*/
Partition partition;
/**
* The list of all window functions in the query block
* that contains this partition.
*/
Vector windowFunctions;
/**
* The list of aggregate nodes we've processed as
* window functions
*/
Vector<AggregateNode> processedAggregates = new Vector<AggregateNode>();
/**
* Information that is used at execution time to
* process aggregates.
*/
private AggregatorInfoList aggInfo;
/**
* The parent to the WindowResultSetNode. We generate a ProjectRestrict
* over the windowing node and parent is set to that node.
*/
FromTable parent;
// Is the source in sorted order
private boolean isInSortedOrder;
/**
* Intializer for a WindowResultSetNode.
*
* @param bottomPR The child FromTable
* @param windowDef The window definition
* @param windowFunctions The vector of aggregates from
* the query block. Since aggregation is done
* at the same time as grouping, we need them
* here.
* @param tableProperties Properties list associated with the table
* @param nestingLevel nestingLevel of this group by node. This is used for
* error checking of group by queries with having clause.
* @throws StandardException Thrown on error
*/
public void init(
Object bottomPR,
Object windowDef,
Object windowFunctions,
Object tableProperties,
Object nestingLevel)
throws StandardException {
super.init(bottomPR, tableProperties);
setLevel(((Integer) nestingLevel).intValue());
/* Group by without aggregates gets xformed into distinct */
if (SanityManager.DEBUG) {
SanityManager.ASSERT(((Vector) windowFunctions).size() > 0,
"windowFunctions expected to be non-empty");
if (!(childResult instanceof Optimizable)) {
SanityManager.THROWASSERT("childResult, " + childResult.getClass().getName() +
", expected to be instanceof Optimizable");
}
if (!(childResult instanceof FromTable)) {
SanityManager.THROWASSERT("childResult, " + childResult.getClass().getName() +
", expected to be instanceof FromTable");
}
}
this.wdn = (WindowDefinitionNode) windowDef;
this.partition = wdn.getPartition();
this.windowFunctions = (Vector) windowFunctions;
this.parent = this;
/*
** The first thing we do is put ourselves on
** top of the SELECT. The select becomes the
** childResult. So our RCL becomes its RCL (so
** nodes above it now point to us). Map our
** RCL to its columns.
*/
ResultColumnList newBottomRCL;
newBottomRCL = childResult.getResultColumns().copyListAndObjects();
resultColumns = childResult.getResultColumns();
childResult.setResultColumns(newBottomRCL);
/*
** We have aggregates, so we need to add
** an extra PRNode and we also have to muck around
** with our trees a might.
*/
addAggregates();
/*
* Check to see if the source is in sorted order on any permutation
* of the grouping columns.
*/
if (partition != null) {
ColumnReference[] crs =
new ColumnReference[this.partition.size()];
// Now populate the CR array and see if ordered
int glSize = this.partition.size();
int index;
for (index = 0; index < glSize; index++) {
GroupByColumn gc = (GroupByColumn) this.partition.elementAt(index);
if (gc.getColumnExpression() instanceof ColumnReference) {
crs[index] = (ColumnReference) gc.getColumnExpression();
} else {
isInSortedOrder = false;
break;
}
}
if (index == glSize) {
isInSortedOrder = childResult.isOrderedOn(crs, true, (Vector) null);
}
}
}
/**
* Get the aggregates that were processed as window function
*
* @return list of aggregates processed as window functions
*/
Vector<AggregateNode> getProcessedAggregates() {
return this.processedAggregates;
}
/**
* Get whether or not the source is in sorted order.
*
* @return Whether or not the source is in sorted order.
*/
boolean getIsInSortedOrder() {
return isInSortedOrder;
}
/**
* Add the extra result columns required by the aggregates
* to the result list.
*
* @throws StandardException
*/
private void addAggregates() throws StandardException {
addNewPRNode();
addNewColumnsForAggregation();
}
/**
* Add a new PR node for aggregation. Put the
* new PR under the sort.
*
* @throws StandardException
*/
private void addNewPRNode() throws StandardException {
/*
** Get the new PR, put above the GroupBy.
*/
ResultColumnList rclNew = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
int sz = resultColumns.size();
for (int i = 0; i < sz; i++) {
ResultColumn rc = (ResultColumn) resultColumns.elementAt(i);
if (!rc.isGenerated()) {
rclNew.addElement(rc);
}
}
// if any columns in the source RCL were generated for an order by
// remember it in the new RCL as well. After the sort is done it will
// have to be projected out upstream.
rclNew.copyOrderBySelect(resultColumns);
parent = (FromTable) getNodeFactory().getNode(
C_NodeTypes.PROJECT_RESTRICT_NODE,
this, // child
rclNew,
null, //havingClause,
null, // restriction list
null, // project subqueries
null, // having subqueries
tableProperties,
getContextManager());
/*
** Reset the bottom RCL to be empty.
*/
childResult.setResultColumns((ResultColumnList)
getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager()));
/*
* Set the Windowing RCL to be empty
*/
resultColumns = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
}
/**
* In the query rewrite for partition, add the columns on which we are doing
* the partition.
*
* @see #addNewColumnsForAggregation
*/
private void addUnAggColumns() throws StandardException {
ResultColumnList bottomRCL = childResult.getResultColumns();
ResultColumnList groupByRCL = resultColumns;
ArrayList referencesToSubstitute = new ArrayList();
int sz = partition.size();
for (int i = 0; i < sz; i++) {
GroupByColumn gbc = (GroupByColumn) partition.elementAt(i);
ResultColumn newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##PartitionColumn",
gbc.getColumnExpression(),
getContextManager());
// add this result column to the bottom rcl
bottomRCL.addElement(newRC);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
newRC.setVirtualColumnId(bottomRCL.size());
// now add this column to the groupbylist
ResultColumn gbRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##PartitionColumn",
gbc.getColumnExpression(),
getContextManager());
groupByRCL.addElement(gbRC);
gbRC.markGenerated();
gbRC.bindResultColumnToExpression();
gbRC.setVirtualColumnId(groupByRCL.size());
/*
** Reset the original node to point to the
** Group By result set.
*/
VirtualColumnNode vc = (VirtualColumnNode) getNodeFactory().getNode(
C_NodeTypes.VIRTUAL_COLUMN_NODE,
this, // source result set.
gbRC,
new Integer(groupByRCL.size()),
getContextManager());
// we replace each group by expression
// in the projection list with a virtual column node
// that effectively points to a result column
// in the result set doing the group by
//
// Note that we don't perform the replacements
// immediately, but instead we accumulate them
// until the end of the loop. This allows us to
// sort the expressions and process them in
// descending order of complexity, necessary
// because a compound expression may contain a
// reference to a simple grouped column, but in
// such a case we want to process the expression
// as an expression, not as individual column
// references. E.g., if the statement was:
// SELECT ... GROUP BY C1, C1 * (C2 / 100), C3
// then we don't want the replacement of the
// simple column reference C1 to affect the
// compound expression C1 * (C2 / 100). DERBY-3094.
//
ValueNode vn = gbc.getColumnExpression();
SubstituteExpressionVisitor vis =
new SubstituteExpressionVisitor(vn, vc,
AggregateNode.class);
referencesToSubstitute.add(vis);
// Since we always need a PR node on top of the GB
// node to perform projection we can use it to perform
// the having clause restriction as well.
// To evaluate the having clause correctly, we need to
// convert each aggregate and expression to point
// to the appropriate result column in the group by node.
// This is no different from the transformations we do to
// correctly evaluate aggregates and expressions in the
// projection list.
//
//
// For this query:
// SELECT c1, SUM(c2), MAX(c3)
// FROM t1
// HAVING c1+max(c3) > 0;
// PRSN RCL -> (ptr(gbn:rcl[0]), ptr(gbn:rcl[1]), ptr(gbn:rcl[4]))
// Restriction: (> (+ ptr(gbn:rcl[0]) ptr(gbn:rcl[4])) 0)
// |
// GBN (RCL) -> (C1, SUM(C2), <input>, <aggregator>, MAX(C3), <input>, <aggregator>
// |
// FBT (C1, C2)
gbc.setColumnPosition(bottomRCL.size());
}
Comparator sorter = new ExpressionSorter();
Collections.sort(referencesToSubstitute, sorter);
for (int r = 0; r < referencesToSubstitute.size(); r++)
parent.getResultColumns().accept(
(SubstituteExpressionVisitor) referencesToSubstitute.get(r));
}
/**
* Add a whole slew of columns needed for
* aggregation. Basically, for each aggregate we add
* 3 columns: the aggregate input expression
* and the aggregator column and a column where the aggregate
* result is stored. The input expression is
* taken directly from the aggregator node. The aggregator
* is the run time aggregator. We add it to the RC list
* as a new object coming into the sort node.
* <p/>
* At this point this is invoked, we have the following
* tree: <UL>
* PR - (PARENT): RCL is the original select list
* |
* PR - GROUP BY: RCL is empty
* |
* PR - FROM TABLE: RCL is empty </UL> <P>
* <p/>
* For each ColumnReference in PR RCL <UL>
* <LI> clone the ref </LI>
* <LI> create a new RC in the bottom RCL and set it
* to the col ref </LI>
* <LI> create a new RC in the GROUPBY RCL and set it to
* point to the bottom RC </LI>
* <LI> reset the top PR ref to point to the new GROUPBY
* RC</LI></UL>
* <p/>
* For each aggregate in windowFunctions <UL>
* <LI> create RC in FROM TABLE. Fill it with
* aggs Operator.
* <LI> create RC in FROM TABLE for agg result</LI>
* <LI> create RC in FROM TABLE for aggregator</LI>
* <LI> create RC in GROUPBY for agg input, set it
* to point to FROM TABLE RC </LI>
* <LI> create RC in GROUPBY for agg result</LI>
* <LI> create RC in GROUPBY for aggregator</LI>
* <LI> replace Agg with reference to RC for agg result </LI></UL>.
* <p/>
* For a query like,
* <pre>
* select c1, sum(c2), max(c3)
* from t1
* group by c1;
* </pre>
* the query tree ends up looking like this:
* <pre>
* ProjectRestrictNode RCL -> (ptr to GBN(column[0]), ptr to GBN(column[1]), ptr to GBN(column[4]))
* |
* GroupByNode RCL->(C1, SUM(C2), <agg-input>, <aggregator>, MAX(C3), <agg-input>, <aggregator>)
* |
* ProjectRestrict RCL->(C1, C2, C3)
* |
* FromBaseTable
* </pre>
* <p/>
* The RCL of the GroupByNode contains all the unagg (or grouping columns)
* followed by 3 RC's for each aggregate in this order: the final computed
* aggregate value, the aggregate input and the aggregator function.
* <p/>
* The Aggregator function puts the results in the first of the 3 RC's
* and the PR resultset in turn picks up the value from there.
* <p/>
* The notation (ptr to GBN(column[0])) basically means that it is
* a pointer to the 0th RC in the RCL of the GroupByNode.
* <p/>
* The addition of these unagg and agg columns to the GroupByNode and
* to the PRN is performed in addUnAggColumns and addAggregateColumns.
* <p/>
* Note that that addition of the GroupByNode is done after the
* query is optimized (in SelectNode#modifyAccessPaths) which means a
* fair amount of patching up is needed to account for generated group by columns.
*
* @throws StandardException
*/
private void addNewColumnsForAggregation()
throws StandardException {
aggInfo = new AggregatorInfoList();
ArrayList havingRefsToSubstitute = null;
addUnAggColumns();
addAggregateColumns();
}
/**
* In the query rewrite involving aggregates, add the columns for
* aggregation.
*
* @see #addNewColumnsForAggregation
*/
private void addAggregateColumns() throws StandardException {
DataDictionary dd = getDataDictionary();
WindowFunctionNode aggregate = null;
ColumnReference newColumnRef;
ResultColumn newRC;
ResultColumn tmpRC;
ResultColumn aggResultRC;
ResultColumnList bottomRCL = childResult.getResultColumns();
ResultColumnList groupByRCL = resultColumns;
ResultColumnList aggRCL;
int aggregatorVColId;
int aggInputVColId;
int aggResultVColId;
/*
** Now process all of the aggregates. Replace
** every aggregate with an RC. We toss out
** the list of RCs, we need to get each RC
** as we process its corresponding aggregate.
*/
LanguageFactory lf = getLanguageConnectionContext().getLanguageFactory();
ReplaceAggregatesWithCRVisitor replaceAggsVisitor =
new ReplaceAggregatesWithCRVisitor(
(ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager()),
((FromTable) childResult).getTableNumber(),
ResultSetNode.class);
parent.getResultColumns().accept(replaceAggsVisitor);
/*
** For each aggregate
*/
int alSize = windowFunctions.size();
for (int index = 0; index < alSize; index++) {
aggregate = (WindowFunctionNode) windowFunctions.get(index);
/*
** AGG RESULT: Set the aggregate result to null in the
** bottom project restrict.
*/
newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##WindowResult",
aggregate.getNewNullResultExpression(),
getContextManager());
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggResultVColId = newRC.getVirtualColumnId();
/*
** Set the GB aggregate result column to
** point to this. The GB aggregate result
** was created when we called
** ReplaceAggregatesWithCRVisitor()
*/
newColumnRef = (ColumnReference) getNodeFactory().getNode(
C_NodeTypes.COLUMN_REFERENCE,
newRC.getName(),
null,
getContextManager());
newColumnRef.setSource(newRC);
newColumnRef.setNestingLevel(this.getLevel());
newColumnRef.setSourceLevel(this.getLevel());
tmpRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
newRC.getColumnName(),
newColumnRef,
getContextManager());
tmpRC.markGenerated();
tmpRC.bindResultColumnToExpression();
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** Set the column reference to point to
** this.
*/
newColumnRef = aggregate.getGeneratedRef();
newColumnRef.setSource(tmpRC);
/*
** AGG INPUT: Create a ResultColumn in the bottom
** project restrict that has the expression that is
** to be aggregated
*/
newRC = aggregate.getNewExpressionResultColumn(dd);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggInputVColId = newRC.getVirtualColumnId();
aggResultRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
"##WindowExpression",
aggregate.getNewNullResultExpression(),
getContextManager());
/*
** Add a reference to this column into the
** group by columns.
*/
tmpRC = getColumnReference(newRC, dd);
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** AGGREGATOR: Add a getAggregator method call
** to the bottom result column list.
*/
newRC = aggregate.getNewAggregatorResultColumn(dd);
newRC.markGenerated();
newRC.bindResultColumnToExpression();
bottomRCL.addElement(newRC);
newRC.setVirtualColumnId(bottomRCL.size());
aggregatorVColId = newRC.getVirtualColumnId();
/*
** Add a reference to this column in the Group By result
** set.
*/
tmpRC = getColumnReference(newRC, dd);
groupByRCL.addElement(tmpRC);
tmpRC.setVirtualColumnId(groupByRCL.size());
/*
** Piece together a fake one column rcl that we will use
** to generate a proper result description for input
** to this agg if it is a user agg.
*/
aggRCL = (ResultColumnList) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN_LIST,
getContextManager());
aggRCL.addElement(aggResultRC);
/*
** Note that the column ids in the row are 0 based
** so we have to subtract 1.
*/
aggInfo.addElement(new AggregatorInfo(
aggregate.getAggregateName(),
aggregate.getAggregatorClassName(),
aggInputVColId - 1, // aggregate input column
aggResultVColId - 1, // the aggregate result column
aggregatorVColId - 1, // the aggregator column
aggregate.isDistinct(),
lf.getResultDescription(aggRCL.makeResultDescriptors(), "SELECT")
));
this.processedAggregates.add(aggregate.getWrappedAggregate());
}
}
/**
* Return the parent node to this one, if there is
* one. It will return 'this' if there is no generated
* node above this one.
*
* @return the parent node
*/
public FromTable getParent() {
return parent;
}
/*
* Optimizable interface
*/
/**
* @throws StandardException Thrown on error
* @see Optimizable#optimizeIt
*/
public CostEstimate optimizeIt(
Optimizer optimizer,
OptimizablePredicateList predList,
CostEstimate outerCost,
RowOrdering rowOrdering)
throws StandardException {
// RESOLVE: NEED TO FACTOR IN THE COST OF GROUPING (SORTING) HERE
CostEstimate childCost = ((Optimizable) childResult).optimizeIt(
optimizer,
predList,
outerCost,
rowOrdering);
CostEstimate retval = super.optimizeIt(
optimizer,
predList,
outerCost,
rowOrdering
);
return retval;
}
/**
* @throws StandardException Thrown on error
* @see Optimizable#estimateCost
*/
public CostEstimate estimateCost(OptimizablePredicateList predList,
ConglomerateDescriptor cd,
CostEstimate outerCost,
Optimizer optimizer,
RowOrdering rowOrdering
)
throws StandardException {
// RESOLVE: NEED TO FACTOR IN THE COST OF GROUPING (SORTING) HERE
//
CostEstimate childCost = ((Optimizable) childResult).estimateCost(
predList,
cd,
outerCost,
optimizer,
rowOrdering);
CostEstimate costEstimate = getCostEstimate(optimizer);
costEstimate.setCost(childCost.getEstimatedCost(),
childCost.rowCount(),
childCost.singleScanRowCount());
return costEstimate;
}
/**
* @throws StandardException Thrown on error
* @see org.apache.derby.iapi.sql.compile.Optimizable#pushOptPredicate
*/
public boolean pushOptPredicate(OptimizablePredicate optimizablePredicate)
throws StandardException {
return ((Optimizable) childResult).pushOptPredicate(optimizablePredicate);
}
/**
* Convert this object to a String. See comments in QueryTreeNode.java
* for how this should be done for tree printing.
*
* @return This object as a String
*/
public String toString() {
if (SanityManager.DEBUG) {
return wdn.toString()+ "\n" + super.toString();
} else {
return "";
}
}
/**
* Prints the sub-nodes of this object. See QueryTreeNode.java for
* how tree printing is supposed to work.
*
* @param depth The depth of this node in the tree
*/
public void printSubNodes(int depth) {
if (SanityManager.DEBUG) {
super.printSubNodes(depth);
printLabel(depth, "windowFunctions:\n");
for (int i = 0; i < windowFunctions.size(); i++) {
AggregateNode agg =
(AggregateNode) windowFunctions.get(i);
debugPrint(formatNodeString("[" + i + "]:", depth + 1));
agg.treePrint(depth + 1);
}
printLabel(depth, "windowDefintionNode: ");
wdn.treePrint(depth + 1);
}
}
/**
* Evaluate whether or not the subquery in a FromSubquery is flattenable.
* Currently, a FSqry is flattenable if all of the following are true:
* o Subquery is a SelectNode.
* o It contains no top level subqueries. (RESOLVE - we can relax this)
* o It does not contain a group by or having clause
* o It does not contain aggregates.
*
* @param fromList The outer from list
* @return boolean Whether or not the FromSubquery is flattenable.
*/
public boolean flattenableInFromSubquery(FromList fromList) {
/* Can't flatten a WindowResultSetNode */
return false;
}
/**
* Optimize this WindowResultSetNode.
*
* @param dataDictionary The DataDictionary to use for optimization
* @param predicates The PredicateList to optimize. This should
* be a join predicate.
* @param outerRows The number of outer joining rows
* @throws StandardException Thrown on error
* @return ResultSetNode The top of the optimized subtree
*/
public ResultSetNode optimize(DataDictionary dataDictionary,
PredicateList predicates,
double outerRows)
throws StandardException {
/* We need to implement this method since a PRN can appear above a
* SelectNode in a query tree.
*/
childResult = (ResultSetNode) childResult.optimize(
dataDictionary,
predicates,
outerRows);
Optimizer optimizer = getOptimizer(
(FromList) getNodeFactory().getNode(
C_NodeTypes.FROM_LIST,
getNodeFactory().doJoinOrderOptimization(),
getContextManager()),
predicates,
dataDictionary,
(RequiredRowOrdering) null);
// RESOLVE: NEED TO FACTOR IN COST OF SORTING AND FIGURE OUT HOW
// MANY ROWS HAVE BEEN ELIMINATED.
costEstimate = optimizer.newCostEstimate();
costEstimate.setCost(childResult.getCostEstimate().getEstimatedCost(),
childResult.getCostEstimate().rowCount(),
childResult.getCostEstimate().singleScanRowCount());
return this;
}
ResultColumnDescriptor[] makeResultDescriptors() {
return childResult.makeResultDescriptors();
}
/**
* Return whether or not the underlying ResultSet tree will return
* a single row, at most.
* This is important for join nodes where we can save the extra next
* on the right side if we know that it will return at most 1 row.
*
* @return Whether or not the underlying ResultSet tree will return a single row.
* @throws StandardException Thrown on error
*/
public boolean isOneRowResultSet() throws StandardException {
// Only consider scalar aggregates for now
return ((partition == null) || (partition.size() == 0));
}
/**
* generate the sort result set operating over the source
* resultset. Adds distinct aggregates to the sort if
* necessary.
*
* @throws StandardException Thrown on error
*/
public void generate(ActivationClassBuilder acb,
MethodBuilder mb)
throws StandardException {
int orderingItem = 0;
int aggInfoItem = 0;
FormatableArrayHolder orderingHolder;
/* Get the next ResultSet#, so we can number this ResultSetNode, its
* ResultColumnList and ResultSet.
*/
assignResultSetNumber();
// Get the final cost estimate from the child.
costEstimate = childResult.getFinalCostEstimate();
/*
** Get the column ordering for the sort from orderby list.
* getColumnOrdering does the right thing if orderby list is null empty.
*/
orderingHolder = acb.getColumnOrdering(wdn.getOrderByList());
if (SanityManager.DEBUG) {
if (SanityManager.DEBUG_ON("WindowTrace")) {
StringBuilder s = new StringBuilder();
s.append("Partition column ordering is (");
org.apache.derby.iapi.store.access.ColumnOrdering[] ordering =
(org.apache.derby.iapi.store.access.ColumnOrdering[]) orderingHolder.getArray(org.apache.derby
.iapi.store
.access
.ColumnOrdering
.class);
for (int i = 0; i < ordering.length; i++) {
s.append(ordering[i].getColumnId());
s.append(" ");
}
s.append(")");
SanityManager.DEBUG("WindowTrace", s.toString());
}
}
orderingItem = acb.addItem(orderingHolder);
/*
** We have aggregates, so save the aggInfo
** struct in the activation and store the number
*/
if (SanityManager.DEBUG) {
SanityManager.ASSERT(aggInfo != null,
"aggInfo not set up as expected");
}
aggInfoItem = acb.addItem(aggInfo);
acb.pushGetResultSetFactoryExpression(mb);
/* Generate the WindowResultSet:
* arg1: childExpress - Expression for childResult
* arg2: isInSortedOrder - true if source result set in sorted order
* arg3: aggInfoItem - entry in saved objects for the aggregates,
* arg4: orderingItem - entry in saved objects for the ordering
* arg5: Activation
* arg6: rowAllocator - method to construct rows for fetching
* from the sort
* arg7: row size
* arg8: resultSetNumber
*/
// Generate the child ResultSet
childResult.generate(acb, mb);
mb.push(isInSortedOrder);
mb.push(aggInfoItem);
mb.push(orderingItem);
resultColumns.generateHolder(acb, mb);
mb.push(resultColumns.getTotalColumnSize());
mb.push(resultSetNumber);
mb.push(costEstimate.rowCount());
mb.push(costEstimate.getEstimatedCost());
mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getWindowResultSet",
ClassName.NoPutResultSet, 9);
}
///////////////////////////////////////////////////////////////
//
// UTILITIES
//
///////////////////////////////////////////////////////////////
/**
* Method for creating a new result column referencing
* the one passed in.
*
* @return the new result column
* @throws StandardException on error
* @param targetRC the source
* @param dd
*/
private ResultColumn getColumnReference(ResultColumn targetRC,
DataDictionary dd)
throws StandardException {
ColumnReference tmpColumnRef;
ResultColumn newRC;
tmpColumnRef = (ColumnReference) getNodeFactory().getNode(
C_NodeTypes.COLUMN_REFERENCE,
targetRC.getName(),
null,
getContextManager());
tmpColumnRef.setSource(targetRC);
tmpColumnRef.setNestingLevel(this.getLevel());
tmpColumnRef.setSourceLevel(this.getLevel());
newRC = (ResultColumn) getNodeFactory().getNode(
C_NodeTypes.RESULT_COLUMN,
targetRC.getColumnName(),
tmpColumnRef,
getContextManager());
newRC.markGenerated();
newRC.bindResultColumnToExpression();
return newRC;
}
/**
* Comparator class for GROUP BY expression substitution.
* <p/>
* This class enables the sorting of a collection of
* SubstituteExpressionVisitor instances. We sort the visitors
* during the tree manipulation processing in order to process
* expressions of higher complexity prior to expressions of
* lower complexity. Processing the expressions in this order ensures
* that we choose the best match for an expression, and thus avoids
* problems where we substitute a sub-expression instead of the
* full expression. For example, if the statement is:
* ... GROUP BY a+b, a, a*(a+b), a+b+c
* we'll process those expressions in the order: a*(a+b),
* a+b+c, a+b, then a.
*/
private static final class ExpressionSorter implements Comparator {
public int compare(Object o1, Object o2) {
try {
ValueNode v1 = ((SubstituteExpressionVisitor) o1).getSource();
ValueNode v2 = ((SubstituteExpressionVisitor) o2).getSource();
int refCount1, refCount2;
CollectNodesVisitor vis = new CollectNodesVisitor(
ColumnReference.class);
v1.accept(vis);
refCount1 = vis.getList().size();
vis = new CollectNodesVisitor(ColumnReference.class);
v2.accept(vis);
refCount2 = vis.getList().size();
// The ValueNode with the larger number of refs
// should compare lower. That way we are sorting
// the expressions in descending order of complexity.
return refCount2 - refCount1;
} catch (StandardException e) {
throw new RuntimeException(e);
}
}
}
} | Cleaned up some todos. Added orderbylist to plan in WindowResultSet. Seeing ArrayIndexOutOfBounds on splice side - SinkGroupedAggregateIterator.groupingKey when marshalling key.
| java/engine/org/apache/derby/impl/sql/compile/WindowResultSetNode.java | Cleaned up some todos. Added orderbylist to plan in WindowResultSet. Seeing ArrayIndexOutOfBounds on splice side - SinkGroupedAggregateIterator.groupingKey when marshalling key. | ||
Java | apache-2.0 | f195a6fb6253e21abcd0df3452c7402664f08000 | 0 | koo-taejin/pinpoint,hcapitaine/pinpoint,denzelsN/pinpoint,naver/pinpoint,barneykim/pinpoint,Xylus/pinpoint,tsyma/pinpoint,andyspan/pinpoint,coupang/pinpoint,nstopkimsk/pinpoint,sjmittal/pinpoint,cijung/pinpoint,koo-taejin/pinpoint,breadval/pinpoint,minwoo-jung/pinpoint,cijung/pinpoint,suraj-raturi/pinpoint,andyspan/pinpoint,sbcoba/pinpoint,cijung/pinpoint,sbcoba/pinpoint,nstopkimsk/pinpoint,andyspan/pinpoint,sjmittal/pinpoint,dawidmalina/pinpoint,KimTaehee/pinpoint,denzelsN/pinpoint,Xylus/pinpoint,eBaoTech/pinpoint,denzelsN/pinpoint,barneykim/pinpoint,citywander/pinpoint,coupang/pinpoint,Allive1/pinpoint,KimTaehee/pinpoint,87439247/pinpoint,majinkai/pinpoint,masonmei/pinpoint,Skkeem/pinpoint,koo-taejin/pinpoint,jaehong-kim/pinpoint,Skkeem/pinpoint,Skkeem/pinpoint,masonmei/pinpoint,lioolli/pinpoint,chenguoxi1985/pinpoint,jaehong-kim/pinpoint,cit-lab/pinpoint,sjmittal/pinpoint,andyspan/pinpoint,majinkai/pinpoint,emeroad/pinpoint,Allive1/pinpoint,lioolli/pinpoint,gspandy/pinpoint,naver/pinpoint,coupang/pinpoint,hcapitaine/pinpoint,krishnakanthpps/pinpoint,jiaqifeng/pinpoint,Allive1/pinpoint,jaehong-kim/pinpoint,naver/pinpoint,breadval/pinpoint,tsyma/pinpoint,lioolli/pinpoint,citywander/pinpoint,jiaqifeng/pinpoint,wziyong/pinpoint,krishnakanthpps/pinpoint,PerfGeeks/pinpoint,jiaqifeng/pinpoint,barneykim/pinpoint,philipz/pinpoint,chenguoxi1985/pinpoint,InfomediaLtd/pinpoint,wziyong/pinpoint,koo-taejin/pinpoint,philipz/pinpoint,majinkai/pinpoint,cit-lab/pinpoint,emeroad/pinpoint,InfomediaLtd/pinpoint,suraj-raturi/pinpoint,coupang/pinpoint,majinkai/pinpoint,denzelsN/pinpoint,cit-lab/pinpoint,breadval/pinpoint,InfomediaLtd/pinpoint,dawidmalina/pinpoint,InfomediaLtd/pinpoint,eBaoTech/pinpoint,krishnakanthpps/pinpoint,cijung/pinpoint,naver/pinpoint,philipz/pinpoint,Allive1/pinpoint,wziyong/pinpoint,PerfGeeks/pinpoint,barneykim/pinpoint,KimTaehee/pinpoint,masonmei/pinpoint,masonmei/pinpoint,PerfGeeks/pinpoint,masonmei/pinpoint,nstopkimsk/pinpoint,sjmittal/pinpoint,Xylus/pinpoint,87439247/pinpoint,hcapitaine/pinpoint,suraj-raturi/pinpoint,minwoo-jung/pinpoint,breadval/pinpoint,KimTaehee/pinpoint,majinkai/pinpoint,cijung/pinpoint,87439247/pinpoint,breadval/pinpoint,citywander/pinpoint,cijung/pinpoint,eBaoTech/pinpoint,nstopkimsk/pinpoint,lioolli/pinpoint,sbcoba/pinpoint,suraj-raturi/pinpoint,Xylus/pinpoint,koo-taejin/pinpoint,jaehong-kim/pinpoint,KimTaehee/pinpoint,dawidmalina/pinpoint,hcapitaine/pinpoint,nstopkimsk/pinpoint,dawidmalina/pinpoint,jiaqifeng/pinpoint,tsyma/pinpoint,cit-lab/pinpoint,philipz/pinpoint,InfomediaLtd/pinpoint,nstopkimsk/pinpoint,sjmittal/pinpoint,majinkai/pinpoint,cit-lab/pinpoint,jiaqifeng/pinpoint,krishnakanthpps/pinpoint,naver/pinpoint,gspandy/pinpoint,koo-taejin/pinpoint,barneykim/pinpoint,citywander/pinpoint,chenguoxi1985/pinpoint,shuvigoss/pinpoint,sbcoba/pinpoint,sjmittal/pinpoint,emeroad/pinpoint,cit-lab/pinpoint,PerfGeeks/pinpoint,wziyong/pinpoint,philipz/pinpoint,gspandy/pinpoint,wziyong/pinpoint,chenguoxi1985/pinpoint,andyspan/pinpoint,denzelsN/pinpoint,denzelsN/pinpoint,krishnakanthpps/pinpoint,wziyong/pinpoint,KRDeNaT/pinpoint,KRDeNaT/pinpoint,dawidmalina/pinpoint,citywander/pinpoint,jaehong-kim/pinpoint,Allive1/pinpoint,hcapitaine/pinpoint,PerfGeeks/pinpoint,chenguoxi1985/pinpoint,suraj-raturi/pinpoint,InfomediaLtd/pinpoint,minwoo-jung/pinpoint,jaehong-kim/pinpoint,KimTaehee/pinpoint,suraj-raturi/pinpoint,emeroad/pinpoint,Xylus/pinpoint,krishnakanthpps/pinpoint,coupang/pinpoint,shuvigoss/pinpoint,chenguoxi1985/pinpoint,eBaoTech/pinpoint,Skkeem/pinpoint,KRDeNaT/pinpoint,coupang/pinpoint,masonmei/pinpoint,dawidmalina/pinpoint,lioolli/pinpoint,Skkeem/pinpoint,sbcoba/pinpoint,minwoo-jung/pinpoint,gspandy/pinpoint,shuvigoss/pinpoint,Skkeem/pinpoint,eBaoTech/pinpoint,sbcoba/pinpoint,PerfGeeks/pinpoint,gspandy/pinpoint,minwoo-jung/pinpoint,87439247/pinpoint,philipz/pinpoint,KRDeNaT/pinpoint,Xylus/pinpoint,minwoo-jung/pinpoint,emeroad/pinpoint,shuvigoss/pinpoint,tsyma/pinpoint,KRDeNaT/pinpoint,andyspan/pinpoint,emeroad/pinpoint,87439247/pinpoint,denzelsN/pinpoint,87439247/pinpoint,eBaoTech/pinpoint,shuvigoss/pinpoint,barneykim/pinpoint,jiaqifeng/pinpoint,KRDeNaT/pinpoint,Allive1/pinpoint,gspandy/pinpoint,citywander/pinpoint,shuvigoss/pinpoint,hcapitaine/pinpoint,lioolli/pinpoint,barneykim/pinpoint,breadval/pinpoint,Xylus/pinpoint,tsyma/pinpoint,tsyma/pinpoint | /*
* Copyright 2015 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.calltree.span;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import com.navercorp.pinpoint.common.bo.SpanBo;
import com.navercorp.pinpoint.common.bo.SpanEventBo;
/**
*
* @author jaehong.kim
*
*/
public class CallTreeIteratorTest {
private static final boolean SYNC = false;
private static final boolean ASYNC = true;
private static final long START_TIME = 1430983914531L;
private static final int ELAPSED = 10;
@Test
public void depth() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
for (int i = 0; i <= node.getDepth(); i++) {
System.out.print("#");
}
System.out.println("");
}
}
@Test
public void gap() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
}
}
@Ignore
@Test
public void gapAsync() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1, -1, 1));
CallTree subTree = new SpanAsyncCallTree(root);
subTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 1, 1, -1));
subTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 1, 1, -1));
subTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 1, 1, -1));
subTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(subTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("gapAsync");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
}
}
@Test
public void gapComplex() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1, -1, 1));
SpanAlign rpc = makeSpanAlign(START_TIME + 10, 240);
CallTree rpcTree = new SpanCallTree(rpc);
rpcTree.add(1, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 0, 1, 1));
rpcTree.add(2, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 1, 2, 1));
rpcTree.add(3, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 2, 3, 1));
rpcTree.add(4, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(rpcTree);
CallTree asyncTree = new SpanAsyncCallTree(root);
asyncTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 1, 1, -1));
asyncTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 1, 1, -1));
asyncTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 1, 1, -1));
asyncTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(asyncTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("gapComplex");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
if(!node.isRoot()) {
assertEquals(1, align.getGap());
}
}
}
@Test
public void executionTime() {
SpanAlign root = makeSpanAlign(START_TIME, 10);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 8));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 4));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 3));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 2, -1, 1));
SpanAlign rpc = makeSpanAlign(START_TIME + 10, 5);
CallTree rpcTree = new SpanCallTree(rpc);
rpcTree.add(1, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 0, 1, 4));
rpcTree.add(2, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 1, 2, 3));
rpcTree.add(3, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 2, 3, 2));
rpcTree.add(4, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(rpcTree);
CallTree asyncTree = new SpanAsyncCallTree(root);
asyncTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 4, 1, -1));
asyncTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 3, 1, -1));
asyncTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 2, 1, -1));
asyncTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(asyncTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 3));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("executionTime");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : executionTime=" + align.getExecutionMilliseconds());
assertEquals(1, align.getExecutionMilliseconds());
}
}
private SpanAlign makeSpanAlign(long startTime, int elapsed) {
SpanBo span = new SpanBo();
span.setStartTime(startTime);
span.setElapsed(elapsed);
return new SpanAlign(span);
}
private SpanAlign makeSpanAlign(SpanBo span, final boolean async, final short sequence, int startElapsed, int endElapsed) {
return makeSpanAlign(span, async, sequence, startElapsed, endElapsed, -1, -1);
}
private SpanAlign makeSpanAlign(SpanBo span, final boolean async, final short sequence, int startElapsed, int endElapsed, final int asyncId, int nextAsyncId) {
SpanEventBo event = new SpanEventBo();
event.setSequence(sequence);
event.setStartElapsed(startElapsed);
event.setEndElapsed(endElapsed);
event.setAsyncId(asyncId);
event.setNextAsyncId(nextAsyncId);
return new SpanAlign(span, event);
}
} | web/src/test/java/com/navercorp/pinpoint/web/calltree/span/CallTreeIteratorTest.java | /*
* Copyright 2015 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.calltree.span;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import com.navercorp.pinpoint.common.bo.SpanBo;
import com.navercorp.pinpoint.common.bo.SpanEventBo;
/**
*
* @author jaehong.kim
*
*/
public class CallTreeIteratorTest {
private static final boolean SYNC = false;
private static final boolean ASYNC = true;
private static final long START_TIME = 1430983914531L;
private static final int ELAPSED = 10;
@Test
public void depth() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
for (int i = 0; i <= node.getDepth(); i++) {
System.out.print("#");
}
System.out.println("");
}
}
@Test
public void gap() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
}
}
@Ignore
@Test
public void gapAsync() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1, -1, 1));
CallTree subTree = new SpanAsyncCallTree(root);
subTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 1, 1, -1));
subTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 1, 1, -1));
subTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 1, 1, -1));
subTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(subTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("gapAsync");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
}
}
@Test
public void gapComplex() {
SpanAlign root = makeSpanAlign(START_TIME, 240);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 1));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 1, -1, 1));
SpanAlign rpc = makeSpanAlign(START_TIME + 10, 240);
CallTree rpcTree = new SpanCallTree(rpc);
rpcTree.add(1, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 0, 1, 1));
rpcTree.add(2, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 1, 2, 1));
rpcTree.add(3, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 2, 3, 1));
rpcTree.add(4, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(rpcTree);
CallTree asyncTree = new SpanAsyncCallTree(root);
asyncTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 1, 1, -1));
asyncTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 1, 1, -1));
asyncTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 1, 1, -1));
asyncTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(asyncTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 1));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("gapComplex");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : gap=" + align.getGap());
assertEquals(1, align.getGap());
}
}
@Test
public void executionTime() {
SpanAlign root = makeSpanAlign(START_TIME, 10);
CallTree callTree = new SpanCallTree(root);
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 0, 1, 8));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 1, 2, 4));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 2, 3, 3));
callTree.add(4, makeSpanAlign(root.getSpanBo(), SYNC, (short) 3, 4, 2, -1, 1));
SpanAlign rpc = makeSpanAlign(START_TIME + 10, 5);
CallTree rpcTree = new SpanCallTree(rpc);
rpcTree.add(1, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 0, 1, 4));
rpcTree.add(2, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 1, 2, 3));
rpcTree.add(3, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 2, 3, 2));
rpcTree.add(4, makeSpanAlign(rpc.getSpanBo(), SYNC, (short) 3, 4, 1));
callTree.add(rpcTree);
CallTree asyncTree = new SpanAsyncCallTree(root);
asyncTree.add(1, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 0, 5, 4, 1, -1));
asyncTree.add(2, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 1, 6, 3, 1, -1));
asyncTree.add(3, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 2, 7, 2, 1, -1));
asyncTree.add(4, makeSpanAlign(root.getSpanBo(), ASYNC, (short) 3, 8, 1, 1, -1));
callTree.add(asyncTree);
callTree.add(5, makeSpanAlign(root.getSpanBo(), SYNC, (short) 4, 5, 1));
callTree.add(2, makeSpanAlign(root.getSpanBo(), SYNC, (short) 5, 6, 3));
callTree.add(3, makeSpanAlign(root.getSpanBo(), SYNC, (short) 6, 7, 1));
callTree.add(-1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 7, 8, 1));
callTree.add(1, makeSpanAlign(root.getSpanBo(), SYNC, (short) 8, 9, 1));
CallTreeIterator iterator = callTree.iterator();
// assertEquals(5, iterator.size());
System.out.println("executionTime");
while (iterator.hasNext()) {
CallTreeNode node = iterator.next();
SpanAlign align = node.getValue();
for (int i = 0; i <= align.getDepth(); i++) {
System.out.print("#");
}
System.out.println(" : executionTime=" + align.getExecutionMilliseconds());
assertEquals(1, align.getExecutionMilliseconds());
}
}
private SpanAlign makeSpanAlign(long startTime, int elapsed) {
SpanBo span = new SpanBo();
span.setStartTime(startTime);
span.setElapsed(elapsed);
return new SpanAlign(span);
}
private SpanAlign makeSpanAlign(SpanBo span, final boolean async, final short sequence, int startElapsed, int endElapsed) {
return makeSpanAlign(span, async, sequence, startElapsed, endElapsed, -1, -1);
}
private SpanAlign makeSpanAlign(SpanBo span, final boolean async, final short sequence, int startElapsed, int endElapsed, final int asyncId, int nextAsyncId) {
SpanEventBo event = new SpanEventBo();
event.setSequence(sequence);
event.setStartElapsed(startElapsed);
event.setEndElapsed(endElapsed);
event.setAsyncId(asyncId);
event.setNextAsyncId(nextAsyncId);
return new SpanAlign(span, event);
}
} | fix testcase - ignored root node.gap()
| web/src/test/java/com/navercorp/pinpoint/web/calltree/span/CallTreeIteratorTest.java | fix testcase - ignored root node.gap() | <ide><path>eb/src/test/java/com/navercorp/pinpoint/web/calltree/span/CallTreeIteratorTest.java
<ide> System.out.print("#");
<ide> }
<ide> System.out.println(" : gap=" + align.getGap());
<del> assertEquals(1, align.getGap());
<add> if(!node.isRoot()) {
<add> assertEquals(1, align.getGap());
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | ca1fa207688246d86aab0c93b33191954a75ffb6 | 0 | wildfly-security/wildfly-elytron,wildfly-security/wildfly-elytron | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth.client;
import static java.security.AccessController.doPrivileged;
import static java.security.AccessController.getContext;
import static org.wildfly.security._private.ElytronMessages.log;
import static org.wildfly.security.util.ProviderUtil.INSTALLED_PROVIDERS;
import java.io.IOException;
import java.net.URI;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ChoiceCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.x500.X500Principal;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.RealmChoiceCallback;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.Oid;
import org.wildfly.common.Assert;
import org.wildfly.common.annotation.NotNull;
import org.wildfly.security.FixedSecurityFactory;
import org.wildfly.security.SecurityFactory;
import org.wildfly.security.WildFlyElytronProvider;
import org.wildfly.security.auth.callback.CallbackUtil;
import org.wildfly.security.auth.callback.ChannelBindingCallback;
import org.wildfly.security.auth.callback.CredentialCallback;
import org.wildfly.security.auth.callback.EvidenceVerifyCallback;
import org.wildfly.security.auth.callback.ParameterCallback;
import org.wildfly.security.auth.callback.PasswordResetCallback;
import org.wildfly.security.auth.callback.SSLCallback;
import org.wildfly.security.auth.callback.TrustedAuthoritiesCallback;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.IdentityCredentials;
import org.wildfly.security.auth.server.NameRewriter;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.credential.AlgorithmCredential;
import org.wildfly.security.credential.BearerTokenCredential;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.X509CertificateChainPrivateCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.credential.source.CredentialStoreCredentialSource;
import org.wildfly.security.credential.source.FactoryCredentialSource;
import org.wildfly.security.credential.source.KeyStoreCredentialSource;
import org.wildfly.security.credential.source.LocalKerberosCredentialSource;
import org.wildfly.security.credential.store.CredentialStore;
import org.wildfly.security.evidence.X509PeerCertificateChainEvidence;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.TwoWayPassword;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.password.spec.ClearPasswordSpec;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.security.sasl.localuser.LocalUserClient;
import org.wildfly.security.sasl.localuser.LocalUserSaslFactory;
import org.wildfly.security.sasl.util.FilterMechanismSaslClientFactory;
import org.wildfly.security.sasl.util.LocalPrincipalSaslClientFactory;
import org.wildfly.security.sasl.util.PrivilegedSaslClientFactory;
import org.wildfly.security.sasl.util.PropertiesSaslClientFactory;
import org.wildfly.security.sasl.util.ProtocolSaslClientFactory;
import org.wildfly.security.sasl.util.SSLSaslClientFactory;
import org.wildfly.security.sasl.util.SaslMechanismInformation;
import org.wildfly.security.sasl.util.SecurityProviderSaslClientFactory;
import org.wildfly.security.sasl.util.ServerNameSaslClientFactory;
import org.wildfly.security.ssl.SSLConnection;
import org.wildfly.security.ssl.SSLUtils;
import org.wildfly.security.util.ProviderServiceLoaderSupplier;
import org.wildfly.security.util.ProviderUtil;
import org.wildfly.security.util._private.Arrays2;
import org.wildfly.security.x500.TrustedAuthority;
/**
* A configuration which controls how authentication is performed.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
public final class AuthenticationConfiguration {
// constants
private static final Principal[] NO_PRINCIPALS = new Principal[0];
private static final Callback[] NO_CALLBACKS = new Callback[0];
private static final String[] NO_STRINGS = new String[0];
private static final EnumSet<CallbackKind> NO_CALLBACK_KINDS = EnumSet.noneOf(CallbackKind.class);
private static final int SET_PRINCIPAL = 0;
private static final int SET_HOST = 1;
private static final int SET_PROTOCOL = 2;
private static final int SET_REALM = 3;
private static final int SET_AUTHZ_PRINCIPAL = 4;
private static final int SET_FWD_AUTH_NAME_DOMAIN = 5;
private static final int SET_USER_CBH = 6;
private static final int SET_USER_CB_KINDS = 7;
private static final int SET_CRED_SOURCE = 8;
private static final int SET_PROVIDER_SUPPLIER = 9;
private static final int SET_KEY_MGR_FAC = 10;
private static final int SET_SASL_SELECTOR = 11;
private static final int SET_FWD_AUTH_CRED_DOMAIN = 12;
private static final int SET_PRINCIPAL_RW = 13;
private static final int SET_SASL_FAC_SUP = 14;
private static final int SET_PARAM_SPECS = 15;
private static final int SET_TRUST_MGR_FAC = 16;
private static final int SET_SASL_MECH_PROPS = 17;
private static final int SET_ACCESS_CTXT = 18;
private static final int SET_CALLBACK_INTERCEPT = 19;
private static final int SET_SASL_PROTOCOL = 20;
private static final int SET_FWD_AUTHZ_NAME_DOMAIN = 21;
private static final Supplier<Provider[]> DEFAULT_PROVIDER_SUPPLIER = ProviderUtil.aggregate(
() -> new Provider[] {
WildFlySecurityManager.isChecking() ?
AccessController.doPrivileged((PrivilegedAction<WildFlyElytronProvider>) () -> new WildFlyElytronProvider()) :
new WildFlyElytronProvider()
},
WildFlySecurityManager.isChecking() ?
AccessController.doPrivileged((PrivilegedAction<ProviderServiceLoaderSupplier>) () -> new ProviderServiceLoaderSupplier(AuthenticationConfiguration.class.getClassLoader(), true)) :
new ProviderServiceLoaderSupplier(AuthenticationConfiguration.class.getClassLoader(), true),
INSTALLED_PROVIDERS);
/**
* An empty configuration which can be used as the basis for any configuration. This configuration supports no
* remapping of any kind, and always uses an anonymous principal.
* @deprecated to obtain empty configuration use {@link #empty()} method instead
*/
@Deprecated
public static final AuthenticationConfiguration EMPTY = new AuthenticationConfiguration();
/**
* An empty configuration which can be used as the basis for any configuration. This configuration supports no
* remapping of any kind, and always uses an anonymous principal.
*/
public static AuthenticationConfiguration empty() {
return EMPTY;
}
private volatile SaslClientFactory saslClientFactory = null;
private int hashCode;
private String toString;
final AccessControlContext capturedAccessContext;
@NotNull final Principal principal;
final String setHost;
final String setProtocol;
final String setRealm;
final Principal setAuthzPrincipal;
final SecurityDomain authenticationNameForwardSecurityDomain;
final SecurityDomain authenticationCredentialsForwardSecurityDomain;
final SecurityDomain authorizationNameForwardSecurityDomain;
final CallbackHandler userCallbackHandler;
final EnumSet<CallbackKind> userCallbackKinds;
final CredentialSource credentialSource;
final int setPort;
final Supplier<Provider[]> providerSupplier;
final SecurityFactory<X509KeyManager> keyManagerFactory;
final SaslMechanismSelector saslMechanismSelector;
final Function<Principal, Principal> principalRewriter;
final Supplier<SaslClientFactory> saslClientFactorySupplier;
final List<AlgorithmParameterSpec> parameterSpecs;
final SecurityFactory<X509TrustManager> trustManagerFactory;
final Map<String, ?> saslMechanismProperties;
final Predicate<Callback> callbackIntercept;
final String saslProtocol;
// constructors
/**
* Construct the empty configuration instance.
*/
private AuthenticationConfiguration() {
this.capturedAccessContext = null;
this.principal = AnonymousPrincipal.getInstance();
this.setHost = null;
this.setProtocol = null;
this.setRealm = null;
this.setAuthzPrincipal = null;
this.authenticationNameForwardSecurityDomain = null;
this.authenticationCredentialsForwardSecurityDomain = null;
this.authorizationNameForwardSecurityDomain = null;
this.userCallbackHandler = null;
this.userCallbackKinds = NO_CALLBACK_KINDS;
this.credentialSource = IdentityCredentials.NONE;
this.setPort = -1;
this.providerSupplier = DEFAULT_PROVIDER_SUPPLIER;
this.keyManagerFactory = null;
this.saslMechanismSelector = null;
this.principalRewriter = null;
this.saslClientFactorySupplier = null;
this.parameterSpecs = Collections.emptyList();
this.trustManagerFactory = null;
this.saslMechanismProperties = Collections.singletonMap(LocalUserClient.QUIET_AUTH, "true");
this.callbackIntercept = null;
this.saslProtocol = null;
}
/**
* Copy constructor for mutating one object field. It's not pretty but the alternative (many constructors) is much
* worse.
*
* @param original the original configuration (must not be {@code null})
* @param what the field to mutate
* @param value the field value to set
*/
@SuppressWarnings("unchecked")
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int what, final Object value) {
this.capturedAccessContext = what == SET_ACCESS_CTXT ? (AccessControlContext) value : original.capturedAccessContext;
this.principal = what == SET_PRINCIPAL ? (Principal) value : original.principal;
this.setHost = what == SET_HOST ? (String) value : original.setHost;
this.setProtocol = what == SET_PROTOCOL ? (String) value : original.setProtocol;
this.setRealm = what == SET_REALM ? (String) value : original.setRealm;
this.setAuthzPrincipal = what == SET_AUTHZ_PRINCIPAL ? (Principal) value : original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = what == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value : original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = what == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value : original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = what == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value : original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = what == SET_USER_CBH ? (CallbackHandler) value : original.userCallbackHandler;
this.userCallbackKinds = (what == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value : original.userCallbackKinds).clone();
this.credentialSource = what == SET_CRED_SOURCE ? (CredentialSource) value : original.credentialSource;
this.setPort = original.setPort;
this.providerSupplier = what == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value : original.providerSupplier;
this.keyManagerFactory = what == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value : original.keyManagerFactory;
this.saslMechanismSelector = what == SET_SASL_SELECTOR ? (SaslMechanismSelector) value : original.saslMechanismSelector;
this.principalRewriter = what == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value : original.principalRewriter;
this.saslClientFactorySupplier = what == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value : original.saslClientFactorySupplier;
this.parameterSpecs = what == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value : original.parameterSpecs;
this.trustManagerFactory = what == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value : original.trustManagerFactory;
this.saslMechanismProperties = what == SET_SASL_MECH_PROPS ? (Map<String, ?>) value : original.saslMechanismProperties;
this.callbackIntercept = what == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value : original.callbackIntercept;
this.saslProtocol = what == SET_SASL_PROTOCOL ? (String) value : original.saslProtocol;
sanitazeOnMutation(what);
}
/**
* Copy constructor for mutating two object fields. It's not pretty but the alternative (many constructors) is much
* worse.
*
* @param original the original configuration (must not be {@code null})
* @param what1 the field to mutate
* @param value1 the field value to set
* @param what2 the field to mutate
* @param value2 the field value to set
*/
@SuppressWarnings("unchecked")
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int what1, final Object value1, final int what2, final Object value2) {
this.capturedAccessContext = what1 == SET_ACCESS_CTXT ? (AccessControlContext) value1 : what2 == SET_ACCESS_CTXT ? (AccessControlContext) value2 : original.capturedAccessContext;
this.principal = what1 == SET_PRINCIPAL ? (Principal) value1 : what2 == SET_PRINCIPAL ? (Principal) value2 : original.principal;
this.setHost = what1 == SET_HOST ? (String) value1 : what2 == SET_HOST ? (String) value2 : original.setHost;
this.setProtocol = what1 == SET_PROTOCOL ? (String) value1 : what2 == SET_PROTOCOL ? (String) value2 : original.setProtocol;
this.setRealm = what1 == SET_REALM ? (String) value1 : what2 == SET_REALM ? (String) value2 : original.setRealm;
this.setAuthzPrincipal = what1 == SET_AUTHZ_PRINCIPAL ? (Principal) value1 : what2 == SET_AUTHZ_PRINCIPAL ? (Principal) value2 : original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = what1 == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value2 : original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = what1 == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value2 : original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = what1 == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value2 : original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = what1 == SET_USER_CBH ? (CallbackHandler) value1 : what2 == SET_USER_CBH ? (CallbackHandler) value2 : original.userCallbackHandler;
this.userCallbackKinds = (what1 == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value1 : what2 == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value2 : original.userCallbackKinds).clone();
this.credentialSource = what1 == SET_CRED_SOURCE ? (CredentialSource) value1 : what2 == SET_CRED_SOURCE ? (CredentialSource) value2 : original.credentialSource;
this.setPort = original.setPort;
this.providerSupplier = what1 == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value1 : what2 == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value2 : original.providerSupplier;
this.keyManagerFactory = what1 == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value1 : what2 == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value2 : original.keyManagerFactory;
this.saslMechanismSelector = what1 == SET_SASL_SELECTOR ? (SaslMechanismSelector) value1 : what2 == SET_SASL_SELECTOR ? (SaslMechanismSelector) value2 : original.saslMechanismSelector;
this.principalRewriter = what1 == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value1 : what2 == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value2 : original.principalRewriter;
this.saslClientFactorySupplier = what1 == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value1 : what2 == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value2 : original.saslClientFactorySupplier;
this.parameterSpecs = what1 == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value1 : what2 == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value2 : original.parameterSpecs;
this.trustManagerFactory = what1 == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value1 : what2 == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value2 : original.trustManagerFactory;
this.saslMechanismProperties = what1 == SET_SASL_MECH_PROPS ? (Map<String, ?>) value1 : what2 == SET_SASL_MECH_PROPS ? (Map<String, ?>) value2 : original.saslMechanismProperties;
this.callbackIntercept = what1 == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value1 : what2 == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value2 : original.callbackIntercept;
this.saslProtocol = what1 == SET_SASL_PROTOCOL ? (String) value1 : what2 == SET_SASL_PROTOCOL ? (String) value2 : original.saslProtocol;
sanitazeOnMutation(what1);
sanitazeOnMutation(what2);
}
/**
* Copy constructor for mutating the port number.
*
* @param original the original configuration (must not be {@code null})
* @param port the port number
*/
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int port) {
this.capturedAccessContext = original.capturedAccessContext;
this.principal = original.principal;
this.setHost = original.setHost;
this.setProtocol = original.setProtocol;
this.setRealm = original.setRealm;
this.setAuthzPrincipal = original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = original.userCallbackHandler;
this.userCallbackKinds = original.userCallbackKinds;
this.credentialSource = original.credentialSource;
this.setPort = port;
this.providerSupplier = original.providerSupplier;
this.keyManagerFactory = original.keyManagerFactory;
this.saslMechanismSelector = original.saslMechanismSelector;
this.principalRewriter = original.principalRewriter;
this.saslClientFactorySupplier = original.saslClientFactorySupplier;
this.parameterSpecs = original.parameterSpecs;
this.trustManagerFactory = original.trustManagerFactory;
this.saslMechanismProperties = original.saslMechanismProperties;
this.callbackIntercept = original.callbackIntercept;
this.saslProtocol = original.saslProtocol;
}
private AuthenticationConfiguration(final AuthenticationConfiguration original, final AuthenticationConfiguration other) {
this.capturedAccessContext = getOrDefault(other.capturedAccessContext, original.capturedAccessContext);
this.principal = other.principal instanceof AnonymousPrincipal ? original.principal : other.principal;
this.setHost = getOrDefault(other.setHost, original.setHost);
this.setProtocol = getOrDefault(other.setProtocol, original.setProtocol);
this.setRealm = getOrDefault(other.setRealm, original.setRealm);
this.setAuthzPrincipal = getOrDefault(other.setAuthzPrincipal, original.setAuthzPrincipal);
this.authenticationNameForwardSecurityDomain = getOrDefault(other.authenticationNameForwardSecurityDomain, original.authenticationNameForwardSecurityDomain);
this.authenticationCredentialsForwardSecurityDomain = getOrDefault(other.authenticationCredentialsForwardSecurityDomain, original.authenticationCredentialsForwardSecurityDomain);
this.authorizationNameForwardSecurityDomain = getOrDefault(other.authorizationNameForwardSecurityDomain, original.authorizationNameForwardSecurityDomain);
this.userCallbackHandler = getOrDefault(other.userCallbackHandler, original.userCallbackHandler);
this.userCallbackKinds = getOrDefault(other.userCallbackKinds, original.userCallbackKinds).clone();
this.credentialSource = other.credentialSource == IdentityCredentials.NONE ? original.credentialSource : other.credentialSource;
this.setPort = getOrDefault(other.setPort, original.setPort);
this.providerSupplier = getOrDefault(other.providerSupplier, original.providerSupplier);
this.keyManagerFactory = getOrDefault(other.keyManagerFactory, original.keyManagerFactory);
this.saslMechanismSelector = getOrDefault(other.saslMechanismSelector, original.saslMechanismSelector);
this.principalRewriter = getOrDefault(other.principalRewriter, original.principalRewriter);
this.saslClientFactorySupplier = getOrDefault(other.saslClientFactorySupplier, original.saslClientFactorySupplier);
this.parameterSpecs = getOrDefault(other.parameterSpecs, original.parameterSpecs);
this.trustManagerFactory = getOrDefault(other.trustManagerFactory, original.trustManagerFactory);
this.saslMechanismProperties = getOrDefault(other.saslMechanismProperties, original.saslMechanismProperties);
this.callbackIntercept = other.callbackIntercept == null ? original.callbackIntercept : original.callbackIntercept == null ? other.callbackIntercept : other.callbackIntercept.or(original.callbackIntercept);
this.saslProtocol = getOrDefault(other.saslProtocol, original.saslProtocol);
sanitazeOnMutation(SET_USER_CBH);
}
private static <T> T getOrDefault(T value, T defVal) {
return value != null ? value : defVal;
}
private static int getOrDefault(int value, int defVal) {
return value != -1 ? value : defVal;
}
// test method
Principal getPrincipal() {
return authenticationNameForwardSecurityDomain != null ? authenticationNameForwardSecurityDomain.getCurrentSecurityIdentity().getPrincipal() : principal;
}
@Deprecated
String getHost() {
return setHost;
}
@Deprecated
String getProtocol() {
return setProtocol;
}
String getSaslProtocol() {
return saslProtocol;
}
@Deprecated
int getPort() {
return setPort;
}
// internal actions
/**
* Determine if this SASL mechanism is supported by this configuration (not policy). Implementations must
* combine using boolean-OR operations.
*
* @param mechanismName the mech name (must not be {@code null})
* @return {@code true} if supported, {@code false} otherwise
*/
boolean saslSupportedByConfiguration(String mechanismName) {
// special case for local, quiet auth
// anonymous is only supported if the principal is anonymous. If the principal is anonymous, only anonymous or principal-less mechanisms are supported.
if (! userCallbackKinds.contains(CallbackKind.PRINCIPAL) && principal != AnonymousPrincipal.getInstance()) {
// no callback which can handle a principal.
if (! (mechanismName.equals(LocalUserSaslFactory.JBOSS_LOCAL_USER) || SaslMechanismInformation.doesNotUsePrincipal(mechanismName))) {
// the mechanism requires a principal.
if (getPrincipal() instanceof AnonymousPrincipal != mechanismName.equals(SaslMechanismInformation.Names.ANONYMOUS)) {
// either we have no principal & the mech requires one, or we have a principal but the mech is anonymous.
return false;
}
}
}
// if we have a credential-providing callback handler, we support any mechanism from here on out
if (userCallbackKinds.contains(CallbackKind.CREDENTIAL) || (credentialSource != null && ! credentialSource.equals(IdentityCredentials.NONE))) {
return true;
}
// mechanisms that do not need credentials are probably supported
if (SaslMechanismInformation.doesNotRequireClientCredentials(mechanismName)) {
return true;
}
// if we have a key manager factory, we definitely support IEC/ISO 9798
if (keyManagerFactory != null && SaslMechanismInformation.IEC_ISO_9798.test(mechanismName)) {
return true;
}
// otherwise, use mechanism information and our credential set
Set<Class<? extends Credential>> types = SaslMechanismInformation.getSupportedClientCredentialTypes(mechanismName);
final CredentialSource credentials = credentialSource;
for (Class<? extends Credential> type : types) {
if (AlgorithmCredential.class.isAssignableFrom(type)) {
Set<String> algorithms = SaslMechanismInformation.getSupportedClientCredentialAlgorithms(mechanismName, type);
if (algorithms.contains("*")) {
try {
if (credentials.getCredentialAcquireSupport(type, null).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
} else {
for (String algorithm : algorithms) {
try {
if (credentials.getCredentialAcquireSupport(type, algorithm).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
}
}
} else {
try {
if (credentials.getCredentialAcquireSupport(type).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
}
}
// no apparent way to support the mechanism
return false;
}
Principal doRewriteUser(Principal original) {
final Function<Principal, Principal> principalRewriter = this.principalRewriter;
final Principal rewritten = principalRewriter == null ? original : principalRewriter.apply(original);
if (rewritten == null) {
throw log.invalidName();
}
return rewritten;
}
Principal getAuthorizationPrincipal() {
return authorizationNameForwardSecurityDomain != null ? authorizationNameForwardSecurityDomain.getCurrentSecurityIdentity().getPrincipal() : setAuthzPrincipal;
}
Supplier<Provider[]> getProviderSupplier() {
final Supplier<Provider[]> providerSupplier = this.providerSupplier;
return providerSupplier == null ? INSTALLED_PROVIDERS : providerSupplier;
}
SaslClientFactory getSaslClientFactory(Supplier<Provider[]> providers) {
final Supplier<SaslClientFactory> supplier = saslClientFactorySupplier;
return supplier != null ? supplier.get() : new SecurityProviderSaslClientFactory(providers);
}
SecurityFactory<X509TrustManager> getX509TrustManagerFactory() {
return trustManagerFactory == null ? SSLUtils.getDefaultX509TrustManagerSecurityFactory() : trustManagerFactory;
}
SecurityFactory<X509KeyManager> getX509KeyManagerFactory() {
return keyManagerFactory;
}
CredentialSource getCredentialSource() {
if (authenticationCredentialsForwardSecurityDomain != null) {
return doPrivileged((PrivilegedAction<IdentityCredentials>) () -> authenticationCredentialsForwardSecurityDomain.getCurrentSecurityIdentity().getPrivateCredentials(), capturedAccessContext);
} else {
return credentialSource;
}
}
// assembly methods - rewrite
/**
* Create a new configuration which is the same as this configuration, but rewrites the user name using the given
* name rewriter. The name rewriter is appended to the the existing name rewrite function.
*
* @param rewriter the name rewriter
* @return the new configuration
*/
public AuthenticationConfiguration rewriteUser(NameRewriter rewriter) {
if (rewriter == null) {
return this;
}
if (this.principalRewriter == null) {
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, rewriter.asPrincipalRewriter());
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, principalRewriter.andThen(rewriter.asPrincipalRewriter()));
}
/**
* Create a new configuration which is the same as this configuration, but rewrites the user name using <em>only</em>
* the given name rewriter. Any name rewriters on this configuration are ignored for the new configuration.
*
* @param rewriter the name rewriter
* @return the new configuration
*/
public AuthenticationConfiguration rewriteUserOnlyWith(NameRewriter rewriter) {
if (rewriter == null) {
return this;
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, rewriter.asPrincipalRewriter());
}
// assembly methods - filter
// assembly methods - configuration
/**
* Create a new configuration which is the same as this configuration, but which uses an anonymous login.
*
* @return the new configuration
*/
public AuthenticationConfiguration useAnonymous() {
return usePrincipal(AnonymousPrincipal.getInstance());
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given principal to authenticate.
*
* @param principal the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration usePrincipal(NamePrincipal principal) {
return usePrincipal((Principal) principal);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given principal to authenticate.
*
* @param principal the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration usePrincipal(Principal principal) {
Assert.checkNotNullParam("principal", principal);
if (Objects.equals(this.principal, principal)) {
return this;
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL, principal);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given login name to authenticate.
*
* @param name the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration useName(String name) {
Assert.checkNotNullParam("name", name);
return usePrincipal(new NamePrincipal(name));
}
/**
* Create a new configuration which is the same as this configuration, but which attempts to authorize to the given
* name after authentication. Only mechanisms which support an authorization name principal will be selected.
*
* @param name the name to use, or {@code null} to not request authorization in the new configuration
* @return the new configuration
*/
public AuthenticationConfiguration useAuthorizationName(String name) {
return useAuthorizationPrincipal(name == null ? null : new NamePrincipal(name));
}
/**
* Create a new configuration which is the same as this configuration, but which attempts to authorize to the given
* principal after authentication. Only mechanisms which support an authorization principal of the given type will
* be selected.
*
* @param principal the principal to use, or {@code null} to not request authorization in the new configuration
* @return the new configuration
*/
public AuthenticationConfiguration useAuthorizationPrincipal(Principal principal) {
if (Objects.equals(principal, setAuthzPrincipal)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_AUTHZ_PRINCIPAL, principal);
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given credential to authenticate.
*
* @param credential the credential to authenticate
* @return the new configuration
*/
public AuthenticationConfiguration useCredential(Credential credential) {
if (credential == null) return this;
final CredentialSource credentialSource = this.credentialSource;
if (credentialSource == CredentialSource.NONE) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, IdentityCredentials.NONE.withCredential(credential));
} else if (credentialSource instanceof IdentityCredentials) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, ((IdentityCredentials) credentialSource).withCredential(credential));
} else {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, credentialSource.with(IdentityCredentials.NONE.withCredential(credential)));
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(Password password) {
final CredentialSource filtered = getCredentialSource().without(PasswordCredential.class);
return password == null ? useCredentials(filtered) : useCredentials(filtered).useCredential(new PasswordCredential(password));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(char[] password) {
return usePassword(password == null ? null : ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, password));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(String password) {
return usePassword(password == null ? null : ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, password.toCharArray()));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler to
* acquire a password with which to authenticate, when a password-based authentication algorithm is in use.
*
* @param callbackHandler the password callback handler
* @return the new configuration
*/
public AuthenticationConfiguration useCredentialCallbackHandler(CallbackHandler callbackHandler) {
return useCallbackHandler(callbackHandler, EnumSet.of(CallbackKind.CREDENTIAL));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler
* to authenticate.
* <p>
* <em>Important notes:</em> It is important to ensure that each distinct client identity uses a distinct {@code CallbackHandler}
* instance in order to avoid mis-pooling of connections, identity crossovers, and other potentially serious problems.
* It is not recommended that a {@code CallbackHandler} implement {@code equals()} and {@code hashCode()}, however if it does,
* it is important to ensure that these methods consider equality based on an authenticating identity that does not
* change between instances. In particular, a callback handler which requests user input on each usage is likely to cause
* a problem if the user name can change on each authentication request.
* <p>
* Because {@code CallbackHandler} instances are unique per identity, it is often useful for instances to cache
* identity information, credentials, and/or other authentication-related information in order to facilitate fast
* re-authentication.
*
* @param callbackHandler the callback handler to use
* @return the new configuration
*/
public AuthenticationConfiguration useCallbackHandler(CallbackHandler callbackHandler) {
return callbackHandler == null ? this : new AuthenticationConfiguration(this, SET_USER_CBH, callbackHandler, SET_USER_CB_KINDS, EnumSet.allOf(CallbackKind.class));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler
* to authenticate.
* <p>
* <em>Important notes:</em> It is important to ensure that each distinct client identity uses a distinct {@code CallbackHandler}
* instance in order to avoid mis-pooling of connections, identity crossovers, and other potentially serious problems.
* It is not recommended that a {@code CallbackHandler} implement {@code equals()} and {@code hashCode()}, however if it does,
* it is important to ensure that these methods consider equality based on an authenticating identity that does not
* change between instances. In particular, a callback handler which requests user input on each usage is likely to cause
* a problem if the user name can change on each authentication request.
* <p>
* Because {@code CallbackHandler} instances are unique per identity, it is often useful for instances to cache
* identity information, credentials, and/or other authentication-related information in order to facilitate fast
* re-authentication.
*
* @param callbackHandler the callback handler to use
* @param callbackKinds the kinds of callbacks that the handler should use
* @return the new configuration
*/
public AuthenticationConfiguration useCallbackHandler(CallbackHandler callbackHandler, Set<CallbackKind> callbackKinds) {
return callbackHandler == null ? this : new AuthenticationConfiguration(this, SET_USER_CBH, callbackHandler, SET_USER_CB_KINDS, EnumSet.copyOf(callbackKinds));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given GSS-API credential to authenticate.
*
* @param credential the GSS-API credential to use
* @return the new configuration
*/
public AuthenticationConfiguration useGSSCredential(GSSCredential credential) {
return credential == null ? this : useCredential(new GSSKerberosCredential(credential));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStoreEntry the key store entry to use
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore.Entry keyStoreEntry) {
return keyStoreEntry == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(new FixedSecurityFactory<>(keyStoreEntry))));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStore the key store to use
* @param alias the key store alias
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore keyStore, String alias) {
return keyStore == null || alias == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(keyStore, alias, null)));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStore the key store to use
* @param alias the key store alias
* @param protectionParameter the protection parameter to use to access the key store entry
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore keyStore, String alias, KeyStore.ProtectionParameter protectionParameter) {
return keyStore == null || alias == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(keyStore, alias, protectionParameter)));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given private key and X.509
* certificate chain to authenticate.
*
* @param privateKey the client private key
* @param certificateChain the client certificate chain
* @return the new configuration
*/
public AuthenticationConfiguration useCertificateCredential(PrivateKey privateKey, X509Certificate... certificateChain) {
return certificateChain == null || certificateChain.length == 0 || privateKey == null ? this : useCertificateCredential(new X509CertificateChainPrivateCredential(privateKey, certificateChain));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given private key and X.509
* certificate chain to authenticate.
*
* @param credential the credential containing the private key and certificate chain
* @return the new configuration
*/
public AuthenticationConfiguration useCertificateCredential(X509CertificateChainPrivateCredential credential) {
return credential == null ? this : useCredential(credential);
}
/**
* Create a new configuration which is the same as this configuration, but uses credentials found at the given
* alias and credential store.
*
* @param credentialStore the credential store (must not be {@code null})
* @param alias the alias within the store (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration useCredentialStoreEntry(CredentialStore credentialStore, String alias) {
Assert.checkNotNullParam("credentialStore", credentialStore);
Assert.checkNotNullParam("alias", alias);
CredentialStoreCredentialSource csCredentialSource = new CredentialStoreCredentialSource(credentialStore, alias);
return useCredentials(getCredentialSource().with(csCredentialSource));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key manager
* to acquire the credential required for authentication.
*
* @param keyManager the key manager to use
* @return the new configuration
*/
public AuthenticationConfiguration useKeyManagerCredential(X509KeyManager keyManager) {
return new AuthenticationConfiguration(this, SET_KEY_MGR_FAC, new FixedSecurityFactory<>(keyManager));
}
/**
* Create a new configuration which is the same as this configuration, but which uses local kerberos ticket cache
* to acquire the credential required for authentication.
*
* @param mechanismOids array of oid's indicating the mechanisms over which the credential is to be acquired
* @return the new configuration
*
* @since 1.2.0
* @deprecated can be ommited - kerberos based authentication mechanism obtains credential himself
*/
@Deprecated
public AuthenticationConfiguration useLocalKerberosCredential(Oid[] mechanismOids) {
return useCredentials(getCredentialSource().with(LocalKerberosCredentialSource.builder().setMechanismOids(mechanismOids).build()));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given identity
* credentials to acquire the credential required for authentication.
*
* @param credentials the credentials to use
* @return the new configuration
*/
public AuthenticationConfiguration useCredentials(CredentialSource credentials) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, credentials == null ? CredentialSource.NONE : credentials);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given choice if the given
* predicate evaluates to {@code true}.
*
* @param matchPredicate the predicate that should be used to determine if a choice callback type and prompt are
* relevant for the given choice
* @param choice the choice to use if the given predicate evaluates to {@code true}
* @return the new configuration
*/
public AuthenticationConfiguration useChoice(BiPredicate<Class<? extends ChoiceCallback>, String> matchPredicate, String choice) {
Assert.checkNotNullParam("matchPredicate", matchPredicate);
Assert.checkNotNullParam("choice", choice);
final Predicate<Callback> callbackIntercept = this.callbackIntercept;
Predicate<Callback> newIntercept = cb -> {
if (! (cb instanceof ChoiceCallback)) {
return false;
}
final ChoiceCallback choiceCallback = (ChoiceCallback) cb;
if (matchPredicate.test(choiceCallback.getClass(), choiceCallback.getPrompt())) {
final String[] choices = choiceCallback.getChoices();
final int choicesLength = choices.length;
for (int i = 0; i < choicesLength; i++) {
if (choices[i].equals(choice)) {
choiceCallback.setSelectedIndex(i);
return true;
}
}
}
return false;
};
if (callbackIntercept == null) {
return new AuthenticationConfiguration(this, SET_CALLBACK_INTERCEPT, newIntercept);
} else {
return new AuthenticationConfiguration(this, SET_CALLBACK_INTERCEPT, newIntercept.or(callbackIntercept));
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given parameter specification.
*
* @param parameterSpec the algorithm parameter specification to use
* @return the new configuration
*/
public AuthenticationConfiguration useParameterSpec(AlgorithmParameterSpec parameterSpec) {
if (parameterSpec == null) {
return this;
}
final List<AlgorithmParameterSpec> specs = parameterSpecs;
if (specs.isEmpty()) {
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, Collections.singletonList(parameterSpec));
} else {
ArrayList<AlgorithmParameterSpec> newList = new ArrayList<>();
for (AlgorithmParameterSpec spec : specs) {
if (spec.getClass() == parameterSpec.getClass()) continue;
newList.add(spec);
}
if (newList.isEmpty()) {
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, Collections.singletonList(parameterSpec));
} else {
newList.add(parameterSpec);
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, newList);
}
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given trust manager
* for trust verification.
*
* @param trustManager the trust manager to use or {@code null} if the default trust manager should be used
* @return the new configuration
*/
public AuthenticationConfiguration useTrustManager(X509TrustManager trustManager) {
return trustManager == null ? new AuthenticationConfiguration(this, SET_TRUST_MGR_FAC, null) : new AuthenticationConfiguration(this, SET_TRUST_MGR_FAC, new FixedSecurityFactory<>(trustManager));
}
/**
* Create a new configuration which is the same as this configuration, but which connects to a different host name.
*
* @param hostName the host name to connect to
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration useHost(String hostName) {
if (hostName == null || hostName.isEmpty()) {
hostName = null;
}
if (Objects.equals(this.setHost, hostName)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_HOST, hostName);
}
}
/**
* Create a new configuration which is the same as this configuration, but which specifies a different protocol to be used for outgoing connection.
*
* @param protocol the protocol to be used for outgoing connection.
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration useProtocol(String protocol) {
if (protocol == null || protocol.isEmpty()) {
protocol = null;
}
if (Objects.equals(this.setProtocol, protocol)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_PROTOCOL, protocol);
}
}
/**
* Create a new configuration which is the same as this configuration, but which specifies a different protocol to be passed to the authentication mechanisms.
*
* @param saslProtocol the protocol to pass to the authentication mechanisms.
* @return the new configuration
*/
public AuthenticationConfiguration useSaslProtocol(String saslProtocol) {
if (saslProtocol == null || saslProtocol.isEmpty()) {
saslProtocol = null;
}
if (Objects.equals(this.saslProtocol, saslProtocol)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_SASL_PROTOCOL, saslProtocol);
}
}
/**
* Create a new configuration which is the same as this configuration, but which connects to a different port.
*
* @param port the port to connect to, or -1 to not override the port
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration usePort(int port) {
if (port < -1 || port > 65535) throw log.invalidPortNumber(port);
if (port == setPort) return this;
return new AuthenticationConfiguration(this, port);
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication name
* and credentials from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedIdentity(SecurityDomain securityDomain) {
return useForwardedAuthenticationIdentity(securityDomain).useForwardedAuthenticationCredentials(securityDomain);
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication name
* from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthenticationIdentity(SecurityDomain securityDomain) {
if (Objects.equals(authenticationNameForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTH_NAME_DOMAIN, securityDomain);
}
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication
* credentials from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthenticationCredentials(SecurityDomain securityDomain) {
if (Objects.equals(authenticationCredentialsForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTH_CRED_DOMAIN, securityDomain);
}
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authorization name
* from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthorizationIdentity(SecurityDomain securityDomain) {
if (Objects.equals(authorizationNameForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTHZ_NAME_DOMAIN, securityDomain);
}
}
// Providers
/**
* Use the given security provider supplier to locate security implementations.
*
* @param providerSupplier the provider supplier
* @return the new configuration
*/
public AuthenticationConfiguration useProviders(Supplier<Provider[]> providerSupplier) {
if (Objects.equals(this.providerSupplier, providerSupplier)) {
return this;
}
return new AuthenticationConfiguration(this, SET_PROVIDER_SUPPLIER, providerSupplier);
}
/**
* Use the default provider discovery behaviour of combining service loader discovered providers with the system default
* security providers when locating security implementations.
*
* @return the new configuration
*/
public AuthenticationConfiguration useDefaultProviders() {
return useProviders(DEFAULT_PROVIDER_SUPPLIER);
}
/**
* Use security providers from the given class loader.
*
* @param classLoader the class loader to search for security providers
* @return the new configuration
*/
public AuthenticationConfiguration useProvidersFromClassLoader(ClassLoader classLoader) {
return useProviders(new ProviderServiceLoaderSupplier(classLoader));
}
// SASL Mechanisms
/**
* Use a pre-existing {@link SaslClientFactory} instead of discovery.
*
* @param saslClientFactory the pre-existing {@link SaslClientFactory} to use.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactory(final SaslClientFactory saslClientFactory) {
return useSaslClientFactory(() -> saslClientFactory);
}
/**
* Use the given sasl client factory supplier to obtain the {@link SaslClientFactory} to use.
*
* @param saslClientFactory the sasl client factory supplier to use.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactory(final Supplier<SaslClientFactory> saslClientFactory) {
return new AuthenticationConfiguration(this, SET_SASL_FAC_SUP, saslClientFactory);
}
/**
* Use provider based discovery to load available {@link SaslClientFactory} implementations.
*
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactoryFromProviders() {
return new AuthenticationConfiguration(this, SET_SASL_FAC_SUP, null);
}
// SASL Configuration
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* Existing properties defined on this authentication context will be retained unless overridden by new properties, any
* properties resulting with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @return the new configuration.
* @deprecated use {@link #useSaslMechanismProperties(Map)}
*/
@Deprecated
public AuthenticationConfiguration useMechanismProperties(Map<String, ?> mechanismProperties) {
return useSaslMechanismProperties(mechanismProperties);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* Existing properties defined on this authentication context will be retained unless overridden by new properties, any
* properties resulting with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslMechanismProperties(Map<String, ?> mechanismProperties) {
return useSaslMechanismProperties(mechanismProperties, false);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* If exclusive the existing properties will be discarded and replaced with the new properties otherwise existing properties
* defined on this authentication context will be retained unless overridden by new properties, any properties resulting
* with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @param exclusive should the provided properties be used exclusively or merged with the existing properties?
* @return the new configuration.
* @deprecated use {@link #useSaslMechanismProperties(Map, boolean)}
*/
@Deprecated
public AuthenticationConfiguration useMechanismProperties(Map<String, ?> mechanismProperties, boolean exclusive) {
return useSaslMechanismProperties(mechanismProperties, exclusive);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* If exclusive the existing properties will be discarded and replaced with the new properties otherwise existing properties
* defined on this authentication context will be retained unless overridden by new properties, any properties resulting
* with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @param exclusive should the provided properties be used exclusively or merged with the existing properties?
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslMechanismProperties(Map<String, ?> mechanismProperties, boolean exclusive) {
if (!exclusive && (mechanismProperties == null || mechanismProperties.isEmpty())) return this;
final HashMap<String, Object> newMap = exclusive ? new HashMap<>() : new HashMap<>(this.saslMechanismProperties);
newMap.putAll(mechanismProperties);
newMap.values().removeIf(Objects::isNull);
return new AuthenticationConfiguration(this, SET_SASL_MECH_PROPS, optimizeMap(newMap));
}
private static <K, V> Map<K, V> optimizeMap(Map<K, V> orig) {
if (orig.isEmpty()) return Collections.emptyMap();
if (orig.size() == 1) {
final Map.Entry<K, V> entry = orig.entrySet().iterator().next();
return Collections.singletonMap(entry.getKey(), entry.getValue());
}
return orig;
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given kerberos security
* factory to acquire the GSS credential required for authentication.
*
* @param kerberosSecurityFactory a reference to the kerberos security factory to be use
* @return the new configuration
*/
@Deprecated
public AuthenticationConfiguration useKerberosSecurityFactory(SecurityFactory<Credential> kerberosSecurityFactory) {
CredentialSource cs = getCredentialSource();
if (kerberosSecurityFactory != null) {
return cs != null ? new AuthenticationConfiguration(this, SET_CRED_SOURCE, cs.with(new FactoryCredentialSource(kerberosSecurityFactory))) : new AuthenticationConfiguration(this, SET_CRED_SOURCE, new FactoryCredentialSource(kerberosSecurityFactory));
}
return this; // cs != null ? new AuthenticationConfiguration(this, SET_CRED_SOURCE, cs.without(GSSKerberosCredential.class)) : this;
}
/**
* Set the SASL mechanism selector for this authentication configuration.
*
* @param saslMechanismSelector the SASL mechanism selector, or {@code null} to clear the current selector
* @return the new configuration
*/
public AuthenticationConfiguration setSaslMechanismSelector(SaslMechanismSelector saslMechanismSelector) {
if (Objects.equals(this.saslMechanismSelector, saslMechanismSelector)) {
return this;
}
return new AuthenticationConfiguration(this, SET_SASL_SELECTOR, saslMechanismSelector);
}
// other
/**
* Create a new configuration which is the same as this configuration, but uses the given realm for authentication.
*
* @param realm the realm to use, or {@code null} to accept the default realm always
* @return the new configuration
*/
public AuthenticationConfiguration useRealm(String realm) {
if (Objects.equals(realm, this.setRealm)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_REALM, realm);
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given {@link BearerTokenCredential} to authenticate.
*
* @param credential the bearer token credential to use
* @return the new configuration
*/
public AuthenticationConfiguration useBearerTokenCredential(BearerTokenCredential credential) {
return credential == null ? this : useCredentials(getCredentialSource().with(IdentityCredentials.NONE.withCredential(credential)));
}
/**
* Create a new configuration which is the same as this configuration, but which captures the caller's access
* control context to be used in authentication decisions.
*
* @return the new configuration
*/
public AuthenticationConfiguration withCapturedAccessControlContext() {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, getContext());
}
// merging
/**
* Create a new configuration which is the same as this configuration, but which adds or replaces every item in the
* {@code other} configuration with that item, overwriting any corresponding such item in this configuration.
*
* @param other the other authentication configuration
* @return the merged authentication configuration
*/
public AuthenticationConfiguration with(AuthenticationConfiguration other) {
return new AuthenticationConfiguration(this, other);
}
// client methods
CallbackHandler getUserCallbackHandler() {
return userCallbackHandler;
}
EnumSet<CallbackKind> getUserCallbackKinds() {
return userCallbackKinds;
}
private SaslClientFactory getSaslClientFactory() {
if (saslClientFactory == null) {
synchronized (this) {
if (saslClientFactory == null) {
saslClientFactory = getSaslClientFactory(getProviderSupplier());
}
}
}
return saslClientFactory;
}
SaslClient createSaslClient(URI uri, Collection<String> serverMechanisms, UnaryOperator<SaslClientFactory> factoryOperator, SSLSession sslSession) throws SaslException {
SaslClientFactory saslClientFactory = factoryOperator.apply(getSaslClientFactory());
final SaslMechanismSelector selector = this.saslMechanismSelector;
serverMechanisms = (selector == null ? SaslMechanismSelector.DEFAULT : selector).apply(serverMechanisms, sslSession);
if (serverMechanisms.isEmpty()) {
return null;
}
final Principal authorizationPrincipal = getAuthorizationPrincipal();
final Predicate<String> filter;
final String authzName;
if (authorizationPrincipal == null) {
filter = this::saslSupportedByConfiguration;
authzName = null;
} else if (authorizationPrincipal instanceof NamePrincipal) {
filter = this::saslSupportedByConfiguration;
authzName = authorizationPrincipal.getName();
} else if (authorizationPrincipal instanceof AnonymousPrincipal) {
filter = ((Predicate<String>) this::saslSupportedByConfiguration).and("ANONYMOUS"::equals);
authzName = null;
} else {
return null;
}
Map<String, ?> mechanismProperties = this.saslMechanismProperties;
if (! mechanismProperties.isEmpty()) {
mechanismProperties = new HashMap<>(mechanismProperties);
// special handling for JBOSS-LOCAL-USER quiet auth... only pass it through if we have a user callback
if (! userCallbackKinds.contains(CallbackKind.PRINCIPAL) && principal != AnonymousPrincipal.getInstance()) {
mechanismProperties.remove(LocalUserClient.QUIET_AUTH);
mechanismProperties.remove(LocalUserClient.LEGACY_QUIET_AUTH);
}
if (! mechanismProperties.isEmpty()) {
saslClientFactory = new PropertiesSaslClientFactory(saslClientFactory, mechanismProperties);
}
}
String host = uri.getHost();
if (host != null) {
saslClientFactory = new ServerNameSaslClientFactory(saslClientFactory, host);
}
String protocol = getSaslProtocol();
if (protocol != null) {
saslClientFactory = new ProtocolSaslClientFactory(saslClientFactory, protocol);
}
if (sslSession != null) {
saslClientFactory = new SSLSaslClientFactory(() -> SSLConnection.forSession(sslSession, true), saslClientFactory);
}
saslClientFactory = new LocalPrincipalSaslClientFactory(new FilterMechanismSaslClientFactory(saslClientFactory, filter));
final SaslClientFactory finalSaslClientFactory = saslClientFactory;
saslClientFactory = doPrivileged((PrivilegedAction<PrivilegedSaslClientFactory>) () -> new PrivilegedSaslClientFactory(finalSaslClientFactory), capturedAccessContext);
SaslClient saslClient = saslClientFactory.createSaslClient(serverMechanisms.toArray(NO_STRINGS),
authzName, uri.getScheme(), uri.getHost(), Collections.emptyMap(), createCallbackHandler());
if (log.isTraceEnabled()) {
log.tracef("Created SaslClient [%s] for mechanisms %s", saslClient, Arrays2.objectToString(serverMechanisms));
}
return saslClient;
}
CallbackHandler createCallbackHandler() {
return new ClientCallbackHandler(this);
}
// equality
/**
* Determine whether this configuration is equal to another object. Two configurations are equal if they
* apply the same items.
*
* @param obj the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(final Object obj) {
return obj instanceof AuthenticationConfiguration && equals((AuthenticationConfiguration) obj);
}
/**
* Determine whether this configuration is equal to another object. Two configurations are equal if they
* apply the same items.
*
* @param other the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(final AuthenticationConfiguration other) {
return hashCode() == other.hashCode()
&& Objects.equals(principal, other.principal)
&& Objects.equals(setHost, other.setHost)
&& Objects.equals(setProtocol, other.setProtocol)
&& Objects.equals(setRealm, other.setRealm)
&& Objects.equals(setAuthzPrincipal, other.setAuthzPrincipal)
&& Objects.equals(authenticationNameForwardSecurityDomain, other.authenticationNameForwardSecurityDomain)
&& Objects.equals(authenticationCredentialsForwardSecurityDomain, other.authenticationCredentialsForwardSecurityDomain)
&& Objects.equals(authorizationNameForwardSecurityDomain, other.authorizationNameForwardSecurityDomain)
&& Objects.equals(userCallbackHandler, other.userCallbackHandler)
&& Objects.equals(userCallbackKinds, other.userCallbackKinds)
&& Objects.equals(credentialSource, other.credentialSource)
&& this.setPort == other.setPort
&& Objects.equals(providerSupplier, other.providerSupplier)
&& Objects.equals(keyManagerFactory, other.keyManagerFactory)
&& Objects.equals(saslMechanismSelector, other.saslMechanismSelector)
&& Objects.equals(principalRewriter, other.principalRewriter)
&& Objects.equals(saslClientFactorySupplier, other.saslClientFactorySupplier)
&& Objects.equals(parameterSpecs, other.parameterSpecs)
&& Objects.equals(trustManagerFactory, other.trustManagerFactory)
&& Objects.equals(saslMechanismProperties, other.saslMechanismProperties)
&& Objects.equals(saslProtocol, other.saslProtocol);
}
/**
* Get the hash code of this authentication configuration.
*
* @return the hash code of this authentication configuration
*/
public int hashCode() {
int hashCode = this.hashCode;
if (hashCode == 0) {
hashCode = Objects.hash(
principal, setHost, setProtocol, setRealm, setAuthzPrincipal, authenticationNameForwardSecurityDomain,
authenticationCredentialsForwardSecurityDomain, authorizationNameForwardSecurityDomain, userCallbackHandler, credentialSource,
providerSupplier, keyManagerFactory, saslMechanismSelector, principalRewriter, saslClientFactorySupplier, parameterSpecs, trustManagerFactory,
saslMechanismProperties, saslProtocol) * 19 + setPort;
if (hashCode == 0) {
hashCode = 1;
}
this.hashCode = hashCode;
}
return hashCode;
}
// String Representation
@Override
public String toString() {
String toString = this.toString;
if (toString == null) {
StringBuilder b = new StringBuilder(64);
b.append("AuthenticationConfiguration:");
b.append("principal=").append(principal).append(',');
if (setAuthzPrincipal != null) b.append("authorization-id=").append(setAuthzPrincipal).append(',');
if (setHost != null) b.append("set-host=").append(setHost).append(',');
if (setProtocol != null) b.append("set-protocol=").append(setProtocol).append(',');
if (saslProtocol != null) b.append("sasl-protocol-name=").append(saslProtocol).append(',');
if (setPort != -1) b.append("set-port=").append(setPort).append(',');
if (setRealm != null) b.append("set-realm=").append(setRealm).append(',');
if (authenticationNameForwardSecurityDomain != null) b.append("forwarding-authentication-name,");
if (authenticationCredentialsForwardSecurityDomain != null) b.append("forwarding-authentication-credentials,");
if (authorizationNameForwardSecurityDomain != null) b.append("forwarding-authorization-name,");
if (userCallbackHandler != null) b.append("user-callback-handler=").append(userCallbackHandler).append(',');
if (! userCallbackKinds.isEmpty()) b.append("user-callback-kinds=").append(userCallbackKinds).append(',');
if (credentialSource != null && credentialSource != CredentialSource.NONE && credentialSource != IdentityCredentials.NONE) b.append("credentials-present,");
if (providerSupplier != null) b.append("providers-supplier=").append(providerSupplier).append(',');
if (keyManagerFactory != null) b.append("key-manager-factory=").append(keyManagerFactory).append(',');
if (saslMechanismSelector != null) b.append("sasl-mechanism-selector=").append(saslMechanismSelector).append(',');
if (principalRewriter != null) b.append("principal-rewriter=").append(principalRewriter).append(',');
if (saslClientFactorySupplier != null) b.append("sasl-client-factory-supplier=").append(saslClientFactorySupplier).append(',');
if (! parameterSpecs.isEmpty()) b.append("parameter-specifications=").append(parameterSpecs).append(',');
if (trustManagerFactory != null) b.append("trust-manager-factory=").append(trustManagerFactory).append(',');
if (! saslMechanismProperties.isEmpty()) b.append("mechanism-properties=").append(saslMechanismProperties).append(',');
b.setLength(b.length() - 1);
return this.toString = b.toString();
}
return toString;
}
//user callback sanitation
private void sanitazeOnMutation(final int what) {
switch (what) {
case SET_PRINCIPAL:
// CallbackKind.PRINCIPAL
if (this.principal != null && ! this.principal.equals(AnonymousPrincipal.getInstance())) {
this.userCallbackKinds.remove(CallbackKind.PRINCIPAL);
}
break;
case SET_CRED_SOURCE:
// CallbackKind.CREDENTIAL
if (this.credentialSource != null && ! this.credentialSource.equals(IdentityCredentials.NONE)) {
this.userCallbackKinds.remove(CallbackKind.CREDENTIAL);
}
break;
case SET_REALM:
// CallbackKind.REALM
this.userCallbackKinds.remove(CallbackKind.REALM);
break;
case SET_PARAM_SPECS:
// CallbackKind.PARAMETERS
this.userCallbackKinds.remove(CallbackKind.PARAMETERS);
break;
case SET_KEY_MGR_FAC:
// CallbackKind.PEER_CREDENTIAL
this.userCallbackKinds.remove(CallbackKind.PEER_CREDENTIAL);
break;
case SET_USER_CB_KINDS:
// SANITAZE on above content
if (this.principal != null) {
sanitazeOnMutation(SET_PRINCIPAL);
}
if (this.credentialSource != null) {
sanitazeOnMutation(SET_CRED_SOURCE);
}
if (this.setRealm != null) {
sanitazeOnMutation(SET_REALM);
}
if (this.parameterSpecs != null) {
sanitazeOnMutation(SET_PARAM_SPECS);
}
if (this.keyManagerFactory != null) {
sanitazeOnMutation(SET_KEY_MGR_FAC);
}
break;
}
}
AccessControlContext getCapturedContext() {
return capturedAccessContext;
}
// delegates for equality tests
// interfaces
static class ClientCallbackHandler implements CallbackHandler {
private final AuthenticationConfiguration config;
private final CallbackHandler userCallbackHandler;
private List<TrustedAuthority> trustedAuthorities;
private SSLConnection sslConnection;
ClientCallbackHandler(final AuthenticationConfiguration config) {
this.config = config;
userCallbackHandler = config.getUserCallbackHandler();
}
@SuppressWarnings("UnnecessaryContinue")
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
final AuthenticationConfiguration config = this.config;
final Predicate<Callback> callbackIntercept = config.callbackIntercept;
final ArrayList<Callback> userCallbacks = new ArrayList<>(callbacks.length);
for (final Callback callback : callbacks) {
if (callbackIntercept != null && callbackIntercept.test(callback)) {
continue;
} else if (callback instanceof NameCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PRINCIPAL)) {
userCallbacks.add(callback);
continue;
}
final NameCallback nameCallback = (NameCallback) callback;
// populate with our authentication name
final Principal principal = config.getPrincipal();
if (principal instanceof AnonymousPrincipal) {
final String defaultName = nameCallback.getDefaultName();
if (defaultName != null) {
nameCallback.setName(defaultName);
}
// otherwise set nothing; the mech can decide if that's OK or not
continue;
} else {
nameCallback.setName(config.doRewriteUser(principal).getName());
continue;
}
} else if (callback instanceof PasswordCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final PasswordCallback passwordCallback = (PasswordCallback) callback;
final CredentialSource credentials = config.getCredentialSource();
if (credentials != null) {
final TwoWayPassword password = credentials.applyToCredential(PasswordCredential.class, ClearPassword.ALGORITHM_CLEAR, c -> c.getPassword(TwoWayPassword.class));
if (password instanceof ClearPassword) {
// shortcut
passwordCallback.setPassword(((ClearPassword) password).getPassword());
continue;
} else if (password != null) try {
PasswordFactory passwordFactory = PasswordFactory.getInstance(password.getAlgorithm());
ClearPasswordSpec clearPasswordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), ClearPasswordSpec.class);
passwordCallback.setPassword(clearPasswordSpec.getEncodedPassword());
continue;
} catch (GeneralSecurityException e) {
// not supported
CallbackUtil.unsupported(passwordCallback);
continue;
}
else {
// supported but no credentials
continue;
}
} else {
// supported but no credentials
continue;
}
} else if (callback instanceof PasswordResetCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL_RESET)) {
userCallbacks.add(callback);
continue;
}
// not supported
CallbackUtil.unsupported(callback);
continue;
} else if (callback instanceof CredentialCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final CredentialCallback credentialCallback = (CredentialCallback) callback;
// special handling for X.509 when a key manager factory is set
final SecurityFactory<X509KeyManager> keyManagerFactory = config.getX509KeyManagerFactory();
if (keyManagerFactory != null) {
final String allowedAlgorithm = credentialCallback.getAlgorithm();
if (allowedAlgorithm != null && credentialCallback.isCredentialTypeSupported(X509CertificateChainPrivateCredential.class, allowedAlgorithm)) {
final X509KeyManager keyManager;
try {
keyManager = keyManagerFactory.create();
} catch (GeneralSecurityException e) {
throw log.unableToCreateKeyManager(e);
}
Principal[] acceptableIssuers;
if (trustedAuthorities != null) {
List<Principal> issuers = new ArrayList<Principal>();
for (TrustedAuthority trustedAuthority : trustedAuthorities) {
if (trustedAuthority instanceof TrustedAuthority.CertificateTrustedAuthority) {
final X509Certificate authorityCertificate = ((TrustedAuthority.CertificateTrustedAuthority) trustedAuthority).getIdentifier();
issuers.add(authorityCertificate.getSubjectX500Principal());
} else if (trustedAuthority instanceof TrustedAuthority.NameTrustedAuthority) {
final String authorityName = ((TrustedAuthority.NameTrustedAuthority) trustedAuthority).getIdentifier();
issuers.add(new X500Principal(authorityName));
}
}
acceptableIssuers = issuers.toArray(NO_PRINCIPALS);
} else {
acceptableIssuers = null;
}
final String alias = keyManager.chooseClientAlias(new String[] { allowedAlgorithm }, acceptableIssuers, null);
if (alias != null) {
final X509Certificate[] certificateChain = keyManager.getCertificateChain(alias);
final PrivateKey privateKey = keyManager.getPrivateKey(alias);
credentialCallback.setCredential(new X509CertificateChainPrivateCredential(privateKey, certificateChain));
continue;
}
// otherwise fall out to normal handling
}
}
// normal handling
final Credential credential = config.getCredentialSource().getCredential(credentialCallback.getCredentialType(), credentialCallback.getAlgorithm(), credentialCallback.getParameterSpec());
if (credential != null && credentialCallback.isCredentialSupported(credential)) {
credentialCallback.setCredential(credential);
continue;
} else {
// supported but no credentials
continue;
}
} else if (callback instanceof RealmChoiceCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.REALM)) {
userCallbacks.add(callback);
continue;
}
final RealmChoiceCallback realmChoiceCallback = (RealmChoiceCallback) callback;
// find our realm
final String realm = config.setRealm;
if (realm == null) {
realmChoiceCallback.setSelectedIndex(realmChoiceCallback.getDefaultChoice());
continue;
} else {
String[] choices = realmChoiceCallback.getChoices();
for (int i = 0; i < choices.length; i++) {
if (realm.equals(choices[i])) {
realmChoiceCallback.setSelectedIndex(i);
break;
}
}
// no choice matches, so just fall out and choose nothing
continue;
}
} else if (callback instanceof RealmCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.REALM)) {
userCallbacks.add(callback);
continue;
}
RealmCallback realmCallback = (RealmCallback) callback;
final String realm = config.setRealm;
realmCallback.setText(realm != null ? realm : realmCallback.getDefaultText());
continue;
} else if (callback instanceof ParameterCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PARAMETERS)) {
userCallbacks.add(callback);
continue;
}
ParameterCallback parameterCallback = (ParameterCallback) callback;
if (parameterCallback.getParameterSpec() == null) {
for (AlgorithmParameterSpec parameterSpec : config.parameterSpecs) {
if (parameterCallback.isParameterSupported(parameterSpec)) {
parameterCallback.setParameterSpec(parameterSpec);
break; // inner loop break
}
}
}
continue;
} else if (callback instanceof SSLCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.SSL)) {
userCallbacks.add(callback);
continue;
}
SSLCallback sslCallback = (SSLCallback) callback;
this.sslConnection = sslCallback.getSslConnection();
continue;
} else if (callback instanceof ChannelBindingCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CHANNEL_BINDING)) {
userCallbacks.add(callback);
continue;
}
final SSLConnection sslConnection = this.sslConnection;
if (sslConnection != null) {
sslConnection.handleChannelBindingCallback((ChannelBindingCallback) callback);
}
continue;
} else if (callback instanceof ChoiceCallback) { // Must come AFTER RealmChoiceCallback
if (config.getUserCallbackKinds().contains(CallbackKind.CHOICE)) {
userCallbacks.add(callback);
continue;
}
final ChoiceCallback choiceCallback = (ChoiceCallback) callback;
choiceCallback.setSelectedIndex(choiceCallback.getDefaultChoice());
continue;
} else if (callback instanceof TrustedAuthoritiesCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.SERVER_TRUSTED_AUTHORITIES)) {
userCallbacks.add(callback);
continue;
}
final TrustedAuthoritiesCallback trustedAuthoritiesCallback = (TrustedAuthoritiesCallback) callback;
final List<TrustedAuthority> trustedAuthoritiesHolder = trustedAuthoritiesCallback.getTrustedAuthorities();
if (trustedAuthoritiesHolder != null) {
if (trustedAuthorities == null) {
trustedAuthorities = new ArrayList<>(trustedAuthoritiesHolder);
} else {
final List<TrustedAuthority> authorities = new ArrayList<>(trustedAuthoritiesHolder);
authorities.removeIf(trustedAuthorities::contains);
trustedAuthorities.addAll(authorities);
}
}
continue;
} else if (callback instanceof EvidenceVerifyCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PEER_CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final EvidenceVerifyCallback evidenceVerifyCallback = (EvidenceVerifyCallback) callback;
// special handling for X.509
final SecurityFactory<X509TrustManager> trustManagerFactory = config.getX509TrustManagerFactory();
if (trustManagerFactory != null) {
final X509PeerCertificateChainEvidence peerCertificateChainEvidence = evidenceVerifyCallback.getEvidence(X509PeerCertificateChainEvidence.class);
if (peerCertificateChainEvidence != null) {
X509TrustManager trustManager;
try {
trustManager = trustManagerFactory.create();
} catch (GeneralSecurityException e) {
throw log.unableToCreateTrustManager(e);
}
try {
trustManager.checkServerTrusted(peerCertificateChainEvidence.getPeerCertificateChain(), peerCertificateChainEvidence.getAlgorithm());
evidenceVerifyCallback.setVerified(true);
} catch (CertificateException e) {
}
continue;
}
}
continue;
} else if (callback instanceof TextOutputCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.GENERAL_OUTPUT)) {
userCallbacks.add(callback);
continue;
}
// ignore
continue;
} else if (callback instanceof TextInputCallback) { // must come after RealmCallback
if (config.getUserCallbackKinds().contains(CallbackKind.GENERAL_INPUT)) {
userCallbacks.add(callback);
continue;
}
// always choose the default
final TextInputCallback inputCallback = (TextInputCallback) callback;
final String text = inputCallback.getText();
if (text == null) {
final String defaultText = inputCallback.getDefaultText();
if (defaultText != null) {
inputCallback.setText(defaultText);
} else {
CallbackUtil.unsupported(callback);
continue;
}
}
continue;
} else if (userCallbackHandler != null) {
userCallbacks.add(callback);
} else {
CallbackUtil.unsupported(callback);
continue;
}
}
if (! userCallbacks.isEmpty()) {
// pass on to the user callback handler
assert userCallbackHandler != null; // otherwise userCallbacks would be empty
final Callback[] userCallbackArray = userCallbacks.toArray(NO_CALLBACKS);
userCallbackHandler.handle(userCallbackArray);
}
}
}
}
| src/main/java/org/wildfly/security/auth/client/AuthenticationConfiguration.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth.client;
import static java.security.AccessController.doPrivileged;
import static java.security.AccessController.getContext;
import static org.wildfly.security._private.ElytronMessages.log;
import static org.wildfly.security.util.ProviderUtil.INSTALLED_PROVIDERS;
import java.io.IOException;
import java.net.URI;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ChoiceCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.x500.X500Principal;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.RealmChoiceCallback;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.Oid;
import org.wildfly.common.Assert;
import org.wildfly.common.annotation.NotNull;
import org.wildfly.security.FixedSecurityFactory;
import org.wildfly.security.SecurityFactory;
import org.wildfly.security.WildFlyElytronProvider;
import org.wildfly.security.auth.callback.CallbackUtil;
import org.wildfly.security.auth.callback.ChannelBindingCallback;
import org.wildfly.security.auth.callback.CredentialCallback;
import org.wildfly.security.auth.callback.EvidenceVerifyCallback;
import org.wildfly.security.auth.callback.ParameterCallback;
import org.wildfly.security.auth.callback.PasswordResetCallback;
import org.wildfly.security.auth.callback.SSLCallback;
import org.wildfly.security.auth.callback.TrustedAuthoritiesCallback;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.IdentityCredentials;
import org.wildfly.security.auth.server.NameRewriter;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.credential.AlgorithmCredential;
import org.wildfly.security.credential.BearerTokenCredential;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.X509CertificateChainPrivateCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.credential.source.CredentialStoreCredentialSource;
import org.wildfly.security.credential.source.FactoryCredentialSource;
import org.wildfly.security.credential.source.KeyStoreCredentialSource;
import org.wildfly.security.credential.source.LocalKerberosCredentialSource;
import org.wildfly.security.credential.store.CredentialStore;
import org.wildfly.security.evidence.X509PeerCertificateChainEvidence;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.TwoWayPassword;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.password.spec.ClearPasswordSpec;
import org.wildfly.security.sasl.SaslMechanismSelector;
import org.wildfly.security.sasl.localuser.LocalUserClient;
import org.wildfly.security.sasl.localuser.LocalUserSaslFactory;
import org.wildfly.security.sasl.util.FilterMechanismSaslClientFactory;
import org.wildfly.security.sasl.util.LocalPrincipalSaslClientFactory;
import org.wildfly.security.sasl.util.PrivilegedSaslClientFactory;
import org.wildfly.security.sasl.util.PropertiesSaslClientFactory;
import org.wildfly.security.sasl.util.ProtocolSaslClientFactory;
import org.wildfly.security.sasl.util.SSLSaslClientFactory;
import org.wildfly.security.sasl.util.SaslMechanismInformation;
import org.wildfly.security.sasl.util.SecurityProviderSaslClientFactory;
import org.wildfly.security.sasl.util.ServerNameSaslClientFactory;
import org.wildfly.security.ssl.SSLConnection;
import org.wildfly.security.ssl.SSLUtils;
import org.wildfly.security.util.ProviderServiceLoaderSupplier;
import org.wildfly.security.util.ProviderUtil;
import org.wildfly.security.util._private.Arrays2;
import org.wildfly.security.x500.TrustedAuthority;
/**
* A configuration which controls how authentication is performed.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
public final class AuthenticationConfiguration {
// constants
private static final Principal[] NO_PRINCIPALS = new Principal[0];
private static final Callback[] NO_CALLBACKS = new Callback[0];
private static final String[] NO_STRINGS = new String[0];
private static final EnumSet<CallbackKind> NO_CALLBACK_KINDS = EnumSet.noneOf(CallbackKind.class);
private static final int SET_PRINCIPAL = 0;
private static final int SET_HOST = 1;
private static final int SET_PROTOCOL = 2;
private static final int SET_REALM = 3;
private static final int SET_AUTHZ_PRINCIPAL = 4;
private static final int SET_FWD_AUTH_NAME_DOMAIN = 5;
private static final int SET_USER_CBH = 6;
private static final int SET_USER_CB_KINDS = 7;
private static final int SET_CRED_SOURCE = 8;
private static final int SET_PROVIDER_SUPPLIER = 9;
private static final int SET_KEY_MGR_FAC = 10;
private static final int SET_SASL_SELECTOR = 11;
private static final int SET_FWD_AUTH_CRED_DOMAIN = 12;
private static final int SET_PRINCIPAL_RW = 13;
private static final int SET_SASL_FAC_SUP = 14;
private static final int SET_PARAM_SPECS = 15;
private static final int SET_TRUST_MGR_FAC = 16;
private static final int SET_SASL_MECH_PROPS = 17;
private static final int SET_ACCESS_CTXT = 18;
private static final int SET_CALLBACK_INTERCEPT = 19;
private static final int SET_SASL_PROTOCOL = 20;
private static final int SET_FWD_AUTHZ_NAME_DOMAIN = 21;
private static final Supplier<Provider[]> DEFAULT_PROVIDER_SUPPLIER = ProviderUtil.aggregate(
() -> new Provider[] {
WildFlySecurityManager.isChecking() ?
AccessController.doPrivileged((PrivilegedAction<WildFlyElytronProvider>) () -> new WildFlyElytronProvider()) :
new WildFlyElytronProvider()
},
WildFlySecurityManager.isChecking() ?
AccessController.doPrivileged((PrivilegedAction<ProviderServiceLoaderSupplier>) () -> new ProviderServiceLoaderSupplier(AuthenticationConfiguration.class.getClassLoader(), true)) :
new ProviderServiceLoaderSupplier(AuthenticationConfiguration.class.getClassLoader(), true),
INSTALLED_PROVIDERS);
/**
* An empty configuration which can be used as the basis for any configuration. This configuration supports no
* remapping of any kind, and always uses an anonymous principal.
* @deprecated to obtain empty configuration use {@link #empty()} method instead
*/
@Deprecated
public static final AuthenticationConfiguration EMPTY = new AuthenticationConfiguration();
/**
* An empty configuration which can be used as the basis for any configuration. This configuration supports no
* remapping of any kind, and always uses an anonymous principal.
*/
public static AuthenticationConfiguration empty() {
return EMPTY;
}
private volatile SaslClientFactory saslClientFactory = null;
private int hashCode;
private String toString;
final AccessControlContext capturedAccessContext;
@NotNull final Principal principal;
final String setHost;
final String setProtocol;
final String setRealm;
final Principal setAuthzPrincipal;
final SecurityDomain authenticationNameForwardSecurityDomain;
final SecurityDomain authenticationCredentialsForwardSecurityDomain;
final SecurityDomain authorizationNameForwardSecurityDomain;
final CallbackHandler userCallbackHandler;
final EnumSet<CallbackKind> userCallbackKinds;
final CredentialSource credentialSource;
final int setPort;
final Supplier<Provider[]> providerSupplier;
final SecurityFactory<X509KeyManager> keyManagerFactory;
final SaslMechanismSelector saslMechanismSelector;
final Function<Principal, Principal> principalRewriter;
final Supplier<SaslClientFactory> saslClientFactorySupplier;
final List<AlgorithmParameterSpec> parameterSpecs;
final SecurityFactory<X509TrustManager> trustManagerFactory;
final Map<String, ?> saslMechanismProperties;
final Predicate<Callback> callbackIntercept;
final String saslProtocol;
// constructors
/**
* Construct the empty configuration instance.
*/
private AuthenticationConfiguration() {
this.capturedAccessContext = null;
this.principal = AnonymousPrincipal.getInstance();
this.setHost = null;
this.setProtocol = null;
this.setRealm = null;
this.setAuthzPrincipal = null;
this.authenticationNameForwardSecurityDomain = null;
this.authenticationCredentialsForwardSecurityDomain = null;
this.authorizationNameForwardSecurityDomain = null;
this.userCallbackHandler = null;
this.userCallbackKinds = NO_CALLBACK_KINDS;
this.credentialSource = IdentityCredentials.NONE;
this.setPort = -1;
this.providerSupplier = DEFAULT_PROVIDER_SUPPLIER;
this.keyManagerFactory = null;
this.saslMechanismSelector = null;
this.principalRewriter = null;
this.saslClientFactorySupplier = null;
this.parameterSpecs = Collections.emptyList();
this.trustManagerFactory = null;
this.saslMechanismProperties = Collections.singletonMap(LocalUserClient.QUIET_AUTH, "true");
this.callbackIntercept = null;
this.saslProtocol = null;
}
/**
* Copy constructor for mutating one object field. It's not pretty but the alternative (many constructors) is much
* worse.
*
* @param original the original configuration (must not be {@code null})
* @param what the field to mutate
* @param value the field value to set
*/
@SuppressWarnings("unchecked")
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int what, final Object value) {
this.capturedAccessContext = what == SET_ACCESS_CTXT ? (AccessControlContext) value : original.capturedAccessContext;
this.principal = what == SET_PRINCIPAL ? (Principal) value : original.principal;
this.setHost = what == SET_HOST ? (String) value : original.setHost;
this.setProtocol = what == SET_PROTOCOL ? (String) value : original.setProtocol;
this.setRealm = what == SET_REALM ? (String) value : original.setRealm;
this.setAuthzPrincipal = what == SET_AUTHZ_PRINCIPAL ? (Principal) value : original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = what == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value : original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = what == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value : original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = what == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value : original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = what == SET_USER_CBH ? (CallbackHandler) value : original.userCallbackHandler;
this.userCallbackKinds = (what == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value : original.userCallbackKinds).clone();
this.credentialSource = what == SET_CRED_SOURCE ? (CredentialSource) value : original.credentialSource;
this.setPort = original.setPort;
this.providerSupplier = what == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value : original.providerSupplier;
this.keyManagerFactory = what == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value : original.keyManagerFactory;
this.saslMechanismSelector = what == SET_SASL_SELECTOR ? (SaslMechanismSelector) value : original.saslMechanismSelector;
this.principalRewriter = what == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value : original.principalRewriter;
this.saslClientFactorySupplier = what == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value : original.saslClientFactorySupplier;
this.parameterSpecs = what == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value : original.parameterSpecs;
this.trustManagerFactory = what == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value : original.trustManagerFactory;
this.saslMechanismProperties = what == SET_SASL_MECH_PROPS ? (Map<String, ?>) value : original.saslMechanismProperties;
this.callbackIntercept = what == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value : original.callbackIntercept;
this.saslProtocol = what == SET_SASL_PROTOCOL ? (String) value : original.saslProtocol;
sanitazeOnMutation(what);
}
/**
* Copy constructor for mutating two object fields. It's not pretty but the alternative (many constructors) is much
* worse.
*
* @param original the original configuration (must not be {@code null})
* @param what1 the field to mutate
* @param value1 the field value to set
* @param what2 the field to mutate
* @param value2 the field value to set
*/
@SuppressWarnings("unchecked")
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int what1, final Object value1, final int what2, final Object value2) {
this.capturedAccessContext = what1 == SET_ACCESS_CTXT ? (AccessControlContext) value1 : what2 == SET_ACCESS_CTXT ? (AccessControlContext) value2 : original.capturedAccessContext;
this.principal = what1 == SET_PRINCIPAL ? (Principal) value1 : what2 == SET_PRINCIPAL ? (Principal) value2 : original.principal;
this.setHost = what1 == SET_HOST ? (String) value1 : what2 == SET_HOST ? (String) value2 : original.setHost;
this.setProtocol = what1 == SET_PROTOCOL ? (String) value1 : what2 == SET_PROTOCOL ? (String) value2 : original.setProtocol;
this.setRealm = what1 == SET_REALM ? (String) value1 : what2 == SET_REALM ? (String) value2 : original.setRealm;
this.setAuthzPrincipal = what1 == SET_AUTHZ_PRINCIPAL ? (Principal) value1 : what2 == SET_AUTHZ_PRINCIPAL ? (Principal) value2 : original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = what1 == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTH_NAME_DOMAIN ? (SecurityDomain) value2 : original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = what1 == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTH_CRED_DOMAIN ? (SecurityDomain) value2 : original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = what1 == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value1 : what2 == SET_FWD_AUTHZ_NAME_DOMAIN ? (SecurityDomain) value2 : original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = what1 == SET_USER_CBH ? (CallbackHandler) value1 : what2 == SET_USER_CBH ? (CallbackHandler) value2 : original.userCallbackHandler;
this.userCallbackKinds = (what1 == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value1 : what2 == SET_USER_CB_KINDS ? (EnumSet<CallbackKind>) value2 : original.userCallbackKinds).clone();
this.credentialSource = what1 == SET_CRED_SOURCE ? (CredentialSource) value1 : what2 == SET_CRED_SOURCE ? (CredentialSource) value2 : original.credentialSource;
this.setPort = original.setPort;
this.providerSupplier = what1 == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value1 : what2 == SET_PROVIDER_SUPPLIER ? (Supplier<Provider[]>) value2 : original.providerSupplier;
this.keyManagerFactory = what1 == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value1 : what2 == SET_KEY_MGR_FAC ? (SecurityFactory<X509KeyManager>) value2 : original.keyManagerFactory;
this.saslMechanismSelector = what1 == SET_SASL_SELECTOR ? (SaslMechanismSelector) value1 : what2 == SET_SASL_SELECTOR ? (SaslMechanismSelector) value2 : original.saslMechanismSelector;
this.principalRewriter = what1 == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value1 : what2 == SET_PRINCIPAL_RW ? (Function<Principal, Principal>) value2 : original.principalRewriter;
this.saslClientFactorySupplier = what1 == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value1 : what2 == SET_SASL_FAC_SUP ? (Supplier<SaslClientFactory>) value2 : original.saslClientFactorySupplier;
this.parameterSpecs = what1 == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value1 : what2 == SET_PARAM_SPECS ? (List<AlgorithmParameterSpec>) value2 : original.parameterSpecs;
this.trustManagerFactory = what1 == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value1 : what2 == SET_TRUST_MGR_FAC ? (SecurityFactory<X509TrustManager>) value2 : original.trustManagerFactory;
this.saslMechanismProperties = what1 == SET_SASL_MECH_PROPS ? (Map<String, ?>) value1 : what2 == SET_SASL_MECH_PROPS ? (Map<String, ?>) value2 : original.saslMechanismProperties;
this.callbackIntercept = what1 == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value1 : what2 == SET_CALLBACK_INTERCEPT ? (Predicate<Callback>) value2 : original.callbackIntercept;
this.saslProtocol = what1 == SET_SASL_PROTOCOL ? (String) value1 : what2 == SET_SASL_PROTOCOL ? (String) value2 : original.saslProtocol;
sanitazeOnMutation(what1);
sanitazeOnMutation(what2);
}
/**
* Copy constructor for mutating the port number.
*
* @param original the original configuration (must not be {@code null})
* @param port the port number
*/
private AuthenticationConfiguration(final AuthenticationConfiguration original, final int port) {
this.capturedAccessContext = original.capturedAccessContext;
this.principal = original.principal;
this.setHost = original.setHost;
this.setProtocol = original.setProtocol;
this.setRealm = original.setRealm;
this.setAuthzPrincipal = original.setAuthzPrincipal;
this.authenticationNameForwardSecurityDomain = original.authenticationNameForwardSecurityDomain;
this.authenticationCredentialsForwardSecurityDomain = original.authenticationCredentialsForwardSecurityDomain;
this.authorizationNameForwardSecurityDomain = original.authorizationNameForwardSecurityDomain;
this.userCallbackHandler = original.userCallbackHandler;
this.userCallbackKinds = original.userCallbackKinds;
this.credentialSource = original.credentialSource;
this.setPort = port;
this.providerSupplier = original.providerSupplier;
this.keyManagerFactory = original.keyManagerFactory;
this.saslMechanismSelector = original.saslMechanismSelector;
this.principalRewriter = original.principalRewriter;
this.saslClientFactorySupplier = original.saslClientFactorySupplier;
this.parameterSpecs = original.parameterSpecs;
this.trustManagerFactory = original.trustManagerFactory;
this.saslMechanismProperties = original.saslMechanismProperties;
this.callbackIntercept = original.callbackIntercept;
this.saslProtocol = original.saslProtocol;
}
private AuthenticationConfiguration(final AuthenticationConfiguration original, final AuthenticationConfiguration other) {
this.capturedAccessContext = getOrDefault(other.capturedAccessContext, original.capturedAccessContext);
this.principal = other.principal instanceof AnonymousPrincipal ? original.principal : other.principal;
this.setHost = getOrDefault(other.setHost, original.setHost);
this.setProtocol = getOrDefault(other.setProtocol, original.setProtocol);
this.setRealm = getOrDefault(other.setRealm, original.setRealm);
this.setAuthzPrincipal = getOrDefault(other.setAuthzPrincipal, original.setAuthzPrincipal);
this.authenticationNameForwardSecurityDomain = getOrDefault(other.authenticationNameForwardSecurityDomain, original.authenticationNameForwardSecurityDomain);
this.authenticationCredentialsForwardSecurityDomain = getOrDefault(other.authenticationCredentialsForwardSecurityDomain, original.authenticationCredentialsForwardSecurityDomain);
this.authorizationNameForwardSecurityDomain = getOrDefault(other.authorizationNameForwardSecurityDomain, original.authorizationNameForwardSecurityDomain);
this.userCallbackHandler = getOrDefault(other.userCallbackHandler, original.userCallbackHandler);
this.userCallbackKinds = getOrDefault(other.userCallbackKinds, original.userCallbackKinds).clone();
this.credentialSource = other.credentialSource == IdentityCredentials.NONE ? original.credentialSource : other.credentialSource;
this.setPort = getOrDefault(other.setPort, original.setPort);
this.providerSupplier = getOrDefault(other.providerSupplier, original.providerSupplier);
this.keyManagerFactory = getOrDefault(other.keyManagerFactory, original.keyManagerFactory);
this.saslMechanismSelector = getOrDefault(other.saslMechanismSelector, original.saslMechanismSelector);
this.principalRewriter = getOrDefault(other.principalRewriter, original.principalRewriter);
this.saslClientFactorySupplier = getOrDefault(other.saslClientFactorySupplier, original.saslClientFactorySupplier);
this.parameterSpecs = getOrDefault(other.parameterSpecs, original.parameterSpecs);
this.trustManagerFactory = getOrDefault(other.trustManagerFactory, original.trustManagerFactory);
this.saslMechanismProperties = getOrDefault(other.saslMechanismProperties, original.saslMechanismProperties);
this.callbackIntercept = other.callbackIntercept == null ? original.callbackIntercept : original.callbackIntercept == null ? other.callbackIntercept : other.callbackIntercept.or(original.callbackIntercept);
this.saslProtocol = getOrDefault(other.saslProtocol, original.saslProtocol);
sanitazeOnMutation(SET_USER_CBH);
}
private static <T> T getOrDefault(T value, T defVal) {
return value != null ? value : defVal;
}
private static int getOrDefault(int value, int defVal) {
return value != -1 ? value : defVal;
}
// test method
Principal getPrincipal() {
return authenticationNameForwardSecurityDomain != null ? authenticationNameForwardSecurityDomain.getCurrentSecurityIdentity().getPrincipal() : principal;
}
@Deprecated
String getHost() {
return setHost;
}
@Deprecated
String getProtocol() {
return setProtocol;
}
String getSaslProtocol() {
return saslProtocol;
}
@Deprecated
int getPort() {
return setPort;
}
// internal actions
/**
* Determine if this SASL mechanism is supported by this configuration (not policy). Implementations must
* combine using boolean-OR operations.
*
* @param mechanismName the mech name (must not be {@code null})
* @return {@code true} if supported, {@code false} otherwise
*/
boolean saslSupportedByConfiguration(String mechanismName) {
// special case for local, quiet auth
// anonymous is only supported if the principal is anonymous. If the principal is anonymous, only anonymous or principal-less mechanisms are supported.
if (! userCallbackKinds.contains(CallbackKind.PRINCIPAL) && principal != AnonymousPrincipal.getInstance()) {
// no callback which can handle a principal.
if (! (mechanismName.equals(LocalUserSaslFactory.JBOSS_LOCAL_USER) || SaslMechanismInformation.doesNotUsePrincipal(mechanismName))) {
// the mechanism requires a principal.
if (getPrincipal() instanceof AnonymousPrincipal != mechanismName.equals(SaslMechanismInformation.Names.ANONYMOUS)) {
// either we have no principal & the mech requires one, or we have a principal but the mech is anonymous.
return false;
}
}
}
// if we have a credential-providing callback handler, we support any mechanism from here on out
if (userCallbackKinds.contains(CallbackKind.CREDENTIAL) || (credentialSource != null && ! credentialSource.equals(IdentityCredentials.NONE))) {
return true;
}
// mechanisms that do not need credentials are probably supported
if (SaslMechanismInformation.doesNotRequireClientCredentials(mechanismName)) {
return true;
}
// if we have a key manager factory, we definitely support IEC/ISO 9798
if (keyManagerFactory != null && SaslMechanismInformation.IEC_ISO_9798.test(mechanismName)) {
return true;
}
// otherwise, use mechanism information and our credential set
Set<Class<? extends Credential>> types = SaslMechanismInformation.getSupportedClientCredentialTypes(mechanismName);
final CredentialSource credentials = credentialSource;
for (Class<? extends Credential> type : types) {
if (AlgorithmCredential.class.isAssignableFrom(type)) {
Set<String> algorithms = SaslMechanismInformation.getSupportedClientCredentialAlgorithms(mechanismName, type);
if (algorithms.contains("*")) {
try {
if (credentials.getCredentialAcquireSupport(type, null).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
} else {
for (String algorithm : algorithms) {
try {
if (credentials.getCredentialAcquireSupport(type, algorithm).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
}
}
} else {
try {
if (credentials.getCredentialAcquireSupport(type).mayBeSupported()) {
return true;
}
} catch (IOException e) {
// no match
}
}
}
// no apparent way to support the mechanism
return false;
}
Principal doRewriteUser(Principal original) {
final Function<Principal, Principal> principalRewriter = this.principalRewriter;
final Principal rewritten = principalRewriter == null ? original : principalRewriter.apply(original);
if (rewritten == null) {
throw log.invalidName();
}
return rewritten;
}
Principal getAuthorizationPrincipal() {
return authorizationNameForwardSecurityDomain != null ? authorizationNameForwardSecurityDomain.getCurrentSecurityIdentity().getPrincipal() : setAuthzPrincipal;
}
Supplier<Provider[]> getProviderSupplier() {
final Supplier<Provider[]> providerSupplier = this.providerSupplier;
return providerSupplier == null ? INSTALLED_PROVIDERS : providerSupplier;
}
SaslClientFactory getSaslClientFactory(Supplier<Provider[]> providers) {
final Supplier<SaslClientFactory> supplier = saslClientFactorySupplier;
return supplier != null ? supplier.get() : new SecurityProviderSaslClientFactory(providers);
}
SecurityFactory<X509TrustManager> getX509TrustManagerFactory() {
return trustManagerFactory == null ? SSLUtils.getDefaultX509TrustManagerSecurityFactory() : trustManagerFactory;
}
SecurityFactory<X509KeyManager> getX509KeyManagerFactory() {
return keyManagerFactory;
}
CredentialSource getCredentialSource() {
if (authenticationCredentialsForwardSecurityDomain != null) {
return doPrivileged((PrivilegedAction<IdentityCredentials>) () -> authenticationCredentialsForwardSecurityDomain.getCurrentSecurityIdentity().getPrivateCredentials(), capturedAccessContext);
} else {
return credentialSource;
}
}
// assembly methods - rewrite
/**
* Create a new configuration which is the same as this configuration, but rewrites the user name using the given
* name rewriter. The name rewriter is appended to the the existing name rewrite function.
*
* @param rewriter the name rewriter
* @return the new configuration
*/
public AuthenticationConfiguration rewriteUser(NameRewriter rewriter) {
if (rewriter == null) {
return this;
}
if (this.principalRewriter == null) {
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, rewriter.asPrincipalRewriter());
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, principalRewriter.andThen(rewriter.asPrincipalRewriter()));
}
/**
* Create a new configuration which is the same as this configuration, but rewrites the user name using <em>only</em>
* the given name rewriter. Any name rewriters on this configuration are ignored for the new configuration.
*
* @param rewriter the name rewriter
* @return the new configuration
*/
public AuthenticationConfiguration rewriteUserOnlyWith(NameRewriter rewriter) {
if (rewriter == null) {
return this;
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL_RW, rewriter.asPrincipalRewriter());
}
// assembly methods - filter
// assembly methods - configuration
/**
* Create a new configuration which is the same as this configuration, but which uses an anonymous login.
*
* @return the new configuration
*/
public AuthenticationConfiguration useAnonymous() {
return usePrincipal(AnonymousPrincipal.getInstance());
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given principal to authenticate.
*
* @param principal the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration usePrincipal(NamePrincipal principal) {
return usePrincipal((Principal) principal);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given principal to authenticate.
*
* @param principal the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration usePrincipal(Principal principal) {
Assert.checkNotNullParam("principal", principal);
if (Objects.equals(this.principal, principal)) {
return this;
}
return new AuthenticationConfiguration(this, SET_PRINCIPAL, principal);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given login name to authenticate.
*
* @param name the principal to use (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration useName(String name) {
Assert.checkNotNullParam("name", name);
return usePrincipal(new NamePrincipal(name));
}
/**
* Create a new configuration which is the same as this configuration, but which attempts to authorize to the given
* name after authentication. Only mechanisms which support an authorization name principal will be selected.
*
* @param name the name to use, or {@code null} to not request authorization in the new configuration
* @return the new configuration
*/
public AuthenticationConfiguration useAuthorizationName(String name) {
return useAuthorizationPrincipal(name == null ? null : new NamePrincipal(name));
}
/**
* Create a new configuration which is the same as this configuration, but which attempts to authorize to the given
* principal after authentication. Only mechanisms which support an authorization principal of the given type will
* be selected.
*
* @param principal the principal to use, or {@code null} to not request authorization in the new configuration
* @return the new configuration
*/
public AuthenticationConfiguration useAuthorizationPrincipal(Principal principal) {
if (Objects.equals(principal, setAuthzPrincipal)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_AUTHZ_PRINCIPAL, principal);
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given credential to authenticate.
*
* @param credential the credential to authenticate
* @return the new configuration
*/
public AuthenticationConfiguration useCredential(Credential credential) {
if (credential == null) return this;
final CredentialSource credentialSource = this.credentialSource;
if (credentialSource == CredentialSource.NONE) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, IdentityCredentials.NONE.withCredential(credential));
} else if (credentialSource instanceof IdentityCredentials) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, ((IdentityCredentials) credentialSource).withCredential(credential));
} else {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, credentialSource.with(IdentityCredentials.NONE.withCredential(credential)));
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(Password password) {
final CredentialSource filtered = getCredentialSource().without(PasswordCredential.class);
return password == null ? useCredentials(filtered) : useCredentials(filtered).useCredential(new PasswordCredential(password));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(char[] password) {
return usePassword(password == null ? null : ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, password));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given password to authenticate.
*
* @param password the password to use
* @return the new configuration
*/
public AuthenticationConfiguration usePassword(String password) {
return usePassword(password == null ? null : ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, password.toCharArray()));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler to
* acquire a password with which to authenticate, when a password-based authentication algorithm is in use.
*
* @param callbackHandler the password callback handler
* @return the new configuration
*/
public AuthenticationConfiguration useCredentialCallbackHandler(CallbackHandler callbackHandler) {
return useCallbackHandler(callbackHandler, EnumSet.of(CallbackKind.CREDENTIAL));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler
* to authenticate.
* <p>
* <em>Important notes:</em> It is important to ensure that each distinct client identity uses a distinct {@code CallbackHandler}
* instance in order to avoid mis-pooling of connections, identity crossovers, and other potentially serious problems.
* It is not recommended that a {@code CallbackHandler} implement {@code equals()} and {@code hashCode()}, however if it does,
* it is important to ensure that these methods consider equality based on an authenticating identity that does not
* change between instances. In particular, a callback handler which requests user input on each usage is likely to cause
* a problem if the user name can change on each authentication request.
* <p>
* Because {@code CallbackHandler} instances are unique per identity, it is often useful for instances to cache
* identity information, credentials, and/or other authentication-related information in order to facilitate fast
* re-authentication.
*
* @param callbackHandler the callback handler to use
* @return the new configuration
*/
public AuthenticationConfiguration useCallbackHandler(CallbackHandler callbackHandler) {
return callbackHandler == null ? this : new AuthenticationConfiguration(this, SET_USER_CBH, callbackHandler, SET_USER_CB_KINDS, EnumSet.allOf(CallbackKind.class));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given callback handler
* to authenticate.
* <p>
* <em>Important notes:</em> It is important to ensure that each distinct client identity uses a distinct {@code CallbackHandler}
* instance in order to avoid mis-pooling of connections, identity crossovers, and other potentially serious problems.
* It is not recommended that a {@code CallbackHandler} implement {@code equals()} and {@code hashCode()}, however if it does,
* it is important to ensure that these methods consider equality based on an authenticating identity that does not
* change between instances. In particular, a callback handler which requests user input on each usage is likely to cause
* a problem if the user name can change on each authentication request.
* <p>
* Because {@code CallbackHandler} instances are unique per identity, it is often useful for instances to cache
* identity information, credentials, and/or other authentication-related information in order to facilitate fast
* re-authentication.
*
* @param callbackHandler the callback handler to use
* @param callbackKinds the kinds of callbacks that the handler should use
* @return the new configuration
*/
public AuthenticationConfiguration useCallbackHandler(CallbackHandler callbackHandler, Set<CallbackKind> callbackKinds) {
return callbackHandler == null ? this : new AuthenticationConfiguration(this, SET_USER_CBH, callbackHandler, SET_USER_CB_KINDS, EnumSet.copyOf(callbackKinds));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given GSS-API credential to authenticate.
*
* @param credential the GSS-API credential to use
* @return the new configuration
*/
public AuthenticationConfiguration useGSSCredential(GSSCredential credential) {
return credential == null ? this : useCredential(new GSSKerberosCredential(credential));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStoreEntry the key store entry to use
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore.Entry keyStoreEntry) {
return keyStoreEntry == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(new FixedSecurityFactory<>(keyStoreEntry))));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStore the key store to use
* @param alias the key store alias
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore keyStore, String alias) {
return keyStore == null || alias == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(keyStore, alias, null)));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key store and alias
* to acquire the credential required for authentication.
*
* @param keyStore the key store to use
* @param alias the key store alias
* @param protectionParameter the protection parameter to use to access the key store entry
* @return the new configuration
*/
public AuthenticationConfiguration useKeyStoreCredential(KeyStore keyStore, String alias, KeyStore.ProtectionParameter protectionParameter) {
return keyStore == null || alias == null ? this : useCredentials(getCredentialSource().with(new KeyStoreCredentialSource(keyStore, alias, protectionParameter)));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given private key and X.509
* certificate chain to authenticate.
*
* @param privateKey the client private key
* @param certificateChain the client certificate chain
* @return the new configuration
*/
public AuthenticationConfiguration useCertificateCredential(PrivateKey privateKey, X509Certificate... certificateChain) {
return certificateChain == null || certificateChain.length == 0 || privateKey == null ? this : useCertificateCredential(new X509CertificateChainPrivateCredential(privateKey, certificateChain));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given private key and X.509
* certificate chain to authenticate.
*
* @param credential the credential containing the private key and certificate chain
* @return the new configuration
*/
public AuthenticationConfiguration useCertificateCredential(X509CertificateChainPrivateCredential credential) {
return credential == null ? this : useCredential(credential);
}
/**
* Create a new configuration which is the same as this configuration, but uses credentials found at the given
* alias and credential store.
*
* @param credentialStore the credential store (must not be {@code null})
* @param alias the alias within the store (must not be {@code null})
* @return the new configuration
*/
public AuthenticationConfiguration useCredentialStoreEntry(CredentialStore credentialStore, String alias) {
Assert.checkNotNullParam("credentialStore", credentialStore);
Assert.checkNotNullParam("alias", alias);
CredentialStoreCredentialSource csCredentialSource = new CredentialStoreCredentialSource(credentialStore, alias);
return useCredentials(getCredentialSource().with(csCredentialSource));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given key manager
* to acquire the credential required for authentication.
*
* @param keyManager the key manager to use
* @return the new configuration
*/
public AuthenticationConfiguration useKeyManagerCredential(X509KeyManager keyManager) {
return new AuthenticationConfiguration(this, SET_KEY_MGR_FAC, new FixedSecurityFactory<>(keyManager));
}
/**
* Create a new configuration which is the same as this configuration, but which uses local kerberos ticket cache
* to acquire the credential required for authentication.
*
* @param mechanismOids array of oid's indicating the mechanisms over which the credential is to be acquired
* @return the new configuration
*
* @since 1.2.0
* @deprecated can be ommited - kerberos based authentication mechanism obtains credential himself
*/
@Deprecated
public AuthenticationConfiguration useLocalKerberosCredential(Oid[] mechanismOids) {
return useCredentials(getCredentialSource().with(LocalKerberosCredentialSource.builder().setMechanismOids(mechanismOids).build()));
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given identity
* credentials to acquire the credential required for authentication.
*
* @param credentials the credentials to use
* @return the new configuration
*/
public AuthenticationConfiguration useCredentials(CredentialSource credentials) {
return new AuthenticationConfiguration(this, SET_CRED_SOURCE, credentials == null ? CredentialSource.NONE : credentials);
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given choice if the given
* predicate evaluates to {@code true}.
*
* @param matchPredicate the predicate that should be used to determine if a choice callback type and prompt are
* relevant for the given choice
* @param choice the choice to use if the given predicate evaluates to {@code true}
* @return the new configuration
*/
public AuthenticationConfiguration useChoice(BiPredicate<Class<? extends ChoiceCallback>, String> matchPredicate, String choice) {
Assert.checkNotNullParam("matchPredicate", matchPredicate);
Assert.checkNotNullParam("choice", choice);
final Predicate<Callback> callbackIntercept = this.callbackIntercept;
Predicate<Callback> newIntercept = cb -> {
if (! (cb instanceof ChoiceCallback)) {
return false;
}
final ChoiceCallback choiceCallback = (ChoiceCallback) cb;
if (matchPredicate.test(choiceCallback.getClass(), choiceCallback.getPrompt())) {
final String[] choices = choiceCallback.getChoices();
final int choicesLength = choices.length;
for (int i = 0; i < choicesLength; i++) {
if (choices[i].equals(choice)) {
choiceCallback.setSelectedIndex(i);
return true;
}
}
}
return false;
};
if (callbackIntercept == null) {
return new AuthenticationConfiguration(this, SET_CALLBACK_INTERCEPT, newIntercept);
} else {
return new AuthenticationConfiguration(this, SET_CALLBACK_INTERCEPT, newIntercept.or(callbackIntercept));
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given parameter specification.
*
* @param parameterSpec the algorithm parameter specification to use
* @return the new configuration
*/
public AuthenticationConfiguration useParameterSpec(AlgorithmParameterSpec parameterSpec) {
if (parameterSpec == null) {
return this;
}
final List<AlgorithmParameterSpec> specs = parameterSpecs;
if (specs.isEmpty()) {
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, Collections.singletonList(parameterSpec));
} else {
ArrayList<AlgorithmParameterSpec> newList = new ArrayList<>();
for (AlgorithmParameterSpec spec : specs) {
if (spec.getClass() == parameterSpec.getClass()) continue;
newList.add(spec);
}
if (newList.isEmpty()) {
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, Collections.singletonList(parameterSpec));
} else {
newList.add(parameterSpec);
return new AuthenticationConfiguration(this, SET_PARAM_SPECS, newList);
}
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given trust manager
* for trust verification.
*
* @param trustManager the trust manager to use or {@code null} if the default trust manager should be used
* @return the new configuration
*/
public AuthenticationConfiguration useTrustManager(X509TrustManager trustManager) {
return trustManager == null ? new AuthenticationConfiguration(this, SET_TRUST_MGR_FAC, null) : new AuthenticationConfiguration(this, SET_TRUST_MGR_FAC, new FixedSecurityFactory<>(trustManager));
}
/**
* Create a new configuration which is the same as this configuration, but which connects to a different host name.
*
* @param hostName the host name to connect to
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration useHost(String hostName) {
if (hostName == null || hostName.isEmpty()) {
hostName = null;
}
if (Objects.equals(this.setHost, hostName)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_HOST, hostName);
}
}
/**
* Create a new configuration which is the same as this configuration, but which specifies a different protocol to be used for outgoing connection.
*
* @param protocol the protocol to be used for outgoing connection.
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration useProtocol(String protocol) {
if (protocol == null || protocol.isEmpty()) {
protocol = null;
}
if (Objects.equals(this.setProtocol, protocol)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_PROTOCOL, protocol);
}
}
/**
* Create a new configuration which is the same as this configuration, but which specifies a different protocol to be passed to the authentication mechanisms.
*
* @param saslProtocol the protocol to pass to the authentication mechanisms.
* @return the new configuration
*/
public AuthenticationConfiguration useSaslProtocol(String saslProtocol) {
if (saslProtocol == null || saslProtocol.isEmpty()) {
saslProtocol = null;
}
if (Objects.equals(this.saslProtocol, saslProtocol)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_SASL_PROTOCOL, saslProtocol);
}
}
/**
* Create a new configuration which is the same as this configuration, but which connects to a different port.
*
* @param port the port to connect to, or -1 to not override the port
* @return the new configuration
* @deprecated This configuration is not supported by most providers and will be removed in a future release.
*/
@Deprecated
public AuthenticationConfiguration usePort(int port) {
if (port < -1 || port > 65535) throw log.invalidPortNumber(port);
if (port == setPort) return this;
return new AuthenticationConfiguration(this, port);
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication name
* and credentials from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedIdentity(SecurityDomain securityDomain) {
return useForwardedAuthenticationIdentity(securityDomain).useForwardedAuthenticationCredentials(securityDomain);
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication name
* from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthenticationIdentity(SecurityDomain securityDomain) {
if (Objects.equals(authenticationNameForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTH_NAME_DOMAIN, securityDomain);
}
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authentication
* credentials from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthenticationCredentials(SecurityDomain securityDomain) {
if (Objects.equals(authenticationCredentialsForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTH_CRED_DOMAIN, securityDomain);
}
}
/**
* Create a new configuration which is the same as this configuration, but which forwards the authorization name
* from the current identity of the given security domain.
*
* @param securityDomain the security domain
* @return the new configuration
*/
public AuthenticationConfiguration useForwardedAuthorizationIdentity(SecurityDomain securityDomain) {
if (Objects.equals(authorizationNameForwardSecurityDomain, securityDomain)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, securityDomain != null ? getContext() : null, SET_FWD_AUTHZ_NAME_DOMAIN, securityDomain);
}
}
// Providers
/**
* Use the given security provider supplier to locate security implementations.
*
* @param providerSupplier the provider supplier
* @return the new configuration
*/
public AuthenticationConfiguration useProviders(Supplier<Provider[]> providerSupplier) {
if (Objects.equals(this.providerSupplier, providerSupplier)) {
return this;
}
return new AuthenticationConfiguration(this, SET_PROVIDER_SUPPLIER, providerSupplier);
}
/**
* Use the default provider discovery behaviour of combining service loader discovered providers with the system default
* security providers when locating security implementations.
*
* @return the new configuration
*/
public AuthenticationConfiguration useDefaultProviders() {
return useProviders(DEFAULT_PROVIDER_SUPPLIER);
}
/**
* Use security providers from the given class loader.
*
* @param classLoader the class loader to search for security providers
* @return the new configuration
*/
public AuthenticationConfiguration useProvidersFromClassLoader(ClassLoader classLoader) {
return useProviders(new ProviderServiceLoaderSupplier(classLoader));
}
// SASL Mechanisms
/**
* Use a pre-existing {@link SaslClientFactory} instead of discovery.
*
* @param saslClientFactory the pre-existing {@link SaslClientFactory} to use.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactory(final SaslClientFactory saslClientFactory) {
return useSaslClientFactory(() -> saslClientFactory);
}
/**
* Use the given sasl client factory supplier to obtain the {@link SaslClientFactory} to use.
*
* @param saslClientFactory the sasl client factory supplier to use.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactory(final Supplier<SaslClientFactory> saslClientFactory) {
return new AuthenticationConfiguration(this, SET_SASL_FAC_SUP, saslClientFactory);
}
/**
* Use provider based discovery to load available {@link SaslClientFactory} implementations.
*
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslClientFactoryFromProviders() {
return new AuthenticationConfiguration(this, SET_SASL_FAC_SUP, null);
}
// SASL Configuration
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* Existing properties defined on this authentication context will be retained unless overridden by new properties, any
* properties resulting with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @return the new configuration.
* @deprecated use {@link #useSaslMechanismProperties(Map)}
*/
@Deprecated
public AuthenticationConfiguration useMechanismProperties(Map<String, ?> mechanismProperties) {
return useSaslMechanismProperties(mechanismProperties);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* Existing properties defined on this authentication context will be retained unless overridden by new properties, any
* properties resulting with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslMechanismProperties(Map<String, ?> mechanismProperties) {
return useSaslMechanismProperties(mechanismProperties, false);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* If exclusive the existing properties will be discarded and replaced with the new properties otherwise existing properties
* defined on this authentication context will be retained unless overridden by new properties, any properties resulting
* with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @param exclusive should the provided properties be used exclusively or merged with the existing properties?
* @return the new configuration.
* @deprecated use {@link #useSaslMechanismProperties(Map, boolean)}
*/
@Deprecated
public AuthenticationConfiguration useMechanismProperties(Map<String, ?> mechanismProperties, boolean exclusive) {
return useSaslMechanismProperties(mechanismProperties, exclusive);
}
/**
* Create a new configuration which is the same as this configuration, but which sets the properties that will be passed to
* the {@code SaslClientFactory} when the mechanism is created.
*
* If exclusive the existing properties will be discarded and replaced with the new properties otherwise existing properties
* defined on this authentication context will be retained unless overridden by new properties, any properties resulting
* with a value of {@code null} will be removed.
*
* @param mechanismProperties the properties to be passed to the {@code SaslClientFactory} to create the mechanism.
* @param exclusive should the provided properties be used exclusively or merged with the existing properties?
* @return the new configuration.
*/
public AuthenticationConfiguration useSaslMechanismProperties(Map<String, ?> mechanismProperties, boolean exclusive) {
if (!exclusive && (mechanismProperties == null || mechanismProperties.isEmpty())) return this;
final HashMap<String, Object> newMap = exclusive ? new HashMap<>() : new HashMap<>(this.saslMechanismProperties);
newMap.putAll(mechanismProperties);
newMap.values().removeIf(Objects::isNull);
return new AuthenticationConfiguration(this, SET_SASL_MECH_PROPS, optimizeMap(newMap));
}
private static <K, V> Map<K, V> optimizeMap(Map<K, V> orig) {
if (orig.isEmpty()) return Collections.emptyMap();
if (orig.size() == 1) {
final Map.Entry<K, V> entry = orig.entrySet().iterator().next();
return Collections.singletonMap(entry.getKey(), entry.getValue());
}
return orig;
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given kerberos security
* factory to acquire the GSS credential required for authentication.
*
* @param kerberosSecurityFactory a reference to the kerberos security factory to be use
* @return the new configuration
*/
@Deprecated
public AuthenticationConfiguration useKerberosSecurityFactory(SecurityFactory<Credential> kerberosSecurityFactory) {
CredentialSource cs = getCredentialSource();
if (kerberosSecurityFactory != null) {
return cs != null ? new AuthenticationConfiguration(this, SET_CRED_SOURCE, cs.with(new FactoryCredentialSource(kerberosSecurityFactory))) : new AuthenticationConfiguration(this, SET_CRED_SOURCE, new FactoryCredentialSource(kerberosSecurityFactory));
}
return this; // cs != null ? new AuthenticationConfiguration(this, SET_CRED_SOURCE, cs.without(GSSKerberosCredential.class)) : this;
}
/**
* Set the SASL mechanism selector for this authentication configuration.
*
* @param saslMechanismSelector the SASL mechanism selector, or {@code null} to clear the current selector
* @return the new configuration
*/
public AuthenticationConfiguration setSaslMechanismSelector(SaslMechanismSelector saslMechanismSelector) {
if (Objects.equals(this.saslMechanismSelector, saslMechanismSelector)) {
return this;
}
return new AuthenticationConfiguration(this, SET_SASL_SELECTOR, saslMechanismSelector);
}
// other
/**
* Create a new configuration which is the same as this configuration, but uses the given realm for authentication.
*
* @param realm the realm to use, or {@code null} to accept the default realm always
* @return the new configuration
*/
public AuthenticationConfiguration useRealm(String realm) {
if (Objects.equals(realm, this.setRealm)) {
return this;
} else {
return new AuthenticationConfiguration(this, SET_REALM, realm);
}
}
/**
* Create a new configuration which is the same as this configuration, but which uses the given {@link BearerTokenCredential} to authenticate.
*
* @param credential the bearer token credential to use
* @return the new configuration
*/
public AuthenticationConfiguration useBearerTokenCredential(BearerTokenCredential credential) {
return credential == null ? this : useCredentials(getCredentialSource().with(IdentityCredentials.NONE.withCredential(credential)));
}
/**
* Create a new configuration which is the same as this configuration, but which captures the caller's access
* control context to be used in authentication decisions.
*
* @return the new configuration
*/
public AuthenticationConfiguration withCapturedAccessControlContext() {
return new AuthenticationConfiguration(this, SET_ACCESS_CTXT, getContext());
}
// merging
/**
* Create a new configuration which is the same as this configuration, but which adds or replaces every item in the
* {@code other} configuration with that item, overwriting any corresponding such item in this configuration.
*
* @param other the other authentication configuration
* @return the merged authentication configuration
*/
public AuthenticationConfiguration with(AuthenticationConfiguration other) {
return new AuthenticationConfiguration(this, other);
}
// client methods
CallbackHandler getUserCallbackHandler() {
return userCallbackHandler;
}
EnumSet<CallbackKind> getUserCallbackKinds() {
return userCallbackKinds;
}
private SaslClientFactory getSaslClientFactory() {
if (saslClientFactory == null) {
synchronized (this) {
if (saslClientFactory == null) {
saslClientFactory = getSaslClientFactory(getProviderSupplier());
}
}
}
return saslClientFactory;
}
SaslClient createSaslClient(URI uri, Collection<String> serverMechanisms, UnaryOperator<SaslClientFactory> factoryOperator, SSLSession sslSession) throws SaslException {
SaslClientFactory saslClientFactory = factoryOperator.apply(getSaslClientFactory());
final SaslMechanismSelector selector = this.saslMechanismSelector;
serverMechanisms = (selector == null ? SaslMechanismSelector.DEFAULT : selector).apply(serverMechanisms, sslSession);
if (serverMechanisms.isEmpty()) {
return null;
}
final Principal authorizationPrincipal = getAuthorizationPrincipal();
final Predicate<String> filter;
final String authzName;
if (authorizationPrincipal == null) {
filter = this::saslSupportedByConfiguration;
authzName = null;
} else if (authorizationPrincipal instanceof NamePrincipal) {
filter = this::saslSupportedByConfiguration;
authzName = authorizationPrincipal.getName();
} else if (authorizationPrincipal instanceof AnonymousPrincipal) {
filter = ((Predicate<String>) this::saslSupportedByConfiguration).and("ANONYMOUS"::equals);
authzName = null;
} else {
return null;
}
Map<String, ?> mechanismProperties = this.saslMechanismProperties;
if (! mechanismProperties.isEmpty()) {
mechanismProperties = new HashMap<>(mechanismProperties);
// special handling for JBOSS-LOCAL-USER quiet auth... only pass it through if we have a user callback
if (! userCallbackKinds.contains(CallbackKind.PRINCIPAL) && principal != AnonymousPrincipal.getInstance()) {
mechanismProperties.remove(LocalUserClient.QUIET_AUTH);
mechanismProperties.remove(LocalUserClient.LEGACY_QUIET_AUTH);
}
if (! mechanismProperties.isEmpty()) {
saslClientFactory = new PropertiesSaslClientFactory(saslClientFactory, mechanismProperties);
}
}
String host = uri.getHost();
if (host != null) {
saslClientFactory = new ServerNameSaslClientFactory(saslClientFactory, host);
}
String protocol = getSaslProtocol();
if (protocol != null) {
saslClientFactory = new ProtocolSaslClientFactory(saslClientFactory, protocol);
}
if (sslSession != null) {
saslClientFactory = new SSLSaslClientFactory(() -> SSLConnection.forSession(sslSession, true), saslClientFactory);
}
saslClientFactory = new LocalPrincipalSaslClientFactory(new FilterMechanismSaslClientFactory(saslClientFactory, filter));
final SaslClientFactory finalSaslClientFactory = saslClientFactory;
saslClientFactory = doPrivileged((PrivilegedAction<PrivilegedSaslClientFactory>) () -> new PrivilegedSaslClientFactory(finalSaslClientFactory), capturedAccessContext);
SaslClient saslClient = saslClientFactory.createSaslClient(serverMechanisms.toArray(NO_STRINGS),
authzName, uri.getScheme(), uri.getHost(), Collections.emptyMap(), createCallbackHandler());
if (log.isTraceEnabled()) {
log.tracef("Created SaslClient [%s] for mechanisms %s", saslClient, Arrays2.objectToString(serverMechanisms));
}
return saslClient;
}
CallbackHandler createCallbackHandler() {
return new ClientCallbackHandler(this);
}
// equality
/**
* Determine whether this configuration is equal to another object. Two configurations are equal if they
* apply the same items.
*
* @param obj the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(final Object obj) {
return obj instanceof AuthenticationConfiguration && equals((AuthenticationConfiguration) obj);
}
/**
* Determine whether this configuration is equal to another object. Two configurations are equal if they
* apply the same items.
*
* @param other the other object
* @return {@code true} if they are equal, {@code false} otherwise
*/
public boolean equals(final AuthenticationConfiguration other) {
return hashCode() == other.hashCode()
&& Objects.equals(principal, other.principal)
&& Objects.equals(setHost, other.setHost)
&& Objects.equals(setProtocol, other.setProtocol)
&& Objects.equals(setRealm, other.setRealm)
&& Objects.equals(setAuthzPrincipal, other.setAuthzPrincipal)
&& Objects.equals(authenticationNameForwardSecurityDomain, other.authenticationNameForwardSecurityDomain)
&& Objects.equals(authenticationCredentialsForwardSecurityDomain, other.authenticationCredentialsForwardSecurityDomain)
&& Objects.equals(authorizationNameForwardSecurityDomain, other.authorizationNameForwardSecurityDomain)
&& Objects.equals(userCallbackHandler, other.userCallbackHandler)
&& Objects.equals(userCallbackKinds, other.userCallbackKinds)
&& Objects.equals(credentialSource, other.credentialSource)
&& this.setPort == other.setPort
&& Objects.equals(providerSupplier, other.providerSupplier)
&& Objects.equals(keyManagerFactory, other.keyManagerFactory)
&& Objects.equals(saslMechanismSelector, other.saslMechanismSelector)
&& Objects.equals(principalRewriter, other.principalRewriter)
&& Objects.equals(saslClientFactorySupplier, other.saslClientFactorySupplier)
&& Objects.equals(parameterSpecs, other.parameterSpecs)
&& Objects.equals(trustManagerFactory, other.trustManagerFactory)
&& Objects.equals(saslMechanismProperties, other.saslMechanismProperties)
&& Objects.equals(saslProtocol, other.saslProtocol);
}
/**
* Get the hash code of this authentication configuration.
*
* @return the hash code of this authentication configuration
*/
public int hashCode() {
int hashCode = this.hashCode;
if (hashCode == 0) {
hashCode = Objects.hash(
principal, setHost, setProtocol, setRealm, setAuthzPrincipal, authenticationNameForwardSecurityDomain,
authenticationCredentialsForwardSecurityDomain, authorizationNameForwardSecurityDomain, userCallbackHandler, credentialSource,
providerSupplier, keyManagerFactory, saslMechanismSelector, principalRewriter, saslClientFactorySupplier, parameterSpecs, trustManagerFactory,
saslMechanismProperties, saslProtocol) * 19 + setPort;
if (hashCode == 0) {
hashCode = 1;
}
this.hashCode = hashCode;
}
return hashCode;
}
// String Representation
@Override
public String toString() {
String toString = this.toString;
if (toString == null) {
StringBuilder b = new StringBuilder(64);
b.append("AuthenticationConfiguration:");
b.append("principal=").append(principal).append(',');
if (setAuthzPrincipal != null) b.append("authorization-id=").append(setAuthzPrincipal).append(',');
if (setHost != null) b.append("set-host=").append(setHost).append(',');
if (setProtocol != null) b.append("set-protocol=").append(setProtocol).append(',');
if (saslProtocol != null) b.append("sasl-protocol-name=").append(saslProtocol).append(',');
if (setPort != -1) b.append("set-port=").append(setPort).append(',');
if (setRealm != null) b.append("set-realm=").append(setRealm).append(',');
if (authenticationNameForwardSecurityDomain != null) b.append("forwarding-authentication-name,");
if (authenticationCredentialsForwardSecurityDomain != null) b.append("forwarding-authentication-credentials,");
if (authorizationNameForwardSecurityDomain != null) b.append("forwarding-authorization-name,");
if (userCallbackHandler != null) b.append("user-callback-handler=").append(userCallbackHandler).append(',');
if (! userCallbackKinds.isEmpty()) b.append("user-callback-kinds=").append(userCallbackKinds).append(',');
if (credentialSource != null && credentialSource != CredentialSource.NONE && credentialSource != IdentityCredentials.NONE) b.append("credentials-present,");
if (providerSupplier != null) b.append("providers-supplier=").append(providerSupplier).append(',');
if (keyManagerFactory != null) b.append("key-manager-factory=").append(keyManagerFactory).append(',');
if (saslMechanismSelector != null) b.append("sasl-mechanism-selector=").append(saslMechanismSelector).append(',');
if (principalRewriter != null) b.append("principal-rewriter=").append(principalRewriter).append(',');
if (saslClientFactorySupplier != null) b.append("sasl-client-factory-supplier=").append(saslClientFactorySupplier).append(',');
if (! parameterSpecs.isEmpty()) b.append("parameter-specifications=").append(parameterSpecs).append(',');
if (trustManagerFactory != null) b.append("trust-manager-factory=").append(trustManagerFactory).append(',');
if (! saslMechanismProperties.isEmpty()) b.append("mechanism-properties=").append(saslMechanismProperties).append(',');
b.setLength(b.length() - 1);
return this.toString = b.toString();
}
return toString;
}
//user callback sanitation
private void sanitazeOnMutation(final int what) {
switch (what) {
case SET_PRINCIPAL:
// CallbackKind.PRINCIPAL
if (this.principal != null && ! this.principal.equals(AnonymousPrincipal.getInstance())) {
this.userCallbackKinds.remove(CallbackKind.PRINCIPAL);
}
break;
case SET_CRED_SOURCE:
// CallbackKind.CREDENTIAL
if (this.credentialSource != null && ! this.credentialSource.equals(IdentityCredentials.NONE)) {
this.userCallbackKinds.remove(CallbackKind.CREDENTIAL);
}
break;
case SET_REALM:
// CallbackKind.REALM
this.userCallbackKinds.remove(CallbackKind.REALM);
break;
case SET_PARAM_SPECS:
// CallbackKind.PARAMETERS
this.userCallbackKinds.remove(CallbackKind.PARAMETERS);
break;
case SET_KEY_MGR_FAC:
// CallbackKind.PEER_CREDENTIAL
this.userCallbackKinds.remove(CallbackKind.PEER_CREDENTIAL);
break;
case SET_USER_CB_KINDS:
// SANITAZE on above content
if (this.principal != null) {
sanitazeOnMutation(SET_PRINCIPAL);
}
if (this.credentialSource != null) {
sanitazeOnMutation(SET_CRED_SOURCE);
}
if (this.setRealm != null) {
sanitazeOnMutation(SET_REALM);
}
if (this.parameterSpecs != null) {
sanitazeOnMutation(SET_PARAM_SPECS);
}
if (this.keyManagerFactory != null) {
sanitazeOnMutation(SET_KEY_MGR_FAC);
}
break;
}
}
AccessControlContext getCapturedContext() {
return capturedAccessContext;
}
// delegates for equality tests
// interfaces
static class ClientCallbackHandler implements CallbackHandler {
private final AuthenticationConfiguration config;
private final CallbackHandler userCallbackHandler;
private List<TrustedAuthority> trustedAuthorities;
private SSLConnection sslConnection;
ClientCallbackHandler(final AuthenticationConfiguration config) {
this.config = config;
userCallbackHandler = config.getUserCallbackHandler();
}
@SuppressWarnings("UnnecessaryContinue")
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
final AuthenticationConfiguration config = this.config;
final Predicate<Callback> callbackIntercept = config.callbackIntercept;
final ArrayList<Callback> userCallbacks = new ArrayList<>(callbacks.length);
for (final Callback callback : callbacks) {
if (callbackIntercept != null && callbackIntercept.test(callback)) {
continue;
} else if (callback instanceof NameCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PRINCIPAL)) {
userCallbacks.add(callback);
continue;
}
final NameCallback nameCallback = (NameCallback) callback;
// populate with our authentication name
final Principal principal = config.getPrincipal();
if (principal instanceof AnonymousPrincipal) {
final String defaultName = nameCallback.getDefaultName();
if (defaultName != null) {
nameCallback.setName(defaultName);
}
// otherwise set nothing; the mech can decide if that's OK or not
continue;
} else {
nameCallback.setName(config.doRewriteUser(principal).getName());
continue;
}
} else if (callback instanceof PasswordCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final PasswordCallback passwordCallback = (PasswordCallback) callback;
final CredentialSource credentials = config.getCredentialSource();
if (credentials != null) {
final TwoWayPassword password = credentials.applyToCredential(PasswordCredential.class, ClearPassword.ALGORITHM_CLEAR, c -> c.getPassword(TwoWayPassword.class));
if (password instanceof ClearPassword) {
// shortcut
passwordCallback.setPassword(((ClearPassword) password).getPassword());
continue;
} else if (password != null) try {
PasswordFactory passwordFactory = PasswordFactory.getInstance(password.getAlgorithm());
ClearPasswordSpec clearPasswordSpec = passwordFactory.getKeySpec(passwordFactory.translate(password), ClearPasswordSpec.class);
passwordCallback.setPassword(clearPasswordSpec.getEncodedPassword());
continue;
} catch (GeneralSecurityException e) {
// not supported
CallbackUtil.unsupported(passwordCallback);
continue;
}
else {
// supported but no credentials
continue;
}
} else {
// supported but no credentials
continue;
}
} else if (callback instanceof PasswordResetCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL_RESET)) {
userCallbacks.add(callback);
continue;
}
// not supported
CallbackUtil.unsupported(callback);
continue;
} else if (callback instanceof CredentialCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final CredentialCallback credentialCallback = (CredentialCallback) callback;
// special handling for X.509 when a key manager factory is set
final SecurityFactory<X509KeyManager> keyManagerFactory = config.getX509KeyManagerFactory();
if (keyManagerFactory != null) {
final String allowedAlgorithm = credentialCallback.getAlgorithm();
if (allowedAlgorithm != null && credentialCallback.isCredentialTypeSupported(X509CertificateChainPrivateCredential.class, allowedAlgorithm)) {
final X509KeyManager keyManager;
try {
keyManager = keyManagerFactory.create();
} catch (GeneralSecurityException e) {
throw log.unableToCreateKeyManager(e);
}
Principal[] acceptableIssuers;
if (trustedAuthorities != null) {
List<Principal> issuers = new ArrayList<Principal>();
for (TrustedAuthority trustedAuthority : trustedAuthorities) {
if (trustedAuthority instanceof TrustedAuthority.CertificateTrustedAuthority) {
final X509Certificate authorityCertificate = ((TrustedAuthority.CertificateTrustedAuthority) trustedAuthority).getIdentifier();
issuers.add(authorityCertificate.getSubjectX500Principal());
} else if (trustedAuthority instanceof TrustedAuthority.NameTrustedAuthority) {
final String authorityName = ((TrustedAuthority.NameTrustedAuthority) trustedAuthority).getIdentifier();
issuers.add(new X500Principal(authorityName));
}
}
acceptableIssuers = issuers.toArray(NO_PRINCIPALS);
} else {
acceptableIssuers = null;
}
final String alias = keyManager.chooseClientAlias(new String[] { allowedAlgorithm }, acceptableIssuers, null);
if (alias != null) {
final X509Certificate[] certificateChain = keyManager.getCertificateChain(alias);
final PrivateKey privateKey = keyManager.getPrivateKey(alias);
credentialCallback.setCredential(new X509CertificateChainPrivateCredential(privateKey, certificateChain));
continue;
}
// otherwise fall out to normal handling
}
}
// normal handling
final Credential credential = config.getCredentialSource().getCredential(credentialCallback.getCredentialType(), credentialCallback.getAlgorithm(), credentialCallback.getParameterSpec());
if (credential != null && credentialCallback.isCredentialSupported(credential)) {
credentialCallback.setCredential(credential);
continue;
} else {
// supported but no credentials
continue;
}
} else if (callback instanceof RealmChoiceCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.REALM)) {
userCallbacks.add(callback);
continue;
}
final RealmChoiceCallback realmChoiceCallback = (RealmChoiceCallback) callback;
// find our realm
final String realm = config.setRealm;
if (realm == null) {
realmChoiceCallback.setSelectedIndex(realmChoiceCallback.getDefaultChoice());
continue;
} else {
String[] choices = realmChoiceCallback.getChoices();
for (int i = 0; i < choices.length; i++) {
if (realm.equals(choices[i])) {
realmChoiceCallback.setSelectedIndex(i);
break;
}
}
// no choice matches, so just fall out and choose nothing
continue;
}
} else if (callback instanceof RealmCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.REALM)) {
userCallbacks.add(callback);
continue;
}
RealmCallback realmCallback = (RealmCallback) callback;
final String realm = config.setRealm;
realmCallback.setText(realm != null ? realm : realmCallback.getDefaultText());
continue;
} else if (callback instanceof ParameterCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PARAMETERS)) {
userCallbacks.add(callback);
continue;
}
ParameterCallback parameterCallback = (ParameterCallback) callback;
if (parameterCallback.getParameterSpec() == null) {
for (AlgorithmParameterSpec parameterSpec : config.parameterSpecs) {
if (parameterCallback.isParameterSupported(parameterSpec)) {
parameterCallback.setParameterSpec(parameterSpec);
break; // inner loop break
}
}
}
continue;
} else if (callback instanceof SSLCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.SSL)) {
userCallbacks.add(callback);
continue;
}
SSLCallback sslCallback = (SSLCallback) callback;
this.sslConnection = sslCallback.getSslConnection();
continue;
} else if (callback instanceof ChannelBindingCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.CHANNEL_BINDING)) {
userCallbacks.add(callback);
continue;
}
final SSLConnection sslConnection = this.sslConnection;
if (sslConnection != null) {
sslConnection.handleChannelBindingCallback((ChannelBindingCallback) callback);
}
continue;
} else if (callback instanceof ChoiceCallback) { // Must come AFTER RealmChoiceCallback
if (config.getUserCallbackKinds().contains(CallbackKind.CHOICE)) {
userCallbacks.add(callback);
continue;
}
final ChoiceCallback choiceCallback = (ChoiceCallback) callback;
choiceCallback.setSelectedIndex(choiceCallback.getDefaultChoice());
continue;
} else if (callback instanceof TrustedAuthoritiesCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.SERVER_TRUSTED_AUTHORITIES)) {
userCallbacks.add(callback);
continue;
}
final TrustedAuthoritiesCallback trustedAuthoritiesCallback = (TrustedAuthoritiesCallback) callback;
if (trustedAuthorities == null) {
trustedAuthorities = new ArrayList<>(trustedAuthoritiesCallback.getTrustedAuthorities());
} else {
final List<TrustedAuthority> authorities = new ArrayList<>(trustedAuthoritiesCallback.getTrustedAuthorities());
authorities.removeIf(trustedAuthorities::contains);
trustedAuthorities.addAll(authorities);
}
continue;
} else if (callback instanceof EvidenceVerifyCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.PEER_CREDENTIAL)) {
userCallbacks.add(callback);
continue;
}
final EvidenceVerifyCallback evidenceVerifyCallback = (EvidenceVerifyCallback) callback;
// special handling for X.509
final SecurityFactory<X509TrustManager> trustManagerFactory = config.getX509TrustManagerFactory();
if (trustManagerFactory != null) {
final X509PeerCertificateChainEvidence peerCertificateChainEvidence = evidenceVerifyCallback.getEvidence(X509PeerCertificateChainEvidence.class);
if (peerCertificateChainEvidence != null) {
X509TrustManager trustManager;
try {
trustManager = trustManagerFactory.create();
} catch (GeneralSecurityException e) {
throw log.unableToCreateTrustManager(e);
}
try {
trustManager.checkServerTrusted(peerCertificateChainEvidence.getPeerCertificateChain(), peerCertificateChainEvidence.getAlgorithm());
evidenceVerifyCallback.setVerified(true);
} catch (CertificateException e) {
}
continue;
}
}
continue;
} else if (callback instanceof TextOutputCallback) {
if (config.getUserCallbackKinds().contains(CallbackKind.GENERAL_OUTPUT)) {
userCallbacks.add(callback);
continue;
}
// ignore
continue;
} else if (callback instanceof TextInputCallback) { // must come after RealmCallback
if (config.getUserCallbackKinds().contains(CallbackKind.GENERAL_INPUT)) {
userCallbacks.add(callback);
continue;
}
// always choose the default
final TextInputCallback inputCallback = (TextInputCallback) callback;
final String text = inputCallback.getText();
if (text == null) {
final String defaultText = inputCallback.getDefaultText();
if (defaultText != null) {
inputCallback.setText(defaultText);
} else {
CallbackUtil.unsupported(callback);
continue;
}
}
continue;
} else if (userCallbackHandler != null) {
userCallbacks.add(callback);
} else {
CallbackUtil.unsupported(callback);
continue;
}
}
if (! userCallbacks.isEmpty()) {
// pass on to the user callback handler
assert userCallbackHandler != null; // otherwise userCallbacks would be empty
final Callback[] userCallbackArray = userCallbacks.toArray(NO_CALLBACKS);
userCallbackHandler.handle(userCallbackArray);
}
}
}
}
| [ELY-1660] Fix EntityTest failure on OpenJDK 9
| src/main/java/org/wildfly/security/auth/client/AuthenticationConfiguration.java | [ELY-1660] Fix EntityTest failure on OpenJDK 9 | <ide><path>rc/main/java/org/wildfly/security/auth/client/AuthenticationConfiguration.java
<ide> continue;
<ide> }
<ide> final TrustedAuthoritiesCallback trustedAuthoritiesCallback = (TrustedAuthoritiesCallback) callback;
<del> if (trustedAuthorities == null) {
<del> trustedAuthorities = new ArrayList<>(trustedAuthoritiesCallback.getTrustedAuthorities());
<del> } else {
<del> final List<TrustedAuthority> authorities = new ArrayList<>(trustedAuthoritiesCallback.getTrustedAuthorities());
<del> authorities.removeIf(trustedAuthorities::contains);
<del> trustedAuthorities.addAll(authorities);
<add> final List<TrustedAuthority> trustedAuthoritiesHolder = trustedAuthoritiesCallback.getTrustedAuthorities();
<add> if (trustedAuthoritiesHolder != null) {
<add> if (trustedAuthorities == null) {
<add> trustedAuthorities = new ArrayList<>(trustedAuthoritiesHolder);
<add> } else {
<add> final List<TrustedAuthority> authorities = new ArrayList<>(trustedAuthoritiesHolder);
<add> authorities.removeIf(trustedAuthorities::contains);
<add> trustedAuthorities.addAll(authorities);
<add> }
<ide> }
<ide> continue;
<ide> } else if (callback instanceof EvidenceVerifyCallback) { |
|
JavaScript | mit | f6b74557fef38bef6668ac901368fd7a9ff6a172 | 0 | tudurom/albumify,tudurom/albumify | function getArg() { return location.hash.slice(1); }
function reload() {
parsed = JSON.parse(atob(getArg()));
if (parsed.title) {
$('title').text(parsed.title + ' | Album-ify!');
$('#titleText').text(parsed.title);
} else {
$('title').text('Album-ify!');
$('#titleHr').hide();
}
$('#descText').html(marked(parsed.description));
album = parsed.album;
console.log(atob(getArg()));
var r = "";
album.forEach(function (el, i) {
r += '<div class="pic">';
r += `<h3 class="title">${el.title}</h3>`;
r += `<a href="${el.picSrc}"><img src="${el.picSrc}" /></a>`;
r += '</div>';
});
$('.container').html(r);
}
album = [];
$(document).ready(function () {
reload();
$('#remix')[0].href += location.hash;
$(window).on('hashchange', function () {
reload();
});
});
| js/view.js | function getArg() { return location.hash.slice(1); }
function reload() {
parsed = JSON.parse(atob(getArg()));
if (parsed.title) {
$('title').text(parsed.title + ' | Album-ify!');
$('#titleText').text(parsed.title);
} else {
$('title').text('Album-ify!');
$('#titleHr').hide();
}
$('#descText').html(marked(parsed.description));
album = parsed.album;
console.log(atob(getArg()));
var r = "";
album.forEach(function (el, i) {
r += '<div class="pic">';
r += `<h3 class="title">${el.title}</h3>`;
r += `<img src="${el.picSrc}"`;
r += '</div>';
});
$('.container').html(r);
}
album = [];
$(document).ready(function () {
reload();
$('#remix')[0].href += location.hash;
$(window).on('hashchange', function () {
reload();
});
});
| Now images are clickable
| js/view.js | Now images are clickable | <ide><path>s/view.js
<ide> album.forEach(function (el, i) {
<ide> r += '<div class="pic">';
<ide> r += `<h3 class="title">${el.title}</h3>`;
<del> r += `<img src="${el.picSrc}"`;
<add> r += `<a href="${el.picSrc}"><img src="${el.picSrc}" /></a>`;
<ide> r += '</div>';
<ide> });
<ide> $('.container').html(r); |
|
JavaScript | mit | 395603101f8419c2583843303fdce8e3fb977a85 | 0 | rappid/rAppid.js,rappid/rAppid.js | define(["js/core/Bindable", "underscore"], function (Bindable, _) {
var undefined;
function stringToPrimitive(str) {
// if it's not a string
if (_.isString(str)) {
var num = Number(str);
if (!isNaN(num)) {
return num;
}
if (str === "true") {
return true;
} else if (str === "false") {
return false;
}
}
return str;
}
var Element = Bindable.inherit("js.core.Element", {
ctor: function (attributes, descriptor, systemManager, parentScope, rootScope) {
attributes = attributes || {};
if (!descriptor) {
// created from node
if (!rootScope) {
rootScope = this;
}
}
this.$descriptor = descriptor;
this.$systemManager = systemManager;
this.$parentScope = parentScope || null;
this.$rootScope = rootScope || null;
this.$attributesNamespace = this.$attributesNamespace || {};
this.callBase(attributes);
this._initializeAttributes(this.$);
// manually constructed
if (descriptor === undefined || descriptor === null) {
this._initialize(this.$creationPolicy);
}
},
_getAttributesFromDescriptor: function (descriptor) {
this.$attributesNamespace = this.$attributesNamespace || {};
var attributes = {};
if (descriptor && descriptor.attributes) {
var node, localName;
for (var a = 0; a < descriptor.attributes.length; a++) {
node = descriptor.attributes[a];
// don't add xmlns attributes
if(node.nodeName.indexOf("xmlns") !== 0){
localName = this._getLocalNameFromNode(node);
attributes[localName] = stringToPrimitive(node.value);
if (node.namespaceURI) {
this.$attributesNamespace[localName] = node.namespaceURI;
}
}
}
}
return attributes;
},
_getLocalNameFromNode: function(node){
return node.localName ? node.localName : node.name.split(":").pop();
},
defaults: {
creationPolicy: "auto"
},
_initializeAttributes: function (attributes) {
},
_initializeDescriptors: function () {
},
/**
*
* @param creationPolicy
* auto - do not overwrite (default),
* all - create all children
* TODO none?
*/
_initialize: function (creationPolicy, withBindings) {
if (this.$initialized) {
return;
}
this._preinitialize();
this.initialize();
this._initializeDescriptors();
if (this == this.$rootScope || withBindings) {
this._initializeBindings();
}
},
_initializeBindings: function () {
this._initializationComplete();
},
initialize: function () {
},
find: function (key) {
var scope = this.getScopeForKey(key);
if (this === scope) {
return this.get(key);
} else if (scope != null) {
return scope.get(key);
} else {
return null;
}
},
getScopeForKey: function (key) {
// try to find value for first key
var value = this.$[key];
// if value was found
if (!_.isUndefined(value)) {
return this;
} else if (this.$parentScope) {
return this.$parentScope.getScopeForKey(key);
} else {
return null;
}
},
getScopeForFncName: function (fncName) {
var fnc = this[fncName];
if (!_.isUndefined(fnc) && _.isFunction(fnc)) {
return this;
} else if (this.$parentScope) {
return this.$parentScope.getScopeForFncName(fncName);
} else {
return null;
}
},
_preinitialize: function () {
},
_initializationComplete: function () {
// call commitChangedAttributes for all attributes
this._commitChangedAttributes(this.$);
this.$initialized = true;
},
_getTextContentFromDescriptor: function (desc) {
var textContent = desc.textContent || desc.text || desc.data;
if (!textContent) {
textContent = "";
for (var i = 0; i < desc.childNodes.length; i++) {
var node = desc.childNodes[i];
// element or cdata node
if (node.nodeType == 1 || node.nodeType == 4) {
textContent += this._getTextContentFromDescriptor(node);
}
}
}
return textContent;
}
});
Element.xmlStringToDom = function(xmlString) {
if (window && window.DOMParser) {
return (new DOMParser()).parseFromString(xmlString, "text/xml").documentElement;
} else if (typeof(ActiveXObject) !== "undefined") {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlString);
return xmlDoc.documentElement;
} else {
throw "Couldn't parse xml string";
}
};
return Element;
}
); | js/core/Element.js | define(["js/core/Bindable", "underscore"], function (Bindable, _) {
var undefined;
function stringToPrimitive(str) {
// if it's not a string
if (_.isString(str)) {
var num = Number(str);
if (!isNaN(num)) {
return num;
}
if (str === "true") {
return true;
} else if (str === "false") {
return false;
}
}
return str;
}
var Element = Bindable.inherit("js.core.Element", {
ctor: function (attributes, descriptor, systemManager, parentScope, rootScope) {
attributes = attributes || {};
if (!descriptor) {
// created from node
if (!rootScope) {
rootScope = this;
}
}
this.$descriptor = descriptor;
this.$systemManager = systemManager;
this.$parentScope = parentScope || null;
this.$rootScope = rootScope || null;
this.$attributesNamespace = this.$attributesNamespace || {};
this.callBase(attributes);
this._initializeAttributes(this.$);
// manually constructed
if (descriptor === undefined || descriptor === null) {
this._initialize(this.$creationPolicy);
}
},
_getAttributesFromDescriptor: function (descriptor) {
this.$attributesNamespace = this.$attributesNamespace || {};
var attributes = {};
if (descriptor && descriptor.attributes) {
var node;
for (var a = 0; a < descriptor.attributes.length; a++) {
node = descriptor.attributes[a];
// don't add xmlns attributes
if(node.nodeName.indexOf("xmlns") !== 0){
attributes[node.localName] = stringToPrimitive(node.value);
if (node.namespaceURI) {
this.$attributesNamespace[node.localName] = node.namespaceURI;
}
}
}
}
return attributes;
},
defaults: {
creationPolicy: "auto"
},
_initializeAttributes: function (attributes) {
},
_initializeDescriptors: function () {
},
/**
*
* @param creationPolicy
* auto - do not overwrite (default),
* all - create all children
* TODO none?
*/
_initialize: function (creationPolicy, withBindings) {
if (this.$initialized) {
return;
}
this._preinitialize();
this.initialize();
this._initializeDescriptors();
if (this == this.$rootScope || withBindings) {
this._initializeBindings();
}
},
_initializeBindings: function () {
this._initializationComplete();
},
initialize: function () {
},
find: function (key) {
var scope = this.getScopeForKey(key);
if (this === scope) {
return this.get(key);
} else if (scope != null) {
return scope.get(key);
} else {
return null;
}
},
getScopeForKey: function (key) {
// try to find value for first key
var value = this.$[key];
// if value was found
if (!_.isUndefined(value)) {
return this;
} else if (this.$parentScope) {
return this.$parentScope.getScopeForKey(key);
} else {
return null;
}
},
getScopeForFncName: function (fncName) {
var fnc = this[fncName];
if (!_.isUndefined(fnc) && _.isFunction(fnc)) {
return this;
} else if (this.$parentScope) {
return this.$parentScope.getScopeForFncName(fncName);
} else {
return null;
}
},
_preinitialize: function () {
},
_initializationComplete: function () {
// call commitChangedAttributes for all attributes
this._commitChangedAttributes(this.$);
this.$initialized = true;
},
_getTextContentFromDescriptor: function (desc) {
var textContent = desc.textContent || desc.text || desc.data;
if (!textContent) {
textContent = "";
for (var i = 0; i < desc.childNodes.length; i++) {
var node = desc.childNodes[i];
// element or cdata node
if (node.nodeType == 1 || node.nodeType == 4) {
textContent += this._getTextContentFromDescriptor(node);
}
}
}
return textContent;
}
});
Element.xmlStringToDom = function(xmlString) {
if (window && window.DOMParser) {
return (new DOMParser()).parseFromString(xmlString, "text/xml").documentElement;
} else if (typeof(ActiveXObject) !== "undefined") {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlString);
return xmlDoc.documentElement;
} else {
throw "Couldn't parse xml string";
}
};
return Element;
}
); | refactored getLocalNameForNode
| js/core/Element.js | refactored getLocalNameForNode | <ide><path>s/core/Element.js
<ide> var attributes = {};
<ide>
<ide> if (descriptor && descriptor.attributes) {
<del> var node;
<add> var node, localName;
<ide>
<ide> for (var a = 0; a < descriptor.attributes.length; a++) {
<ide> node = descriptor.attributes[a];
<ide> // don't add xmlns attributes
<ide> if(node.nodeName.indexOf("xmlns") !== 0){
<del> attributes[node.localName] = stringToPrimitive(node.value);
<add> localName = this._getLocalNameFromNode(node);
<add> attributes[localName] = stringToPrimitive(node.value);
<ide>
<ide> if (node.namespaceURI) {
<del> this.$attributesNamespace[node.localName] = node.namespaceURI;
<add> this.$attributesNamespace[localName] = node.namespaceURI;
<ide> }
<ide>
<ide> }
<ide>
<ide> return attributes;
<ide> },
<del>
<add> _getLocalNameFromNode: function(node){
<add> return node.localName ? node.localName : node.name.split(":").pop();
<add> },
<ide> defaults: {
<ide> creationPolicy: "auto"
<ide> }, |
|
Java | apache-2.0 | 0d9362061ee98c15de62eea91e03b10c3366d15f | 0 | physikerwelt/jwbf,physikerwelt/jwbf,buddies2705/jwbf,Hunsu/jwbf,buddies2705/jwbf,eldur/jwbf,Hunsu/jwbf,eldur/jwbf | /*
* Copyright 2007 Thomas Stock.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Contributors:
*
*/
package net.sourceforge.jwbf;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import lombok.val;
/**
* @author Thomas Stock
*/
public final class JWBF {
private static boolean errorInfo = true;
static Map<String, String> cache = null;
static final String DEVEL = "DEVEL";
static final char SEPARATOR_CHAR = '/';
private static final String JAR_FILE_INDEX = "jar:file:";
private static final String FILE_INDEX = "file:";
private static final FileFilter DIRECTORY_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
};
private JWBF() {
// do nothing
}
private static Map<String, String> lazyVersion() {
val clazz = JWBF.class;
val packageName = packageNameOf(clazz);
val url = urlOf(clazz, packageName);
synchronized (JWBF.class) {
if (cache == null) {
synchronized (JWBF.class) {
cache = init(packageName, url);
}
}
}
return cache;
}
static Map<String, String> init(String packageName, URL url) {
val lowerCaseUrl = urlExtract(url).toLowerCase();
if (lowerCaseUrl.startsWith(JAR_FILE_INDEX)) {
return jarManifestLookup(packageName, url);
} else if (lowerCaseUrl.startsWith(FILE_INDEX)) {
return fileSystemManifestLookup(packageName, url);
} else {
return new HashMap<>();
}
}
private static URL urlOf(Class<?> clazz, String packagename) {
return clazz.getClassLoader().getResource(packagename);
}
private static String packageNameOf(Class<?> clazz) {
return clazz.getPackage().getName().replace('.', SEPARATOR_CHAR);
}
private static Map<String, String> fileSystemManifestLookup(String packageName, URL url) {
Manifest manifest = findManifest(urlToFile(url).getAbsolutePath());
File root = urlToFile(url);
File[] dirs = root.listFiles(DIRECTORY_FILTER);
List<ContainerEntry> entries = filesToEntries(dirs, packageName);
return makeVersionMap(packageName, manifest, entries);
}
private static Map<String, String> jarManifestLookup(String packageName, URL url) {
int jarEnd = urlExtract(url).indexOf("!" + SEPARATOR_CHAR);
val jarFileName = urlExtract(url).substring(JAR_FILE_INDEX.length(), jarEnd);
Manifest manifest = findManifest(jarFileName);
List<ContainerEntry> elements = jarToEntries(jarFileName);
return makeVersionMap(packageName, manifest, elements);
}
private static String urlExtract(URL url) {
return url.toExternalForm();
}
static Map<String, String> makeVersionMap(String packageName, Manifest manifest,
List<ContainerEntry> elements) {
Map<String, String> parts = new HashMap<>();
for (ContainerEntry element : elements) {
String jarEntryName = element.getName();
String shlashes = jarEntryName.replaceAll("[a-zA-Z0-9]", "");
if (element.isDirectory() && jarEntryName.contains(packageName) && shlashes.length() == 4) {
String wikiSystemName = jarEntryName.split(SEPARATOR_CHAR + "")[3];
String artifactId = readMFProductTitle(manifest) + "-" + wikiSystemName;
String readMFVersion = readMFVersion(manifest);
parts.put(artifactId, readMFVersion);
}
}
return parts;
}
private static List<ContainerEntry> filesToEntries(File[] dirs, String packageName) {
List<ContainerEntry> result = new ArrayList<>();
if (dirs != null) {
for (File f : dirs) {
if (f.isDirectory()) {
String name = makeFileName(f, packageName);
if (!name.isEmpty()) {
result.add(new ContainerEntry(name, true));
}
result.addAll(filesToEntries(f.listFiles(DIRECTORY_FILTER), packageName));
}
}
}
return result;
}
private static String makeFileName(File file, String packageName) {
String path = file.getAbsolutePath();
int indexOfPackage = path.indexOf(packageName);
if (indexOfPackage == -1) {
return "";
}
return path.substring(indexOfPackage);
}
static List<ContainerEntry> jarToEntries(String jarFileName) {
List<ContainerEntry> result = new ArrayList<>();
try (JarFile jar = new JarFile(jarFileName)) {
Enumeration<JarEntry> je = jar.entries();
while (je.hasMoreElements()) {
JarEntry jarEntry = je.nextElement();
boolean directory = jarEntry.isDirectory();
result.add(new ContainerEntry(jarEntry.getName(), directory));
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @param clazz
* of the module
* @return the version
*/
public static String getVersion(Class<?> clazz) {
return getPartInfo(lazyVersion(), clazz, "Version unknown").version;
}
/**
* @param clazz
* of the module
* @return the version
*/
public static String getPartId(Class<?> clazz) {
return getPartInfo(lazyVersion(), clazz, "No Module for " + clazz.getName()).id;
}
private static PartContainer getPartInfo(Map<String, String> versionDetails, Class<?> clazz,
String fallbackValue) {
String[] packageParts = clazz.getPackage().getName().split("\\.");
if (packageParts.length > 3) {
String classContainer = packageParts[3];
for (Entry<String, String> entry : versionDetails.entrySet()) {
if (entry.getKey().contains(classContainer)) {
return new PartContainer(entry.getKey(), entry.getValue());
}
}
}
return new PartContainer(fallbackValue, fallbackValue);
}
private static class PartContainer {
final String id;
final String version;
public PartContainer(String id, String version) {
this.id = id;
this.version = version;
}
}
/**
* Prints the JWBF Version.
*/
public static void printVersion() {
System.out.println(getVersions());
}
public static void main(String[] args) {
printVersion();
}
/**
* @return the JWBF Version.
*/
public static Map<String, String> getVersions() {
return Collections.unmodifiableMap(lazyVersion());
}
private static String readMFVersion(Manifest manifest) {
return readFromManifest(manifest, "Implementation-Version", DEVEL);
}
private static String readMFProductTitle(Manifest mainfest) {
return readFromManifest(mainfest, "Implementation-Title", "jwbf-generic");
}
private static String readFromManifest(Manifest manifest, String manifestKey, String fallback) {
if (manifest == null) {
return logAndReturn(fallback);
}
val result = manifest.getMainAttributes().getValue(manifestKey);
if (result == null) {
return logAndReturn(fallback);
}
return result;
}
private static String logAndReturn(String fallback) {
if (errorInfo) {
errorInfo = false;
val msg = "E: no MANIFEST.MF found, please create it.";
System.err.println(msg);
}
return fallback;
}
private static Manifest findManifest(String filesystemPath) {
URL manifestUrl;
if (filesystemPath.endsWith(".jar")) {
manifestUrl = newURL(JAR_FILE_INDEX + filesystemPath + "!/META-INF/MANIFEST.MF");
} else {
if (!filesystemPath.endsWith(File.separator)) {
filesystemPath += File.separatorChar;
}
manifestUrl = searchMF(filesystemPath);
}
if (manifestUrl != null) {
return newManifest(manifestUrl);
}
return null;
}
private static Manifest newManifest(URL manifestUrl) {
try {
return new Manifest(manifestUrl.openStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static URL searchMF(String fileName) {
if (fileName == null) {
return null;
}
val file = new File(fileName);
val manifestFileName = "MANIFEST.MF";
val manifestFile = new File(file, manifestFileName);
if (manifestFile.exists()) {
return newURL(FILE_INDEX + file + File.separatorChar + manifestFileName);
} else {
return searchMF(file.getParent());
}
}
static class ContainerEntry {
private final String name;
private final boolean directory;
public ContainerEntry(String name, boolean directory) {
this.name = name;
this.directory = directory;
}
public String getName() {
return name;
}
public boolean isDirectory() {
return directory;
}
@Override
public String toString() {
return Objects.toString(name) + " " + directory;
}
@Override
public int hashCode() {
return Objects.hash(name, directory);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else if (obj instanceof ContainerEntry) {
val that = (ContainerEntry) obj;
return Objects.equals(this.name, that.name) && //
Objects.equals(this.directory, that.directory) //
;
} else {
return false;
}
}
}
public static URL newURLWithoutHandler(final String url) {
try {
return new URL(null, url, new UnsupportedHandler());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(url, e);
}
}
public static URL newURL(final String url) {
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(url, e);
}
}
private static class UnsupportedHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
throw new UnsupportedOperationException();
}
}
public static File urlToFile(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(urlExtract(url), e);
}
}
}
| src/main/java/net/sourceforge/jwbf/JWBF.java | /*
* Copyright 2007 Thomas Stock.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Contributors:
*
*/
package net.sourceforge.jwbf;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import lombok.val;
/**
* @author Thomas Stock
*/
public final class JWBF {
private static boolean errorInfo = true;
static Map<String, String> cache = null;
static final String DEVEL = "DEVEL";
static final char SEPARATOR_CHAR = '/';
private static final String JAR_FILE_INDEX = "jar:file:";
private static final String FILE_INDEX = "file:";
private static final FileFilter DIRECTORY_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
};
private JWBF() {
// do nothing
}
private static Map<String, String> lazyVersion() {
val clazz = JWBF.class;
val packageName = packageNameOf(clazz);
val url = urlOf(clazz, packageName);
synchronized (JWBF.class) {
if (cache == null) {
synchronized (JWBF.class) {
cache = init(packageName, url);
}
}
}
return cache;
}
static Map<String, String> init(String packageName, URL url) {
val lowerCaseUrl = urlExtract(url).toLowerCase();
if (lowerCaseUrl.startsWith(JAR_FILE_INDEX)) {
return jarManifestLookup(packageName, url);
} else if (lowerCaseUrl.startsWith(FILE_INDEX)) {
return fileSystemManifestLookup(packageName, url);
} else {
return new HashMap<>();
}
}
private static URL urlOf(Class<?> clazz, String packagename) {
return clazz.getClassLoader().getResource(packagename);
}
private static String packageNameOf(Class<?> clazz) {
return clazz.getPackage().getName().replace('.', SEPARATOR_CHAR);
}
private static Map<String, String> fileSystemManifestLookup(String packageName, URL url) {
Manifest manifest = findManifest(urlToFile(url).getAbsolutePath());
File root = urlToFile(url);
File[] dirs = root.listFiles(DIRECTORY_FILTER);
List<ContainerEntry> entries = filesToEntries(dirs, packageName);
return makeVersionMap(packageName, manifest, entries);
}
private static Map<String, String> jarManifestLookup(String packageName, URL url) {
int jarEnd = urlExtract(url).indexOf("!" + SEPARATOR_CHAR);
val jarFileName = urlExtract(url).substring(JAR_FILE_INDEX.length(), jarEnd);
Manifest manifest = findManifest(jarFileName);
List<ContainerEntry> elements = jarToEntries(jarFileName);
return makeVersionMap(packageName, manifest, elements);
}
private static String urlExtract(URL url) {
return url.toExternalForm();
}
static Map<String, String> makeVersionMap(String packageName, Manifest manifest,
List<ContainerEntry> elements) {
Map<String, String> parts = new HashMap<>();
for (ContainerEntry element : elements) {
String jarEntryName = element.getName();
String shlashes = jarEntryName.replaceAll("[a-zA-Z0-9]", "");
if (element.isDirectory() && jarEntryName.contains(packageName) && shlashes.length() == 4) {
String wikiSystemName = jarEntryName.split(SEPARATOR_CHAR + "")[3];
String artifactId = readMFProductTitle(manifest) + "-" + wikiSystemName;
String readMFVersion = readMFVersion(manifest);
parts.put(artifactId, readMFVersion);
}
}
return parts;
}
private static List<ContainerEntry> filesToEntries(File[] dirs, String packageName) {
List<ContainerEntry> result = new ArrayList<>();
if (dirs != null) {
for (File f : dirs) {
if (f.isDirectory()) {
String name = makeFileName(f, packageName);
if (!name.isEmpty()) {
result.add(new ContainerEntry(name, true));
}
result.addAll(filesToEntries(f.listFiles(DIRECTORY_FILTER), packageName));
}
}
}
return result;
}
private static String makeFileName(File file, String packageName) {
String path = file.getAbsolutePath();
int indexOfPackage = path.indexOf(packageName);
if (indexOfPackage == -1) {
return "";
}
return path.substring(indexOfPackage);
}
static List<ContainerEntry> jarToEntries(String jarFileName) {
List<ContainerEntry> result = new ArrayList<>();
try (JarFile jar = new JarFile(jarFileName)) {
Enumeration<JarEntry> je = jar.entries();
while (je.hasMoreElements()) {
JarEntry jarEntry = je.nextElement();
boolean directory = jarEntry.isDirectory();
result.add(new ContainerEntry(jarEntry.getName(), directory));
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @param clazz
* of the module
* @return the version
*/
public static String getVersion(Class<?> clazz) {
return getPartInfo(lazyVersion(), clazz, "Version unknown", 1);
}
/**
* @param clazz
* of the module
* @return the version
*/
public static String getPartId(Class<?> clazz) {
return getPartInfo(lazyVersion(), clazz, "No Module for " + clazz.getName(), 0);
}
private static String getPartInfo(Map<String, String> versionDetails, Class<?> clazz,
String fallbackValue, int elementNo) {
String[] packageParts = clazz.getPackage().getName().split("\\.");
if (packageParts.length > 3) {
String classContainer = packageParts[3];
for (Entry<String, String> key : versionDetails.entrySet()) {
if (key.getKey().contains(classContainer)) {
String[] result = { key.getKey(), key.getValue() };
return result[elementNo];
}
}
}
return fallbackValue;
}
/**
* Prints the JWBF Version.
*/
public static void printVersion() {
System.out.println(getVersions());
}
public static void main(String[] args) {
printVersion();
}
/**
* @return the JWBF Version.
*/
public static Map<String, String> getVersions() {
return Collections.unmodifiableMap(lazyVersion());
}
private static String readMFVersion(Manifest manifest) {
return readFromManifest(manifest, "Implementation-Version", DEVEL);
}
private static String readMFProductTitle(Manifest mainfest) {
return readFromManifest(mainfest, "Implementation-Title", "jwbf-generic");
}
private static String readFromManifest(Manifest manifest, String manifestKey, String fallback) {
if (manifest == null) {
return logAndReturn(fallback);
}
val result = manifest.getMainAttributes().getValue(manifestKey);
if (result == null) {
return logAndReturn(fallback);
}
return result;
}
private static String logAndReturn(String fallback) {
if (errorInfo) {
errorInfo = false;
String msg = "E: no MANIFEST.MF found, please create it.";
System.err.println(msg);
}
return fallback;
}
private static Manifest findManifest(String filesystemPath) {
URL manifestUrl;
if (filesystemPath.endsWith(".jar")) {
manifestUrl = newURL(JAR_FILE_INDEX + filesystemPath + "!/META-INF/MANIFEST.MF");
} else {
if (!filesystemPath.endsWith(File.separator)) {
filesystemPath += File.separatorChar;
}
manifestUrl = searchMF(filesystemPath);
}
if (manifestUrl != null) {
return newManifest(manifestUrl);
}
return null;
}
private static Manifest newManifest(URL manifestUrl) {
try {
return new Manifest(manifestUrl.openStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static URL searchMF(String fileName) {
if (fileName == null) {
return null;
}
File file = new File(fileName);
String manifestFileName = "MANIFEST.MF";
File manifestFile = new File(file, manifestFileName);
if (manifestFile.exists()) {
return newURL(FILE_INDEX + file + File.separatorChar + manifestFileName);
} else {
return searchMF(file.getParent());
}
}
static class ContainerEntry {
private final String name;
private final boolean directory;
public ContainerEntry(String name, boolean directory) {
this.name = name;
this.directory = directory;
}
public String getName() {
return name;
}
public boolean isDirectory() {
return directory;
}
@Override
public String toString() {
return Objects.toString(name) + " " + directory;
}
@Override
public int hashCode() {
return Objects.hash(name, directory);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else if (obj instanceof ContainerEntry) {
ContainerEntry that = (ContainerEntry) obj;
return Objects.equals(this.name, that.name) && //
Objects.equals(this.directory, that.directory) //
;
} else {
return false;
}
}
}
public static URL newURLWithoutHandler(final String url) {
try {
return new URL(null, url, new UnsupportedHandler());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(url, e);
}
}
public static URL newURL(final String url) {
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(url, e);
}
}
private static class UnsupportedHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u) throws IOException {
throw new UnsupportedOperationException();
}
}
public static File urlToFile(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(urlExtract(url), e);
}
}
}
| Removed magic numbers in jwbf version info
| src/main/java/net/sourceforge/jwbf/JWBF.java | Removed magic numbers in jwbf version info | <ide><path>rc/main/java/net/sourceforge/jwbf/JWBF.java
<ide> * @return the version
<ide> */
<ide> public static String getVersion(Class<?> clazz) {
<del> return getPartInfo(lazyVersion(), clazz, "Version unknown", 1);
<add> return getPartInfo(lazyVersion(), clazz, "Version unknown").version;
<ide> }
<ide>
<ide> /**
<ide> * @return the version
<ide> */
<ide> public static String getPartId(Class<?> clazz) {
<del> return getPartInfo(lazyVersion(), clazz, "No Module for " + clazz.getName(), 0);
<del> }
<del>
<del> private static String getPartInfo(Map<String, String> versionDetails, Class<?> clazz,
<del> String fallbackValue, int elementNo) {
<add> return getPartInfo(lazyVersion(), clazz, "No Module for " + clazz.getName()).id;
<add> }
<add>
<add> private static PartContainer getPartInfo(Map<String, String> versionDetails, Class<?> clazz,
<add> String fallbackValue) {
<ide> String[] packageParts = clazz.getPackage().getName().split("\\.");
<ide> if (packageParts.length > 3) {
<ide> String classContainer = packageParts[3];
<del> for (Entry<String, String> key : versionDetails.entrySet()) {
<del> if (key.getKey().contains(classContainer)) {
<del> String[] result = { key.getKey(), key.getValue() };
<del> return result[elementNo];
<add> for (Entry<String, String> entry : versionDetails.entrySet()) {
<add> if (entry.getKey().contains(classContainer)) {
<add> return new PartContainer(entry.getKey(), entry.getValue());
<ide> }
<ide> }
<ide> }
<del> return fallbackValue;
<add> return new PartContainer(fallbackValue, fallbackValue);
<add> }
<add>
<add> private static class PartContainer {
<add> final String id;
<add> final String version;
<add>
<add> public PartContainer(String id, String version) {
<add> this.id = id;
<add> this.version = version;
<add> }
<ide> }
<ide>
<ide> /**
<ide> private static String logAndReturn(String fallback) {
<ide> if (errorInfo) {
<ide> errorInfo = false;
<del> String msg = "E: no MANIFEST.MF found, please create it.";
<add> val msg = "E: no MANIFEST.MF found, please create it.";
<ide> System.err.println(msg);
<ide> }
<ide> return fallback;
<ide> if (fileName == null) {
<ide> return null;
<ide> }
<del> File file = new File(fileName);
<del> String manifestFileName = "MANIFEST.MF";
<del> File manifestFile = new File(file, manifestFileName);
<add> val file = new File(fileName);
<add> val manifestFileName = "MANIFEST.MF";
<add> val manifestFile = new File(file, manifestFileName);
<ide> if (manifestFile.exists()) {
<ide> return newURL(FILE_INDEX + file + File.separatorChar + manifestFileName);
<ide> } else {
<ide> } else if (obj == this) {
<ide> return true;
<ide> } else if (obj instanceof ContainerEntry) {
<del> ContainerEntry that = (ContainerEntry) obj;
<add> val that = (ContainerEntry) obj;
<ide> return Objects.equals(this.name, that.name) && //
<ide> Objects.equals(this.directory, that.directory) //
<ide> ; |
|
Java | apache-2.0 | a76a5a5149ff786591c5d68cd6e50fa19f449f00 | 0 | atlasapi/atlas-deer,atlasapi/atlas-deer | package org.atlasapi.query.v4.channelgroup;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.atlasapi.annotation.Annotation;
import org.atlasapi.channel.Channel;
import org.atlasapi.channel.ChannelGroup;
import org.atlasapi.channel.ChannelGroupMembership;
import org.atlasapi.channel.ChannelGroupRef;
import org.atlasapi.channel.ChannelGroupResolver;
import org.atlasapi.channel.ChannelGroupSummary;
import org.atlasapi.channel.ChannelNumbering;
import org.atlasapi.channel.ChannelResolver;
import org.atlasapi.channel.Platform;
import org.atlasapi.channel.Region;
import org.atlasapi.channel.ResolvedChannel;
import org.atlasapi.channel.ResolvedChannelGroup;
import org.atlasapi.criteria.AttributeQuery;
import org.atlasapi.criteria.attribute.Attributes;
import org.atlasapi.entity.Id;
import org.atlasapi.entity.ResourceRef;
import org.atlasapi.entity.util.Resolved;
import org.atlasapi.output.NotFoundException;
import org.atlasapi.query.common.Query;
import org.atlasapi.query.common.QueryExecutor;
import org.atlasapi.query.common.QueryResult;
import org.atlasapi.query.common.context.QueryContext;
import org.atlasapi.query.common.exceptions.QueryExecutionException;
import org.atlasapi.query.common.exceptions.UncheckedQueryExecutionException;
import com.metabroadcast.applications.client.model.internal.ApplicationConfiguration;
import com.metabroadcast.common.ids.NumberToShortStringCodec;
import com.metabroadcast.common.ids.SubstitutionTableNumberCodec;
import com.metabroadcast.common.stream.MoreCollectors;
import com.metabroadcast.promise.Promise;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.Futures;
import org.joda.time.LocalDate;
import static com.google.common.base.Preconditions.checkNotNull;
public class ChannelGroupQueryExecutor implements QueryExecutor<ResolvedChannelGroup> {
private final NumberToShortStringCodec idCodec = SubstitutionTableNumberCodec.lowerCaseOnly();
private final ChannelGroupResolver channelGroupResolver;
private final ChannelResolver channelResolver;
public ChannelGroupQueryExecutor(
ChannelGroupResolver channelGroupResolver,
ChannelResolver channelResolver
) {
this.channelGroupResolver = checkNotNull(channelGroupResolver);
this.channelResolver = channelResolver;
}
@Nonnull
@Override
public QueryResult<ResolvedChannelGroup> execute(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
return query.isListQuery() ? executeListQuery(query) : executeSingleQuery(query);
}
private QueryResult<ResolvedChannelGroup> executeSingleQuery(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
return Futures.get(
Futures.transform(
channelGroupResolver.resolveIds(
ImmutableSet.of(query.getOnlyId()),
Boolean.parseBoolean(query.getContext().getRequest().getParameter(Attributes.REFRESH_CACHE_PARAM))
),
(Resolved<ChannelGroup<?>> resolved) -> {
if (resolved.getResources().isEmpty()) {
throw new UncheckedQueryExecutionException(
new NotFoundException(query.getOnlyId())
);
}
ChannelGroup channelGroup = resolved.getResources()
.first()
.get();
boolean queryHasOperands = !query.getOperands().isEmpty();
if (queryHasOperands) {
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_DTT_CHANNELS.externalName())) {
List<Id> dttIds = (List<Id>) attributeQuery.getValue();
if (!dttIds.isEmpty() && dttIds.contains(channelGroup.getId())) {
filterDttChannels(channelGroup);
}
}
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IP_CHANNELS.externalName())) {
List<Id> ipIds = (List<Id>) attributeQuery.getValue();
if (!ipIds.isEmpty() && ipIds.contains(channelGroup.getId())) {
filterIpChannels(channelGroup);
}
}
}
}
ResolvedChannelGroup resolvedChannelGroup = resolveAnnotationData(
query.getContext(),
channelGroup
);
return QueryResult.singleResult(
resolvedChannelGroup,
query.getContext()
);
}
), 1, TimeUnit.MINUTES, QueryExecutionException.class
);
}
private void filterIpChannels(ChannelGroup channelGroup) {
ImmutableSet<ChannelNumbering> channels = ImmutableSet.copyOf(channelGroup.getChannels());
ImmutableSet<ChannelNumbering> ipChannels = channels.stream()
.filter(channel -> !Strings.isNullOrEmpty(channel.getChannelNumber().get()))
.filter(channel -> Integer.parseInt(channel.getChannelNumber().get()) > 300)
.collect(MoreCollectors.toImmutableSet());
channelGroup.setChannels(ipChannels);
}
private void filterDttChannels(ChannelGroup channelGroup) {
ImmutableSet<ChannelNumbering> immutableSet = ImmutableSet.copyOf(channelGroup.getChannels());
ImmutableSet<ChannelNumbering> dttChannels = immutableSet.stream()
.filter(channel -> !Strings.isNullOrEmpty(channel.getChannelNumber().get()))
.filter(channel -> Integer.parseInt(channel.getChannelNumber().get()) <= 300)
.collect(MoreCollectors.toImmutableSet());
channelGroup.setChannels(dttChannels);
}
private QueryResult<ResolvedChannelGroup> executeListQuery(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
Iterable<ChannelGroup<?>> resolvedChannelGroups;
List<Id> lids = Lists.newArrayList();
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IDS.externalName())) {
lids = (List<Id>) attributeQuery.getValue();
}
}
if (lids.isEmpty()) {
resolvedChannelGroups = Futures.get(
Futures.transform(
channelGroupResolver.allChannels(),
(Resolved<ChannelGroup<?>> input) -> input.getResources()
),
1, TimeUnit.MINUTES,
QueryExecutionException.class
);
} else {
resolvedChannelGroups = Futures.get(
Futures.transform(
channelGroupResolver.resolveIds(
lids,
Boolean.parseBoolean(query.getContext()
.getRequest()
.getParameter(Attributes.REFRESH_CACHE_PARAM)
)
),
(Resolved<ChannelGroup<?>> input) -> input.getResources()
),
1, TimeUnit.MINUTES,
QueryExecutionException.class
);
}
List<ChannelGroup> channelGroups = Lists.newArrayList(resolvedChannelGroups);
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_TYPE.externalName())) {
final String channelGroupType = attributeQuery.getValue().get(0).toString();
channelGroups = channelGroups.stream()
.filter(channelGroup -> channelGroupType.equals(channelGroup.getType()))
.collect(Collectors.toList());
}
if (attributeQuery.getAttributeName()
.equals(Attributes.SOURCE.externalName())) {
channelGroups = channelGroups.stream()
.filter(channelGroup -> channelGroup.getSource()
.key()
.equals(attributeQuery.getValue().get(0).toString())
)
.collect(Collectors.toList());
}
}
channelGroups = query.getContext()
.getSelection()
.get()
.applyTo(channelGroups);
channelGroups = channelGroups.stream()
.filter(input -> query.getContext()
.getApplication()
.getConfiguration()
.isReadEnabled(input.getSource())
)
.collect(Collectors.toList());
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_DTT_CHANNELS.externalName())) {
List<Id> dttIds = (List<Id>) attributeQuery.getValue();
channelGroups.forEach(channelGroup -> {
if (dttIds.contains(channelGroup.getId())) {
filterDttChannels(channelGroup);
}
});
}
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IP_CHANNELS.externalName())) {
List<Id> ipIds = (List<Id>) attributeQuery.getValue();
channelGroups.forEach(channelGroup -> {
if (ipIds.contains(channelGroup.getId())) {
filterIpChannels(channelGroup);
}
});
}
}
ImmutableList<ResolvedChannelGroup> channelGroupsResults = channelGroups.stream()
.map(channelGroup -> resolveAnnotationData(query.getContext(), channelGroup))
.collect(MoreCollectors.toImmutableList());
return QueryResult.listResult(
channelGroupsResults,
query.getContext(),
channelGroupsResults.size()
);
}
private List<String> getIdsListFromAttribute(AttributeQuery<?> attributeQuery) {
return attributeQuery.getValue()
.stream()
.map(Object::toString)
.collect(Collectors.toList());
}
private ResolvedChannelGroup resolveAnnotationData(
QueryContext ctxt,
ChannelGroup<?> channelGroup
) {
ResolvedChannelGroup.Builder resolvedChannelGroupBuilder =
ResolvedChannelGroup.builder(channelGroup);
resolvedChannelGroupBuilder.withRegionChannelGroups(
contextHasAnnotation(ctxt, Annotation.REGIONS) ?
resolveRegionChannelGroups(channelGroup) :
Optional.empty()
);
resolvedChannelGroupBuilder.withPlatformChannelGroup(
contextHasAnnotation(ctxt, Annotation.PLATFORM) ?
resolvePlatformChannelGroup(channelGroup) :
Optional.empty()
);
if (contextHasAnnotation(ctxt, Annotation.FUTURE_CHANNELS)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveChannelsWithChannelGroups(
ctxt.getApplication()
.getConfiguration(),
channelGroup,
contextHasAnnotation(
ctxt,
Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY
)
? this::isChannelGroupMembership
: channelGroupMembership -> true,
true
)
);
} else if (contextHasAnnotation(ctxt, Annotation.CHANNEL_GROUPS_SUMMARY) ||
contextHasAnnotation(ctxt, Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveChannelsWithChannelGroups(
ctxt.getApplication()
.getConfiguration(),
channelGroup,
contextHasAnnotation(
ctxt,
Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY
)
? this::isChannelGroupMembership
: channelGroupMembership -> true,
false
)
);
} else if (contextHasAnnotation(ctxt, Annotation.ADVERTISED_CHANNELS) ||
contextHasAnnotation(ctxt, Annotation.CHANNELS)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveAdvertisedChannels(
channelGroup,
false
)
);
} else {
resolvedChannelGroupBuilder.withAdvertisedChannels(Optional.empty());
}
return resolvedChannelGroupBuilder.build();
}
private Optional<Iterable<ChannelGroup<?>>> resolveRegionChannelGroups(ChannelGroup<?> entity) {
if(!(entity instanceof Platform)) {
return Optional.empty();
}
Platform platform = (Platform) entity;
Iterable<Id> regionIds = platform.getRegions()
.stream()
.map(ChannelGroupRef::getId)
.collect(MoreCollectors.toImmutableSet());
return Optional.of(Promise.wrap(channelGroupResolver.resolveIds(regionIds))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES));
}
private Optional<ChannelGroup<?>> resolvePlatformChannelGroup(ChannelGroup<?> entity) {
if(!(entity instanceof Region)) {
return Optional.empty();
}
Id platformId = ((Region) entity).getPlatform().getId();
return Optional.ofNullable(Promise.wrap(channelGroupResolver.resolveIds(ImmutableSet.of(platformId)))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES)
.first().orNull()
);
}
private Optional<Iterable<ResolvedChannel>> resolveChannelsWithChannelGroups(
ApplicationConfiguration conf,
ChannelGroup<?> entity,
Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate,
boolean withFutureChannels
) {
Optional<Iterable<ResolvedChannel>> channels = resolveAdvertisedChannels(
entity,
withFutureChannels
);
if (!channels.isPresent()) {
return Optional.empty();
}
return Optional.of(
StreamSupport.stream(channels.get().spliterator(), false)
.map(resolvedChannel -> ResolvedChannel.builder(resolvedChannel.getChannel())
.withChannelGroupSummaries(
resolveChannelGroupSummaries(
conf,
resolvedChannel.getChannel(),
whitelistedChannelGroupPredicate
)
)
.withResolvedEquivalents(
resolveChannelEquivalents(
resolvedChannel.getChannel()
)
)
.build()
)
.collect(Collectors.toList())
);
}
private List<ChannelGroupSummary> resolveChannelGroupSummaries(
ApplicationConfiguration conf,
Channel channel,
Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate
) {
Iterable<Id> channelGroupIds = channel.getChannelGroups().stream()
.filter(whitelistedChannelGroupPredicate::apply)
.map(ChannelGroupMembership::getChannelGroup)
.map(ResourceRef::getId)
.collect(MoreCollectors.toImmutableList());
return resolveChannelGroupSummaries(conf, channelGroupIds);
}
private List<ChannelGroupSummary> resolveChannelGroupSummaries(
ApplicationConfiguration conf,
Iterable<Id> channelGroupIds
) {
Iterable<ChannelGroup<?>> channelGroups =
Promise.wrap(channelGroupResolver.resolveIds(channelGroupIds))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
return StreamSupport.stream(channelGroups.spliterator(), false)
.filter(cg -> conf.isReadEnabled(cg.getSource()))
.map(ChannelGroup::toSummary)
.collect(MoreCollectors.toImmutableList());
}
private Optional<Iterable<ResolvedChannel>> resolveAdvertisedChannels(
ChannelGroup<?> entity,
boolean withFutureChannels
) {
final ImmutableMultimap.Builder<Id, ChannelGroupMembership> builder = ImmutableMultimap.builder();
Iterable<? extends ChannelGroupMembership> availableChannels = entity.getChannelsAvailable(LocalDate.now());
if (withFutureChannels) {
availableChannels = entity.getChannels();
}
List<Id> orderedIds = StreamSupport.stream(availableChannels.spliterator(), false)
//TODO fix channel appearing twice in ordering blowing this thing up
.map(cm -> cm.getChannel().getId())
.distinct()
.collect(Collectors.toList());
Ordering<Id> idOrdering = Ordering.explicit(orderedIds);
for (ChannelGroupMembership channelGroupMembership : availableChannels) {
builder.put(channelGroupMembership.getChannel().getId(), channelGroupMembership);
}
ImmutableMultimap<Id, ChannelGroupMembership> channelGroupMemberships = builder.build();
Iterable<Channel> resolvedChannels = Promise.wrap(
channelResolver.resolveIds(channelGroupMemberships.keySet()))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
Iterable<ResolvedChannel> sortedChannels =
StreamSupport.stream(resolvedChannels.spliterator(), false)
.sorted((o1, o2) -> idOrdering.compare(o1.getId(), o2.getId()))
.map(channel -> ResolvedChannel.builder(channel)
.withResolvedEquivalents(resolveChannelEquivalents(channel))
.build()
)
.collect(Collectors.toList());
return Optional.of(sortedChannels);
}
@Nullable
private Iterable<Channel> resolveChannelEquivalents(Channel channel) {
if (channel.getSameAs() == null || channel.getSameAs().isEmpty()) {
return null;
}
Iterable<Id> ids = Iterables.transform(channel.getSameAs(), ResourceRef::getId);
return Promise.wrap(channelResolver.resolveIds(ids))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
}
private boolean contextHasAnnotation(QueryContext ctxt, Annotation annotation) {
return (!Strings.isNullOrEmpty(ctxt.getRequest().getParameter("annotations"))
&&
Splitter.on(',')
.splitToList(
ctxt.getRequest().getParameter("annotations")
).contains(annotation.toKey()));
}
private boolean isChannelGroupMembership(ChannelGroupMembership channelGroupMembership) {
return !(channelGroupMembership instanceof ChannelNumbering);
}
}
| atlas-api/src/main/java/org/atlasapi/query/v4/channelgroup/ChannelGroupQueryExecutor.java | package org.atlasapi.query.v4.channelgroup;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.atlasapi.annotation.Annotation;
import org.atlasapi.channel.Channel;
import org.atlasapi.channel.ChannelGroup;
import org.atlasapi.channel.ChannelGroupMembership;
import org.atlasapi.channel.ChannelGroupRef;
import org.atlasapi.channel.ChannelGroupResolver;
import org.atlasapi.channel.ChannelGroupSummary;
import org.atlasapi.channel.ChannelNumbering;
import org.atlasapi.channel.ChannelResolver;
import org.atlasapi.channel.Platform;
import org.atlasapi.channel.Region;
import org.atlasapi.channel.ResolvedChannel;
import org.atlasapi.channel.ResolvedChannelGroup;
import org.atlasapi.criteria.AttributeQuery;
import org.atlasapi.criteria.attribute.Attributes;
import org.atlasapi.entity.Id;
import org.atlasapi.entity.ResourceRef;
import org.atlasapi.entity.util.Resolved;
import org.atlasapi.output.NotFoundException;
import org.atlasapi.query.common.Query;
import org.atlasapi.query.common.QueryExecutor;
import org.atlasapi.query.common.QueryResult;
import org.atlasapi.query.common.context.QueryContext;
import org.atlasapi.query.common.exceptions.QueryExecutionException;
import org.atlasapi.query.common.exceptions.UncheckedQueryExecutionException;
import com.metabroadcast.applications.client.model.internal.ApplicationConfiguration;
import com.metabroadcast.common.ids.NumberToShortStringCodec;
import com.metabroadcast.common.ids.SubstitutionTableNumberCodec;
import com.metabroadcast.common.stream.MoreCollectors;
import com.metabroadcast.promise.Promise;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.Futures;
import org.joda.time.LocalDate;
import static com.google.common.base.Preconditions.checkNotNull;
public class ChannelGroupQueryExecutor implements QueryExecutor<ResolvedChannelGroup> {
private final NumberToShortStringCodec idCodec = SubstitutionTableNumberCodec.lowerCaseOnly();
private final ChannelGroupResolver channelGroupResolver;
private final ChannelResolver channelResolver;
public ChannelGroupQueryExecutor(
ChannelGroupResolver channelGroupResolver,
ChannelResolver channelResolver
) {
this.channelGroupResolver = checkNotNull(channelGroupResolver);
this.channelResolver = channelResolver;
}
@Nonnull
@Override
public QueryResult<ResolvedChannelGroup> execute(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
return query.isListQuery() ? executeListQuery(query) : executeSingleQuery(query);
}
private QueryResult<ResolvedChannelGroup> executeSingleQuery(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
return Futures.get(
Futures.transform(
channelGroupResolver.resolveIds(
ImmutableSet.of(query.getOnlyId()),
Boolean.parseBoolean(query.getContext().getRequest().getParameter(Attributes.REFRESH_CACHE_PARAM))
),
(Resolved<ChannelGroup<?>> resolved) -> {
if (resolved.getResources().isEmpty()) {
throw new UncheckedQueryExecutionException(
new NotFoundException(query.getOnlyId())
);
}
ChannelGroup channelGroup = resolved.getResources()
.first()
.get();
boolean queryHasOperands = !query.getOperands().isEmpty();
if (queryHasOperands) {
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_DTT_CHANNELS.externalName())) {
List<Id> dttIds = (List<Id>) attributeQuery.getValue();
if (!dttIds.isEmpty() && dttIds.contains(channelGroup.getId())) {
filterDttChannels(channelGroup);
}
}
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IP_CHANNELS.externalName())) {
List<Id> ipIds = (List<Id>) attributeQuery.getValue();
if (!ipIds.isEmpty() && ipIds.contains(channelGroup.getId())) {
filterIpChannels(channelGroup);
}
}
}
}
ResolvedChannelGroup resolvedChannelGroup = resolveAnnotationData(
query.getContext(),
channelGroup
);
return QueryResult.singleResult(
resolvedChannelGroup,
query.getContext()
);
}
), 1, TimeUnit.MINUTES, QueryExecutionException.class
);
}
private void filterIpChannels(ChannelGroup channelGroup) {
ImmutableSet<ChannelNumbering> channels = ImmutableSet.copyOf(channelGroup.getChannels());
ImmutableSet<ChannelNumbering> ipChannels = channels.stream()
.filter(channel -> !Strings.isNullOrEmpty(channel.getChannelNumber().get()))
.filter(channel -> Integer.parseInt(channel.getChannelNumber().get()) > 300)
.collect(MoreCollectors.toImmutableSet());
channelGroup.setChannels(ipChannels);
}
private void filterDttChannels(ChannelGroup channelGroup) {
ImmutableSet<ChannelNumbering> immutableSet = ImmutableSet.copyOf(channelGroup.getChannels());
ImmutableSet<ChannelNumbering> dttChannels = immutableSet.stream()
.filter(channel -> !Strings.isNullOrEmpty(channel.getChannelNumber().get()))
.filter(channel -> Integer.parseInt(channel.getChannelNumber().get()) <= 300)
.collect(MoreCollectors.toImmutableSet());
channelGroup.setChannels(dttChannels);
}
private QueryResult<ResolvedChannelGroup> executeListQuery(Query<ResolvedChannelGroup> query)
throws QueryExecutionException {
Iterable<ChannelGroup<?>> resolvedChannelGroups;
List<Id> lids = Lists.newArrayList();
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IDS.externalName())) {
lids = (List<Id>) attributeQuery.getValue();
}
}
if (lids.isEmpty()) {
resolvedChannelGroups = Futures.get(
Futures.transform(
channelGroupResolver.allChannels(),
(Resolved<ChannelGroup<?>> input) -> input.getResources()
),
1, TimeUnit.MINUTES,
QueryExecutionException.class
);
} else {
resolvedChannelGroups = Futures.get(
Futures.transform(
channelGroupResolver.resolveIds(
lids,
Boolean.parseBoolean(query.getContext()
.getRequest()
.getParameter(Attributes.REFRESH_CACHE_PARAM)
)
),
(Resolved<ChannelGroup<?>> input) -> input.getResources()
),
1, TimeUnit.MINUTES,
QueryExecutionException.class
);
}
List<ChannelGroup> channelGroups = Lists.newArrayList(resolvedChannelGroups);
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_TYPE.externalName())) {
final String channelGroupType = attributeQuery.getValue().get(0).toString();
channelGroups = channelGroups.stream()
.filter(channelGroup -> channelGroupType.equals(channelGroup.getType()))
.collect(Collectors.toList());
}
if (attributeQuery.getAttributeName()
.equals(Attributes.SOURCE.externalName())) {
channelGroups = channelGroups.stream()
.filter(channelGroup -> channelGroup.getSource()
.key()
.equals(attributeQuery.getValue().get(0).toString())
)
.collect(Collectors.toList());
}
}
channelGroups = query.getContext()
.getSelection()
.get()
.applyTo(channelGroups);
channelGroups = channelGroups.stream()
.filter(input -> query.getContext()
.getApplication()
.getConfiguration()
.isReadEnabled(input.getSource())
)
.collect(Collectors.toList());
for (AttributeQuery<?> attributeQuery : query.getOperands()) {
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_DTT_CHANNELS.externalName())) {
List<Id> dttIds = (List<Id>) attributeQuery.getValue();
channelGroups.forEach(channelGroup -> {
if (dttIds.contains(channelGroup.getId())) {
filterDttChannels(channelGroup);
}
});
}
if (attributeQuery.getAttributeName()
.equals(Attributes.CHANNEL_GROUP_IP_CHANNELS.externalName())) {
List<Id> ipIds = (List<Id>) attributeQuery.getValue();
channelGroups.forEach(channelGroup -> {
if (ipIds.contains(channelGroup.getId())) {
filterIpChannels(channelGroup);
}
});
}
}
ImmutableList<ResolvedChannelGroup> channelGroupsResults = channelGroups.stream()
.map(channelGroup -> resolveAnnotationData(query.getContext(), channelGroup))
.collect(MoreCollectors.toImmutableList());
return QueryResult.listResult(
channelGroupsResults,
query.getContext(),
channelGroupsResults.size()
);
}
private List<String> getIdsListFromAttribute(AttributeQuery<?> attributeQuery) {
return attributeQuery.getValue()
.stream()
.map(Object::toString)
.collect(Collectors.toList());
}
private ResolvedChannelGroup resolveAnnotationData(
QueryContext ctxt,
ChannelGroup<?> channelGroup
) {
ResolvedChannelGroup.Builder resolvedChannelGroupBuilder =
ResolvedChannelGroup.builder(channelGroup);
resolvedChannelGroupBuilder.withRegionChannelGroups(
contextHasAnnotation(ctxt, Annotation.REGIONS) ?
resolveRegionChannelGroups(channelGroup) :
Optional.empty()
);
resolvedChannelGroupBuilder.withPlatformChannelGroup(
contextHasAnnotation(ctxt, Annotation.PLATFORM) ?
resolvePlatformChannelGroup(channelGroup) :
Optional.empty()
);
if (contextHasAnnotation(ctxt, Annotation.CHANNEL_GROUPS_SUMMARY) ||
contextHasAnnotation(ctxt, Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveChannelsWithChannelGroups(
ctxt.getApplication()
.getConfiguration(),
channelGroup,
contextHasAnnotation(
ctxt,
Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY
)
? this::isChannelGroupMembership
: channelGroupMembership -> true
)
);
} else if (contextHasAnnotation(ctxt, Annotation.ADVERTISED_CHANNELS) ||
contextHasAnnotation(ctxt, Annotation.CHANNELS)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveAdvertisedChannels(
channelGroup,
false
)
);
} else if (contextHasAnnotation(ctxt, Annotation.FUTURE_CHANNELS)) {
resolvedChannelGroupBuilder.withAdvertisedChannels(
resolveAdvertisedChannels(
channelGroup,
true
)
);
} else {
resolvedChannelGroupBuilder.withAdvertisedChannels(Optional.empty());
}
return resolvedChannelGroupBuilder.build();
}
private Optional<Iterable<ChannelGroup<?>>> resolveRegionChannelGroups(ChannelGroup<?> entity) {
if(!(entity instanceof Platform)) {
return Optional.empty();
}
Platform platform = (Platform) entity;
Iterable<Id> regionIds = platform.getRegions()
.stream()
.map(ChannelGroupRef::getId)
.collect(MoreCollectors.toImmutableSet());
return Optional.of(Promise.wrap(channelGroupResolver.resolveIds(regionIds))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES));
}
private Optional<ChannelGroup<?>> resolvePlatformChannelGroup(ChannelGroup<?> entity) {
if(!(entity instanceof Region)) {
return Optional.empty();
}
Id platformId = ((Region) entity).getPlatform().getId();
return Optional.ofNullable(Promise.wrap(channelGroupResolver.resolveIds(ImmutableSet.of(platformId)))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES)
.first().orNull()
);
}
private Optional<Iterable<ResolvedChannel>> resolveChannelsWithChannelGroups(
ApplicationConfiguration conf,
ChannelGroup<?> entity,
Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate
) {
Optional<Iterable<ResolvedChannel>> channels = resolveAdvertisedChannels(entity, false);
if (!channels.isPresent()) {
return Optional.empty();
}
return Optional.of(
StreamSupport.stream(channels.get().spliterator(), false)
.map(resolvedChannel -> ResolvedChannel.builder(resolvedChannel.getChannel())
.withChannelGroupSummaries(
resolveChannelGroupSummaries(
conf,
resolvedChannel.getChannel(),
whitelistedChannelGroupPredicate
)
)
.withResolvedEquivalents(
resolveChannelEquivalents(
resolvedChannel.getChannel()
)
)
.build()
)
.collect(Collectors.toList())
);
}
private List<ChannelGroupSummary> resolveChannelGroupSummaries(
ApplicationConfiguration conf,
Channel channel,
Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate
) {
Iterable<Id> channelGroupIds = channel.getChannelGroups().stream()
.filter(whitelistedChannelGroupPredicate::apply)
.map(ChannelGroupMembership::getChannelGroup)
.map(ResourceRef::getId)
.collect(MoreCollectors.toImmutableList());
return resolveChannelGroupSummaries(conf, channelGroupIds);
}
private List<ChannelGroupSummary> resolveChannelGroupSummaries(
ApplicationConfiguration conf,
Iterable<Id> channelGroupIds
) {
Iterable<ChannelGroup<?>> channelGroups =
Promise.wrap(channelGroupResolver.resolveIds(channelGroupIds))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
return StreamSupport.stream(channelGroups.spliterator(), false)
.filter(cg -> conf.isReadEnabled(cg.getSource()))
.map(ChannelGroup::toSummary)
.collect(MoreCollectors.toImmutableList());
}
private Optional<Iterable<ResolvedChannel>> resolveAdvertisedChannels(
ChannelGroup<?> entity,
boolean withFutureChannels
) {
final ImmutableMultimap.Builder<Id, ChannelGroupMembership> builder = ImmutableMultimap.builder();
Iterable<? extends ChannelGroupMembership> availableChannels = entity.getChannelsAvailable(LocalDate.now());
if (withFutureChannels) {
availableChannels = entity.getChannels();
}
List<Id> orderedIds = StreamSupport.stream(availableChannels.spliterator(), false)
//TODO fix channel appearing twice in ordering blowing this thing up
.map(cm -> cm.getChannel().getId())
.distinct()
.collect(Collectors.toList());
Ordering<Id> idOrdering = Ordering.explicit(orderedIds);
for (ChannelGroupMembership channelGroupMembership : availableChannels) {
builder.put(channelGroupMembership.getChannel().getId(), channelGroupMembership);
}
ImmutableMultimap<Id, ChannelGroupMembership> channelGroupMemberships = builder.build();
Iterable<Channel> resolvedChannels = Promise.wrap(
channelResolver.resolveIds(channelGroupMemberships.keySet()))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
Iterable<ResolvedChannel> sortedChannels =
StreamSupport.stream(resolvedChannels.spliterator(), false)
.sorted((o1, o2) -> idOrdering.compare(o1.getId(), o2.getId()))
.map(channel -> ResolvedChannel.builder(channel)
.withResolvedEquivalents(resolveChannelEquivalents(channel))
.build()
)
.collect(Collectors.toList());
return Optional.of(sortedChannels);
}
@Nullable
private Iterable<Channel> resolveChannelEquivalents(Channel channel) {
if (channel.getSameAs() == null || channel.getSameAs().isEmpty()) {
return null;
}
Iterable<Id> ids = Iterables.transform(channel.getSameAs(), ResourceRef::getId);
return Promise.wrap(channelResolver.resolveIds(ids))
.then(Resolved::getResources)
.get(1, TimeUnit.MINUTES);
}
private boolean contextHasAnnotation(QueryContext ctxt, Annotation annotation) {
return (!Strings.isNullOrEmpty(ctxt.getRequest().getParameter("annotations"))
&&
Splitter.on(',')
.splitToList(
ctxt.getRequest().getParameter("annotations")
).contains(annotation.toKey()));
}
private boolean isChannelGroupMembership(ChannelGroupMembership channelGroupMembership) {
return !(channelGroupMembership instanceof ChannelNumbering);
}
}
| Give future channels precedence (#600)
* Give future_channels annotation precedence in order to output both future channels and their channel groups
| atlas-api/src/main/java/org/atlasapi/query/v4/channelgroup/ChannelGroupQueryExecutor.java | Give future channels precedence (#600) | <ide><path>tlas-api/src/main/java/org/atlasapi/query/v4/channelgroup/ChannelGroupQueryExecutor.java
<ide> Optional.empty()
<ide> );
<ide>
<del> if (contextHasAnnotation(ctxt, Annotation.CHANNEL_GROUPS_SUMMARY) ||
<add> if (contextHasAnnotation(ctxt, Annotation.FUTURE_CHANNELS)) {
<add> resolvedChannelGroupBuilder.withAdvertisedChannels(
<add> resolveChannelsWithChannelGroups(
<add> ctxt.getApplication()
<add> .getConfiguration(),
<add> channelGroup,
<add> contextHasAnnotation(
<add> ctxt,
<add> Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY
<add> )
<add> ? this::isChannelGroupMembership
<add> : channelGroupMembership -> true,
<add> true
<add> )
<add> );
<add> } else if (contextHasAnnotation(ctxt, Annotation.CHANNEL_GROUPS_SUMMARY) ||
<ide> contextHasAnnotation(ctxt, Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY)) {
<ide> resolvedChannelGroupBuilder.withAdvertisedChannels(
<ide> resolveChannelsWithChannelGroups(
<ide> Annotation.GENERIC_CHANNEL_GROUPS_SUMMARY
<ide> )
<ide> ? this::isChannelGroupMembership
<del> : channelGroupMembership -> true
<add> : channelGroupMembership -> true,
<add> false
<ide> )
<ide> );
<ide> } else if (contextHasAnnotation(ctxt, Annotation.ADVERTISED_CHANNELS) ||
<ide> false
<ide> )
<ide> );
<del> } else if (contextHasAnnotation(ctxt, Annotation.FUTURE_CHANNELS)) {
<del> resolvedChannelGroupBuilder.withAdvertisedChannels(
<del> resolveAdvertisedChannels(
<del> channelGroup,
<del> true
<del> )
<del> );
<ide> } else {
<ide> resolvedChannelGroupBuilder.withAdvertisedChannels(Optional.empty());
<ide> }
<ide> private Optional<Iterable<ResolvedChannel>> resolveChannelsWithChannelGroups(
<ide> ApplicationConfiguration conf,
<ide> ChannelGroup<?> entity,
<del> Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate
<add> Function<ChannelGroupMembership, Boolean> whitelistedChannelGroupPredicate,
<add> boolean withFutureChannels
<ide> ) {
<ide>
<del> Optional<Iterable<ResolvedChannel>> channels = resolveAdvertisedChannels(entity, false);
<add> Optional<Iterable<ResolvedChannel>> channels = resolveAdvertisedChannels(
<add> entity,
<add> withFutureChannels
<add> );
<ide> if (!channels.isPresent()) {
<ide> return Optional.empty();
<ide> } |
|
Java | epl-1.0 | da23ce7d1a3f55f6b9506fda2366575d51b72daa | 0 | gnodet/wikitext | /*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.core.AbstractContextListener;
import org.eclipse.mylyn.context.core.AbstractContextStructureBridge;
import org.eclipse.mylyn.context.core.ContextChangeEvent;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.core.IInteractionContext;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.context.ui.AbstractContextUiBridge;
import org.eclipse.mylyn.context.ui.ContextUi;
import org.eclipse.mylyn.context.ui.IContextAwareEditor;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskMigrator;
import org.eclipse.mylyn.monitor.ui.MonitorUi;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.internal.EditorManager;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchPage;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
/**
* @author Mik Kersten
* @author Shawn Minto
*/
public class ContextEditorManager extends AbstractContextListener {
private static final String PREFS_PREFIX = "editors.task."; //$NON-NLS-1$
private static final String KEY_CONTEXT_EDITORS = "ContextOpenEditors"; //$NON-NLS-1$
private static final String KEY_MONITORED_WINDOW_OPEN_EDITORS = "MonitoredWindowOpenEditors"; //$NON-NLS-1$
private static final String ATTRIBUTE_CLASS = "class"; //$NON-NLS-1$
private static final String ATTRIBUTE_NUMER = "number"; //$NON-NLS-1$
private static final String ATTRIBUTE_IS_LAUNCHING = "isLaunching"; //$NON-NLS-1$
private static final String ATTRIBUTE_IS_ACTIVE = "isActive"; //$NON-NLS-1$
private boolean previousCloseEditorsSetting = Workbench.getInstance().getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
private final IPreferenceStore preferenceStore;
public ContextEditorManager() {
preferenceStore = new ScopedPreferenceStore(new InstanceScope(), "org.eclipse.mylyn.resources.ui"); //$NON-NLS-1$
}
@Override
public void contextChanged(ContextChangeEvent event) {
switch (event.getEventKind()) {
case ACTIVATED:
openEditorsFromMemento(event.getContext());
break;
case DEACTIVATED:
closeEditorsAndSaveMemento(event.getContext());
break;
case INTEREST_CHANGED:
for (IInteractionElement element : event.getElements()) {
closeEditor(element, false);
}
break;
case ELEMENTS_DELETED:
for (IInteractionElement element : event.getElements()) {
closeEditor(element, true);
}
break;
case CLEARED:
// use the handle since the context is null when it is cleared
// bug 255588
clearEditorMemento(event.getContextHandle(), event.isActiveContext());
break;
}
}
public void openEditorsFromMemento(IInteractionContext context) {
if (!Workbench.getInstance().isStarting()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS) && !TaskMigrator.isActive()) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCore.getContextManager().isContextCapturePaused();
try {
if (!wasPaused) {
ContextCore.getContextManager().setContextCapturePaused(true);
}
String mementoString = null;
// TODO change where memento is stored
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
try {
mementoString = readEditorMemento(context);
if (mementoString != null && !mementoString.trim().equals("")) { //$NON-NLS-1$
IMemento memento = XMLMemento.createReadRoot(new StringReader(mementoString));
IMemento[] children = memento.getChildren(KEY_MONITORED_WINDOW_OPEN_EDITORS);
if (children.length > 0) {
// This code supports restore from multiple windows
for (IMemento child : children) {
WorkbenchPage page = getWorkbenchPageForMemento(child, activeWindow);
if (child != null && page != null) {
restoreEditors(page, child, page.getWorkbenchWindow() == activeWindow);
}
}
} else {
// This code is for supporting the old editor management - only the active window
WorkbenchPage page = (WorkbenchPage) activeWindow.getActivePage();
if (memento != null) {
restoreEditors(page, memento, true);
}
}
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Could not restore all editors, memento: \"" + mementoString + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
activeWindow.setActivePage(activeWindow.getActivePage());
IInteractionElement activeNode = context.getActiveNode();
if (activeNode != null) {
ContextUi.getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Failed to open editors on activation", e)); //$NON-NLS-1$
} finally {
ContextCore.getContextManager().setContextCapturePaused(false);
}
}
}
private WorkbenchPage getWorkbenchPageForMemento(IMemento memento, IWorkbenchWindow activeWindow) {
String windowToRestoreClassName = memento.getString(ATTRIBUTE_CLASS);
if (windowToRestoreClassName == null) {
windowToRestoreClassName = ""; //$NON-NLS-1$
}
Integer windowToRestorenumber = memento.getInteger(ATTRIBUTE_NUMER);
if (windowToRestorenumber == null) {
windowToRestorenumber = 0;
}
// try to match the open windows to the one that we want to restore
Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();
for (IWorkbenchWindow window : monitoredWindows) {
int windowNumber = 0;
if (window instanceof WorkbenchWindow) {
windowNumber = ((WorkbenchWindow) window).getNumber();
}
if (window.getClass().getCanonicalName().equals(windowToRestoreClassName)
&& windowNumber == windowToRestorenumber) {
return (WorkbenchPage) window.getActivePage();
}
}
// we don't have a good match here, try to make an educated guess
// TODO e3.4 replace by memento.getBoolean()
Boolean isActive = Boolean.valueOf(memento.getString(ATTRIBUTE_IS_ACTIVE));
if (isActive == null) {
isActive = false;
}
// both of these defaulting to true should ensure that all editors are opened even if their previous editor is not around
boolean shouldRestoreUnknownWindowToActive = true; // TODO could add a preference here
boolean shouldRestoreActiveWindowToActive = true; // TODO could add a preference here
if (isActive && shouldRestoreActiveWindowToActive) {
// if the window that we are trying to restore was the active window, restore it to the active window
return (WorkbenchPage) activeWindow.getActivePage();
}
if (shouldRestoreUnknownWindowToActive) {
// we can't find a good window, so restore it to the active one
return (WorkbenchPage) activeWindow.getActivePage();
}
if (shouldRestoreActiveWindowToActive && shouldRestoreUnknownWindowToActive) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Unable to find window to restore memento to.", new Exception())); //$NON-NLS-1$
}
// we dont have a window that will work, so don't restore the editors
// we shouldn't get here if both *WindowToActive booleans are true
return null;
}
private String readEditorMemento(IInteractionContext context) {
return preferenceStore.getString(PREFS_PREFIX + context.getHandleIdentifier());
}
public void closeEditorsAndSaveMemento(IInteractionContext context) {
if (!PlatformUI.getWorkbench().isClosing()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS) && !TaskMigrator.isActive()) {
closeAllButActiveTaskEditor(context.getHandleIdentifier());
XMLMemento rootMemento = XMLMemento.createWriteRoot(KEY_CONTEXT_EDITORS);
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchWindow launchingWindow = MonitorUi.getLaunchingWorkbenchWindow();
Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();
for (IWorkbenchWindow window : monitoredWindows) {
IMemento memento = rootMemento.createChild(KEY_MONITORED_WINDOW_OPEN_EDITORS);
memento.putString(ATTRIBUTE_CLASS, window.getClass().getCanonicalName());
int number = 0;
if (window instanceof WorkbenchWindow) {
number = ((WorkbenchWindow) window).getNumber();
}
memento.putInteger(ATTRIBUTE_NUMER, number);
// TODO e3.4 replace by memento.putBoolean()
memento.putString(ATTRIBUTE_IS_LAUNCHING, (window == launchingWindow) ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
memento.putString(ATTRIBUTE_IS_ACTIVE, (window == activeWindow) ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
((WorkbenchPage) window.getActivePage()).getEditorManager().saveState(memento);
}
// TODO: avoid storing with preferences due to bloat?
StringWriter writer = new StringWriter();
try {
rootMemento.save(writer);
writeEditorMemento(context.getHandleIdentifier(), writer.getBuffer().toString());
} catch (IOException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not store editor state", //$NON-NLS-1$
e));
}
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN,
previousCloseEditorsSetting);
closeAllEditors();
}
}
public void writeEditorMemento(String contextHandle, String memento) {
preferenceStore.setValue(PREFS_PREFIX + contextHandle, memento);
}
public void clearEditorMemento(String contextHandle, boolean closeEditors) {
if (closeEditors) {
closeAllButActiveTaskEditor(contextHandle);
}
XMLMemento memento = XMLMemento.createWriteRoot(KEY_CONTEXT_EDITORS);
// TODO: avoid storing with preferences due to bloat?
StringWriter writer = new StringWriter();
try {
memento.save(writer);
writeEditorMemento(contextHandle, writer.getBuffer().toString());
} catch (IOException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not store editor state", e)); //$NON-NLS-1$
}
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN,
previousCloseEditorsSetting);
if (closeEditors) {
closeAllEditors();
}
}
/**
* HACK: will fail to restore different parts with same name
*/
@SuppressWarnings("unchecked")
private void restoreEditors(WorkbenchPage page, IMemento memento, boolean isActiveWindow) {
EditorManager editorManager = page.getEditorManager();
final ArrayList visibleEditors = new ArrayList(5);
final IEditorReference activeEditor[] = new IEditorReference[1];
final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$
try {
IMemento[] editorMementos = memento.getChildren(IWorkbenchConstants.TAG_EDITOR);
Set<IMemento> editorMementoSet = new HashSet<IMemento>();
editorMementoSet.addAll(Arrays.asList(editorMementos));
// HACK: same parts could have different editors
Set<String> restoredPartNames = new HashSet<String>();
List<IEditorReference> alreadyVisibleEditors = Arrays.asList(editorManager.getEditors());
for (IEditorReference editorReference : alreadyVisibleEditors) {
restoredPartNames.add(editorReference.getPartName());
}
for (IMemento editorMemento : editorMementoSet) {
String partName = editorMemento.getString(IWorkbenchConstants.TAG_PART_NAME);
if (!restoredPartNames.contains(partName)) {
editorManager.restoreEditorState(editorMemento, visibleEditors, activeEditor, result);
} else {
restoredPartNames.add(partName);
}
}
for (int i = 0; i < visibleEditors.size(); i++) {
editorManager.setVisibleEditor((IEditorReference) visibleEditors.get(i), false);
}
if (activeEditor[0] != null && isActiveWindow) {
IWorkbenchPart editor = activeEditor[0].getPart(true);
if (editor != null) {
page.activate(editor);
}
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not restore editors", e)); //$NON-NLS-1$
}
}
public void closeAllButActiveTaskEditor(String taskHandle) {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (IEditorReference reference : references) {
if (canClose(reference)) {
try {
IEditorInput input = reference.getEditorInput();
if (input instanceof TaskEditorInput) {
ITask task = ((TaskEditorInput) input).getTask();
if (task != null && task.getHandleIdentifier().equals(taskHandle)) {
// do not close
} else {
toClose.add(reference);
}
}
} catch (PartInitException e) {
// ignore
}
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
}
}
public void closeAllEditors() {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (IEditorReference reference : references) {
if (canClose(reference)) {
toClose.add(reference);
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
}
}
private boolean canClose(final IEditorReference editorReference) {
final IEditorPart editor = editorReference.getEditor(false);
if (editor != null) {
final boolean[] result = new boolean[1];
result[0] = true;
SafeRunnable.run(new ISafeRunnable() {
public void run() throws Exception {
if (editor instanceof IContextAwareEditor) {
result[0] = ((IContextAwareEditor) editor).canClose();
} else {
IContextAwareEditor contextAware = (IContextAwareEditor) editor.getAdapter(IContextAwareEditor.class);
if (contextAware != null) {
result[0] = contextAware.canClose();
}
}
}
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Failed to verify editor status", e)); //$NON-NLS-1$
}
});
return result[0];
}
return true;
}
private void closeEditor(IInteractionElement element, boolean force) {
if (ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS)) {
if (force || !element.getInterest().isInteresting()) {
AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
AbstractContextUiBridge uiBridge = ContextUi.getUiBridge(element.getContentType());
uiBridge.close(element);
}
}
}
}
}
| org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/ContextEditorManager.java | /*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.core.AbstractContextListener;
import org.eclipse.mylyn.context.core.AbstractContextStructureBridge;
import org.eclipse.mylyn.context.core.ContextChangeEvent;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.core.IInteractionContext;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.context.ui.AbstractContextUiBridge;
import org.eclipse.mylyn.context.ui.ContextUi;
import org.eclipse.mylyn.context.ui.IContextAwareEditor;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskMigrator;
import org.eclipse.mylyn.monitor.ui.MonitorUi;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.internal.EditorManager;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchPage;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
/**
* @author Mik Kersten
* @author Shawn Minto
*/
public class ContextEditorManager extends AbstractContextListener {
private static final String PREFS_PREFIX = "editors.task."; //$NON-NLS-1$
private static final String KEY_CONTEXT_EDITORS = "ContextOpenEditors"; //$NON-NLS-1$
private static final String KEY_MONITORED_WINDOW_OPEN_EDITORS = "MonitoredWindowOpenEditors"; //$NON-NLS-1$
private static final String ATTRIBUTE_CLASS = "class"; //$NON-NLS-1$
private static final String ATTRIBUTE_NUMER = "number"; //$NON-NLS-1$
private static final String ATTRIBUTE_IS_LAUNCHING = "isLaunching"; //$NON-NLS-1$
private static final String ATTRIBUTE_IS_ACTIVE = "isActive"; //$NON-NLS-1$
private boolean previousCloseEditorsSetting = Workbench.getInstance().getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
private final IPreferenceStore preferenceStore;
public ContextEditorManager() {
preferenceStore = new ScopedPreferenceStore(new InstanceScope(), "org.eclipse.mylyn.resources.ui"); //$NON-NLS-1$
}
@Override
public void contextChanged(ContextChangeEvent event) {
switch (event.getEventKind()) {
case ACTIVATED:
openEditorsFromMemento(event.getContext());
break;
case DEACTIVATED:
closeEditorsAndSaveMemento(event.getContext());
break;
case INTEREST_CHANGED:
for (IInteractionElement element : event.getElements()) {
closeEditor(element, false);
}
break;
case ELEMENTS_DELETED:
for (IInteractionElement element : event.getElements()) {
closeEditor(element, true);
}
break;
case CLEARED:
// use the handle since the context is null when it is cleared
// bug 255588
clearEditorMemento(event.getContextHandle(), event.isActiveContext());
break;
}
}
public void openEditorsFromMemento(IInteractionContext context) {
if (!Workbench.getInstance().isStarting()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS) && !TaskMigrator.isActive()) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCore.getContextManager().isContextCapturePaused();
try {
if (!wasPaused) {
ContextCore.getContextManager().setContextCapturePaused(true);
}
String mementoString = null;
// TODO change where memento is stored
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
try {
mementoString = readEditorMemento(context);
if (mementoString != null && !mementoString.trim().equals("")) { //$NON-NLS-1$
IMemento memento = XMLMemento.createReadRoot(new StringReader(mementoString));
IMemento[] children = memento.getChildren(KEY_MONITORED_WINDOW_OPEN_EDITORS);
if (children.length > 0) {
// This code supports restore from multiple windows
for (IMemento child : children) {
WorkbenchPage page = getWorkbenchPageForMemento(child, activeWindow);
if (child != null && page != null) {
restoreEditors(page, child, page.getWorkbenchWindow() == activeWindow);
}
}
} else {
// This code is for supporting the old editor management - only the active window
WorkbenchPage page = (WorkbenchPage) activeWindow.getActivePage();
if (memento != null) {
restoreEditors(page, memento, true);
}
}
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Could not restore all editors, memento: \"" + mementoString + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
activeWindow.setActivePage(activeWindow.getActivePage());
IInteractionElement activeNode = context.getActiveNode();
if (activeNode != null) {
ContextUi.getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Failed to open editors on activation", e)); //$NON-NLS-1$
} finally {
ContextCore.getContextManager().setContextCapturePaused(false);
}
}
}
private WorkbenchPage getWorkbenchPageForMemento(IMemento memento, IWorkbenchWindow activeWindow) {
String windowToRestoreClassName = memento.getString(ATTRIBUTE_CLASS);
if (windowToRestoreClassName == null) {
windowToRestoreClassName = ""; //$NON-NLS-1$
}
Integer windowToRestorenumber = memento.getInteger(ATTRIBUTE_NUMER);
if (windowToRestorenumber == null) {
windowToRestorenumber = 0;
}
// try to match the open windows to the one that we want to restore
Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();
for (IWorkbenchWindow window : monitoredWindows) {
int windowNumber = 0;
if (window instanceof WorkbenchWindow) {
windowNumber = ((WorkbenchWindow) window).getNumber();
}
if (window.getClass().getCanonicalName().equals(windowToRestoreClassName)
&& windowNumber == windowToRestorenumber) {
return (WorkbenchPage) window.getActivePage();
}
}
// we don't have a good match here, try to make an educated guess
// TODO e3.4 replace by memento.getBoolean()
Boolean isActive = Boolean.valueOf(memento.getString(ATTRIBUTE_IS_ACTIVE));
if (isActive == null) {
isActive = false;
}
// both of these defaulting to true should ensure that all editors are opened even if their previous editor is not around
boolean shouldRestoreUnknownWindowToActive = true; // TODO could add a preference here
boolean shouldRestoreActiveWindowToActive = true; // TODO could add a preference here
if (isActive && shouldRestoreActiveWindowToActive) {
// if the window that we are trying to restore was the active window, restore it to the active window
return (WorkbenchPage) activeWindow.getActivePage();
}
if (shouldRestoreUnknownWindowToActive) {
// we can't find a good window, so restore it to the active one
return (WorkbenchPage) activeWindow.getActivePage();
}
if (shouldRestoreActiveWindowToActive && shouldRestoreUnknownWindowToActive) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
"Unable to find window to restore memento to.", new Exception())); //$NON-NLS-1$
}
// we dont have a window that will work, so don't restore the editors
// we shouldn't get here if both *WindowToActive booleans are true
return null;
}
private String readEditorMemento(IInteractionContext context) {
return preferenceStore.getString(PREFS_PREFIX + context.getHandleIdentifier());
}
public void closeEditorsAndSaveMemento(IInteractionContext context) {
if (!PlatformUI.getWorkbench().isClosing()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS) && !TaskMigrator.isActive()) {
closeAllButActiveTaskEditor(context.getHandleIdentifier());
XMLMemento rootMemento = XMLMemento.createWriteRoot(KEY_CONTEXT_EDITORS);
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchWindow launchingWindow = MonitorUi.getLaunchingWorkbenchWindow();
Set<IWorkbenchWindow> monitoredWindows = MonitorUi.getMonitoredWindows();
for (IWorkbenchWindow window : monitoredWindows) {
IMemento memento = rootMemento.createChild(KEY_MONITORED_WINDOW_OPEN_EDITORS);
memento.putString(ATTRIBUTE_CLASS, window.getClass().getCanonicalName());
int number = 0;
if (window instanceof WorkbenchWindow) {
number = ((WorkbenchWindow) window).getNumber();
}
memento.putInteger(ATTRIBUTE_NUMER, number);
// TODO e3.4 replace by memento.putBoolean()
memento.putString(ATTRIBUTE_IS_LAUNCHING, (window == launchingWindow) ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
memento.putString(ATTRIBUTE_IS_ACTIVE, (window == activeWindow) ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
((WorkbenchPage) window.getActivePage()).getEditorManager().saveState(memento);
}
// TODO: avoid storing with preferences due to bloat?
StringWriter writer = new StringWriter();
try {
rootMemento.save(writer);
writeEditorMemento(context.getHandleIdentifier(), writer.getBuffer().toString());
} catch (IOException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not store editor state", //$NON-NLS-1$
e));
}
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN,
previousCloseEditorsSetting);
closeAllEditors();
}
}
public void writeEditorMemento(String contextHandle, String memento) {
preferenceStore.setValue(PREFS_PREFIX + contextHandle, memento);
}
public void clearEditorMemento(String contextHandle, boolean closeEditors) {
if (closeEditors) {
closeAllButActiveTaskEditor(contextHandle);
}
XMLMemento memento = XMLMemento.createWriteRoot(KEY_CONTEXT_EDITORS);
// TODO: avoid storing with preferences due to bloat?
StringWriter writer = new StringWriter();
try {
memento.save(writer);
writeEditorMemento(contextHandle, writer.getBuffer().toString());
} catch (IOException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not store editor state", e)); //$NON-NLS-1$
}
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN,
previousCloseEditorsSetting);
if (closeEditors) {
closeAllEditors();
}
}
/**
* HACK: will fail to restore different parts with same name
*/
@SuppressWarnings("unchecked")
private void restoreEditors(WorkbenchPage page, IMemento memento, boolean isActiveWindow) {
EditorManager editorManager = page.getEditorManager();
final ArrayList visibleEditors = new ArrayList(5);
final IEditorReference activeEditor[] = new IEditorReference[1];
final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$
try {
IMemento[] editorMementos = memento.getChildren(IWorkbenchConstants.TAG_EDITOR);
Set<IMemento> editorMementoSet = new HashSet<IMemento>();
editorMementoSet.addAll(Arrays.asList(editorMementos));
// HACK: same parts could have different editors
Set<String> restoredPartNames = new HashSet<String>();
List<IEditorReference> alreadyVisibleEditors = Arrays.asList(editorManager.getEditors());
for (IEditorReference editorReference : alreadyVisibleEditors) {
restoredPartNames.add(editorReference.getPartName());
}
for (IMemento editorMemento : editorMementoSet) {
String partName = editorMemento.getString(IWorkbenchConstants.TAG_PART_NAME);
if (!restoredPartNames.contains(partName)) {
editorManager.restoreEditorState(editorMemento, visibleEditors, activeEditor, result);
} else {
restoredPartNames.add(partName);
}
}
for (int i = 0; i < visibleEditors.size(); i++) {
editorManager.setVisibleEditor((IEditorReference) visibleEditors.get(i), false);
}
if (activeEditor[0] != null && isActiveWindow) {
IWorkbenchPart editor = activeEditor[0].getPart(true);
if (editor != null) {
page.activate(editor);
}
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not restore editors", e)); //$NON-NLS-1$
}
}
public void closeAllButActiveTaskEditor(String taskHandle) {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (IEditorReference reference : references) {
if (canClose(reference)) {
try {
IEditorInput input = reference.getEditorInput();
if (input instanceof TaskEditorInput) {
ITask task = ((TaskEditorInput) input).getTask();
if (task != null && task.getHandleIdentifier().equals(taskHandle)) {
// do not close
} else {
toClose.add(reference);
}
}
} catch (PartInitException e) {
// ignore
}
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
}
}
public void closeAllEditors() {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (IEditorReference reference : references) {
if (canClose(reference)) {
toClose.add(reference);
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, "Could not auto close editor", t)); //$NON-NLS-1$
}
}
private boolean canClose(IEditorReference editorReference) {
IEditorPart editor = editorReference.getEditor(false);
if (editor instanceof IContextAwareEditor) {
return ((IContextAwareEditor) editor).canClose();
}
IContextAwareEditor contextAware = (IContextAwareEditor) editor.getAdapter(IContextAwareEditor.class);
if (contextAware != null) {
return contextAware.canClose();
}
return true;
}
private void closeEditor(IInteractionElement element, boolean force) {
if (ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
IContextUiPreferenceContstants.AUTO_MANAGE_EDITORS)) {
if (force || !element.getInterest().isInteresting()) {
AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
AbstractContextUiBridge uiBridge = ContextUi.getUiBridge(element.getContentType());
uiBridge.close(element);
}
}
}
}
}
| NEW - bug 275774: do not close editor of activated when switching tasks
https://bugs.eclipse.org/bugs/show_bug.cgi?id=275774
| org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/ContextEditorManager.java | NEW - bug 275774: do not close editor of activated when switching tasks https://bugs.eclipse.org/bugs/show_bug.cgi?id=275774 | <ide><path>rg.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/ContextEditorManager.java
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<add>import org.eclipse.core.runtime.ISafeRunnable;
<ide> import org.eclipse.core.runtime.IStatus;
<ide> import org.eclipse.core.runtime.MultiStatus;
<ide> import org.eclipse.core.runtime.Status;
<ide> import org.eclipse.core.runtime.preferences.InstanceScope;
<ide> import org.eclipse.jface.preference.IPreferenceStore;
<add>import org.eclipse.jface.util.SafeRunnable;
<ide> import org.eclipse.mylyn.commons.core.StatusHandler;
<ide> import org.eclipse.mylyn.context.core.AbstractContextListener;
<ide> import org.eclipse.mylyn.context.core.AbstractContextStructureBridge;
<ide> }
<ide> }
<ide>
<del> private boolean canClose(IEditorReference editorReference) {
<del> IEditorPart editor = editorReference.getEditor(false);
<del> if (editor instanceof IContextAwareEditor) {
<del> return ((IContextAwareEditor) editor).canClose();
<del> }
<del> IContextAwareEditor contextAware = (IContextAwareEditor) editor.getAdapter(IContextAwareEditor.class);
<del> if (contextAware != null) {
<del> return contextAware.canClose();
<add> private boolean canClose(final IEditorReference editorReference) {
<add> final IEditorPart editor = editorReference.getEditor(false);
<add> if (editor != null) {
<add> final boolean[] result = new boolean[1];
<add> result[0] = true;
<add> SafeRunnable.run(new ISafeRunnable() {
<add> public void run() throws Exception {
<add> if (editor instanceof IContextAwareEditor) {
<add> result[0] = ((IContextAwareEditor) editor).canClose();
<add> } else {
<add> IContextAwareEditor contextAware = (IContextAwareEditor) editor.getAdapter(IContextAwareEditor.class);
<add> if (contextAware != null) {
<add> result[0] = contextAware.canClose();
<add> }
<add> }
<add> }
<add>
<add> public void handleException(Throwable e) {
<add> StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN,
<add> "Failed to verify editor status", e)); //$NON-NLS-1$
<add> }
<add> });
<add> return result[0];
<ide> }
<ide> return true;
<ide> } |
|
Java | mpl-2.0 | c99b0b9bf3bf56d74a369122ccb0879d7ee03ddb | 0 | utybo/BST,utybo/BST,utybo/BST | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
package utybo.branchingstorytree.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import com.google.gson.Gson;
import net.miginfocom.swing.MigLayout;
import utybo.branchingstorytree.api.BSTException;
import utybo.branchingstorytree.api.script.ActionDescriptor;
import utybo.branchingstorytree.api.story.BranchingStory;
import utybo.branchingstorytree.api.story.LogicalNode;
import utybo.branchingstorytree.api.story.NodeOption;
import utybo.branchingstorytree.api.story.SaveState;
import utybo.branchingstorytree.api.story.StoryNode;
import utybo.branchingstorytree.api.story.TextNode;
import utybo.branchingstorytree.swing.JScrollablePanel.ScrollableSizeHint;
@SuppressWarnings("serial")
public class StoryPanel extends JPanel
{
/**
* The story represented by this StoryPanel. This variable will change if
* the file is reload.
*/
protected BranchingStory story;
/**
* The panel for use with the UIB Module
*/
protected JPanel uibPanel;
/**
* The node currently on screen
*/
private StoryNode currentNode;
/**
* The {@link TabClient} linked to this panel
*/
private TabClient client;
/**
* The latest save state made - this is used with the save state buttons
*/
private SaveState latestSaveState;
/**
* The file this story is from
*/
private File bstFile;
/**
* The OpenBST window
*/
protected OpenBST parentWindow;
/**
* The node panel the text is displayed in
*/
private final NodePanel nodePanel;
/**
* The label displaying the current node ID.
*/
private JLabel nodeIdLabel;
/**
* The list of node options for the current node
*/
private NodeOption[] options;
/**
* An array of the Option Buttons available in the grid
*/
private JButton[] optionsButton;
/**
* The panel in which option buttons are placed
*/
private final JPanel optionPanel = new JPanel();
/**
* The regular foreground for option buttons when the "color" tag is not
* applied
*/
private Color normalButtonFg;
// --- Toolbar buttons ---
private JButton restoreSaveStateButton, exportSaveStateButton;
protected JToggleButton variableWatcherButton;
protected VariableWatchDialog variableWatcher;
private JButton backgroundButton;
/**
* Initialize the story panel
*
* @param story
* the story to create
* @param parentWindow
* the OpenBST instance we are creating this story from
* @param f
* the file the story is from
* @param client
* the client that will be linked to this story
*/
public StoryPanel(BranchingStory story, OpenBST parentWindow, File f, TabClient client)
{
log("=> Initial setup");
bstFile = f;
client.setStoryPanel(this);
this.story = story;
this.parentWindow = parentWindow;
this.client = client;
log("=> Creating visual elements");
setLayout(new MigLayout("hidemode 3", "[grow]", ""));
createToolbar();
if(story.hasTag("uib_layout"))
{
uibPanel = new JPanel();
add(uibPanel, "growx, wrap");
uibPanel.setVisible(false);
}
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBackground(Color.WHITE);
add(scrollPane, "grow, pushy, wrap");
nodePanel = new NodePanel(client.getIMGHandler());
nodePanel.setScrollableWidth(ScrollableSizeHint.FIT);
nodePanel.setScrollableHeight(ScrollableSizeHint.STRETCH);
scrollPane.setViewportView(nodePanel);
add(optionPanel, "growx");
setupStory();
}
/**
* Create the toolbar, enforcing the supertools tag
*/
private void createToolbar()
{
int toolbarLevel = readToolbarLevel();
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
if(toolbarLevel > 0)
{
toolBar.add(new AbstractAction(Lang.get("story.createss"), new ImageIcon(OpenBST.saveAsImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
latestSaveState = new SaveState(currentNode.getId(), story.getRegistry());
restoreSaveStateButton.setEnabled(true);
if(exportSaveStateButton != null)
exportSaveStateButton.setEnabled(true);
}
});
restoreSaveStateButton = toolBar.add(new AbstractAction(Lang.get("story.restoress"), new ImageIcon(OpenBST.undoImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.restoress.confirm"), Lang.get("story.restoress"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.undoBigImage)) == JOptionPane.YES_OPTION)
{
restoreSaveState(latestSaveState);
}
}
});
restoreSaveStateButton.setEnabled(false);
if(toolbarLevel > 1)
{
exportSaveStateButton = toolBar.add(new AbstractAction(Lang.get("story.exportss"), new ImageIcon(OpenBST.exportImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
final FileDialog jfc = new FileDialog(parentWindow, Lang.get("story.sslocation"), FileDialog.SAVE);
jfc.setLocationRelativeTo(parentWindow);
jfc.setIconImage(OpenBST.exportImage);
jfc.setVisible(true);
if(jfc.getFile() != null)
{
File file = new File(jfc.getFile().endsWith(".bss") ? jfc.getDirectory() + jfc.getFile() : jfc.getDirectory() + jfc.getFile() + ".bss");
Gson gson = new Gson();
file.delete();
try
{
file.createNewFile();
FileWriter writer = new FileWriter(file);
gson.toJson(new SaveState(currentNode.getId(), story.getRegistry()), writer);
writer.flush();
writer.close();
}
catch(IOException e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(parentWindow, Lang.get("story.exportss.error").replace("$m", e1.getMessage()).replace("$e", e1.getClass().getSimpleName()));
}
}
}
});
exportSaveStateButton.setEnabled(false);
toolBar.add(new AbstractAction(Lang.get("story.importss"), new ImageIcon(OpenBST.importImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
final FileDialog jfc = new FileDialog(parentWindow, Lang.get("story.sslocation"), FileDialog.LOAD);
jfc.setLocationRelativeTo(parentWindow);
jfc.setIconImage(OpenBST.importImage);
jfc.setVisible(true);
if(jfc.getFile() != null)
{
File file = new File(jfc.getDirectory() + jfc.getFile());
Gson gson = new Gson();
try
{
FileReader reader = new FileReader(file);
latestSaveState = gson.fromJson(reader, SaveState.class);
reader.close();
restoreSaveState(latestSaveState);
}
catch(IOException e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(parentWindow, Lang.get("story.exportss.error").replace("$m", e1.getMessage()).replace("$e", e1.getClass().getSimpleName()));
}
}
}
});
if(toolbarLevel > 2)
{
toolBar.addSeparator();
toolBar.add(new AbstractAction(Lang.get("story.reset"), new ImageIcon(OpenBST.returnImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.reset.confirm"), Lang.get("story.reset"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.returnBigImage)) == JOptionPane.YES_OPTION)
{
reset();
}
}
});
toolBar.add(new AbstractAction(Lang.get("story.sreload"), new ImageIcon(OpenBST.refreshImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.sreload.confirm"), Lang.get("story.sreload.confirm.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.refreshBigImage)) == JOptionPane.YES_OPTION)
{
SaveState ss = new SaveState(currentNode.getId(), story.getRegistry());
reset();
reload();
reset();
restoreSaveState(ss);
}
}
});
toolBar.add(new AbstractAction(Lang.get("story.hreload"), new ImageIcon(OpenBST.synchronizeImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.hreload.confirm"), Lang.get("story.hreload.confirm.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.synchronizeBigImage)) == JOptionPane.YES_OPTION)
{
reset();
reload();
reset();
}
}
});
if(toolbarLevel > 3)
{
toolBar.addSeparator();
toolBar.add(new AbstractAction(Lang.get("story.jumptonode"), new ImageIcon(OpenBST.jumpImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
SpinnerNumberModel model = new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1);
JSpinner spinner = new JSpinner(model);
int i = JOptionPane.showOptionDialog(parentWindow, spinner, Lang.get("story.jumptonode"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(OpenBST.jumpBigImage), null, null);
if(i == JOptionPane.OK_OPTION)
{
showNode(story.getNode((Integer)spinner.getModel().getValue()));
}
}
});
variableWatcherButton = new JToggleButton("", new ImageIcon(OpenBST.addonSearchImage));
variableWatcherButton.addItemListener(e ->
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
variableWatcher = new VariableWatchDialog(StoryPanel.this);
variableWatcher.setVisible(true);
}
else if(e.getStateChange() == ItemEvent.DESELECTED)
{
variableWatchClosing();
}
});
variableWatcherButton.setToolTipText(Lang.get("story.variablewatcher"));
toolBar.add(variableWatcherButton);
toolBar.addSeparator();
nodeIdLabel = new JLabel(Lang.get("wait"));
nodeIdLabel.setVerticalAlignment(SwingConstants.CENTER);
nodeIdLabel.setEnabled(false);
toolBar.add(nodeIdLabel);
}
}
}
toolBar.addSeparator();
JLabel hintLabel = new JLabel(Lang.get("story.tip"));
hintLabel.setEnabled(false);
toolBar.add(hintLabel);
}
toolBar.add(Box.createHorizontalGlue());
toolBar.addSeparator();
backgroundButton = toolBar.add(new AbstractAction(Lang.get("story.seebackground"), new ImageIcon(OpenBST.pictureImage))
{
private Dimension previousBounds;
private Image previousImage;
private int x, y;
@Override
public void actionPerformed(ActionEvent e)
{
JDialog dialog = new JDialog(parentWindow);
dialog.add(new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Image image;
int width = getWidth() - 1;
int height = getHeight() - 1;
if(previousBounds != null && previousImage != null && getParent().getSize().equals(previousBounds))
{
image = previousImage;
}
else
{
BufferedImage bi = client.getIMGHandler().getCurrentBackground();
double scaleFactor = 1d;
if(bi.getWidth() > bi.getHeight())
{
scaleFactor = getScaleFactorToFit(new Dimension(bi.getWidth(), bi.getHeight()), getParent().getSize());
}
else if(bi.getHeight() > bi.getWidth())
{
scaleFactor = getScaleFactorToFit(new Dimension(bi.getWidth(), bi.getHeight()), getParent().getSize());
}
int scaleWidth = (int)Math.round(bi.getWidth() * scaleFactor);
int scaleHeight = (int)Math.round(bi.getHeight() * scaleFactor);
image = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_FAST);
previousBounds = getParent().getSize();
previousImage = image;
x = (width - image.getWidth(this)) / 2;
y = (height - image.getHeight(this)) / 2;
}
g.drawImage(image, x, y, this);
}
private double getScaleFactorToFit(Dimension masterSize, Dimension targetSize)
{
double dScaleWidth = getScaleFactor(masterSize.width, targetSize.width);
double dScaleHeight = getScaleFactor(masterSize.height, targetSize.height);
double dScale = Math.min(dScaleHeight, dScaleWidth);
return dScale;
}
private double getScaleFactor(int iMasterSize, int iTargetSize)
{
double dScale = 1;
if(iMasterSize > iTargetSize)
{
dScale = (double)iTargetSize / (double)iMasterSize;
}
else
{
dScale = (double)iTargetSize / (double)iMasterSize;
}
return dScale;
}
});
dialog.setTitle(Lang.get("story.background"));
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
dialog.setIconImage(OpenBST.pictureImage);
dialog.setSize(300, 300);
dialog.setLocationRelativeTo(parentWindow);
dialog.setVisible(true);
}
});
JToggleButton muteButton = new JToggleButton("", new ImageIcon(OpenBST.speakerImage));
muteButton.addActionListener(e ->
{
SSBClient ssb = client.getSSBHandler();
if(ssb != null)
{
ssb.setMuted(muteButton.isSelected());
muteButton.setIcon(new ImageIcon(muteButton.isSelected() ? OpenBST.muteImage : OpenBST.speakerImage));
}
});
muteButton.setToolTipText(Lang.get("story.mute"));
toolBar.add(muteButton);
toolBar.add(new AbstractAction(Lang.get("story.close"), new ImageIcon(OpenBST.closeImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.close.confirm"), Lang.get("story.close"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.closeBigImage)) == JOptionPane.YES_OPTION)
{
client.getSSBHandler().shutdown();
parentWindow.removeStory(StoryPanel.this);
}
}
});
for(Component component : toolBar.getComponents())
{
if(component instanceof JButton)
{
((JButton)component).setHideActionText(false);
((JButton)component).setToolTipText(((JButton)component).getText());
((JButton)component).setText("");
}
}
add(toolBar, "growx, wrap");
}
/**
* Read the toolbar level
*
* @return an integer that represents the level specified in the
* "supertools" tag
*/
private int readToolbarLevel()
{
String value = story.getTag("supertools");
if(value == null)
return 4;
switch(value)
{
case "all":
return 4;
case "hidecheat":
return 3;
case "savestate":
return 2;
case "savestatenoio":
return 1;
case "none":
return 0;
default:
return 0;
}
}
/**
* Restore a previous save state by applying it to the story first and
* showing the node stored
*
* @param ss
*/
protected void restoreSaveState(SaveState ss)
{
ss.applySaveState(story);
showNode(story.getNode(ss.getNodeId()));
// Also notify modules that need to restore their state
client.getSSBHandler().restoreSaveState();
client.getIMGHandler().restoreSaveState();
try
{
client.getUIBarHandler().restoreState();
}
catch(BSTException e)
{
// TODO Indicate this exception happened
e.printStackTrace();
}
}
/**
* Setup of the story. This can be ran again if the story changed
*/
private void setupStory()
{
log("=> Analyzing options and deducing maximum option amount");
// Quick analysis of all the nodes to get the maximum amount of options
int maxOptions = 0;
for(final StoryNode sn : story.getAllNodes())
{
if(sn instanceof TextNode && ((TextNode)sn).getOptions().size() > maxOptions)
{
maxOptions = ((TextNode)sn).getOptions().size();
}
}
if(maxOptions < 4)
{
maxOptions = 4;
}
int rows = maxOptions / 2;
// Make sure the options are always a multiple of 2
if(maxOptions % 2 == 1)
{
rows++;
}
options = new NodeOption[rows * 2];
optionsButton = new JButton[rows * 2];
optionPanel.removeAll();
optionPanel.setLayout(new GridLayout(rows, 2, 5, 5));
for(int i = 0; i < options.length; i++)
{
final int optionId = i;
final JButton button = new JButton();
normalButtonFg = button.getForeground();
button.addActionListener(ev ->
{
try
{
optionSelected(options[optionId]);
}
catch(final BSTException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(this, Lang.get("story.error").replace("$n", "" + currentNode.getId()).replace("$m", e.getMessage()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
}
});
optionPanel.add(button);
optionsButton[i] = button;
button.setEnabled(false);
}
log("Displaying first node");
showNode(story.getInitialNode());
}
/**
* Reload the file (not clean, this is a subroutine method part of the
* entire reloading process)
*/
protected void reload()
{
story = parentWindow.loadFile(bstFile, client);
setupStory();
}
/**
* Show a specific node
*
* @param storyNode
* the node to show
*/
private void showNode(final StoryNode storyNode)
{
if(storyNode == null)
{
// The node does not exist
log("=! Node launched does not exist");
if(currentNode == null)
{
log("=! It was the initial node");
JOptionPane.showMessageDialog(this, Lang.get("story.missinginitial"), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
return;
}
else
{
JOptionPane.showMessageDialog(this, Lang.get("story.missingnode").replace("$n", "" + currentNode.getId()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
return;
}
}
log("=> Trying to show node : " + storyNode.getId());
currentNode = storyNode;
if(nodeIdLabel != null)
nodeIdLabel.setText("Node : " + currentNode.getId());
try
{
// If this is a LogicalNode, we need to solve it.
if(storyNode instanceof LogicalNode)
{
log("=> Solving logical node");
final int i = ((LogicalNode)storyNode).solve();
log("=> Logical node result : " + i);
// TODO Throw a nicer exception when an invalid value is returned
showNode(story.getNode(i));
}
// This is supposed to be executed when the StoryNode is a TextNode
if(storyNode instanceof TextNode)
{
log("=> Text node detected");
final TextNode textNode = (TextNode)storyNode;
log("=> Applying text");
nodePanel.applyNode(story, textNode);
log("Resetting options");
resetOptions();
log("Applying options for node : " + textNode.getId());
showOptions(textNode);
log("Updating UIB if necessary");
client.getUIBarHandler().updateUIB();
backgroundButton.setEnabled(client.getIMGHandler().getCurrentBackground() != null);
}
}
catch(final Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(this, Lang.get("story.error").replace("$n", "" + currentNode.getId()).replace("$m", e.getMessage()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
}
}
/**
* The options to show
*
* @param textNode
* @throws BSTException
*/
private void showOptions(final TextNode textNode) throws BSTException
{
log("=> Filtering valid options");
final ArrayList<NodeOption> validOptions = new ArrayList<>();
for(final NodeOption no : textNode.getOptions())
{
if(no.getChecker().check())
{
validOptions.add(no);
}
}
if(validOptions.size() > 0)
{
log("=> Valid options found (" + validOptions.size() + " valid on " + textNode.getOptions().size() + " total)");
log("=> Processing options");
for(int i = 0; i < validOptions.size(); i++)
{
final NodeOption option = validOptions.get(i);
final JButton button = optionsButton[i];
options[i] = option;
button.setEnabled(true);
if(i == 0)
button.requestFocus();
if(option.hasTag("color"))
{
final String color = option.getTag("color");
Color c = null;
if(color.startsWith("#"))
{
c = new Color(Integer.parseInt(color.substring(1), 16));
}
else
{
try
{
c = (Color)Color.class.getField(color).get(null);
}
catch(IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
{
System.err.println("COLOR DOES NOT EXIST : " + color);
e.printStackTrace();
}
}
if(c != null)
{
button.setForeground(c);
}
}
button.setText(option.getText());
}
}
else
{
log("=> No valid options found (" + validOptions.size() + " total");
log("=> Shwoing ending");
optionsButton[0].setText(Lang.get("story.final.end"));
optionsButton[1].setText(Lang.get("story.final.node").replace("$n", "" + textNode.getId()));
optionsButton[2].setText(Lang.get("story.final.restart"));
optionsButton[2].setEnabled(true);
optionsButton[2].requestFocus();
final ActionListener[] original = optionsButton[2].getActionListeners();
final ActionListener[] original2 = optionsButton[3].getActionListeners();
for(final ActionListener al : original)
{
optionsButton[2].removeActionListener(al);
}
final ActionListener shutdownListener = e -> parentWindow.removeStory(this);
optionsButton[2].addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
log("Resetting story");
for(final ActionListener al : original)
{
optionsButton[2].addActionListener(al);
}
for(final ActionListener al : original2)
{
optionsButton[3].addActionListener(al);
}
optionsButton[2].removeActionListener(this);
optionsButton[3].removeActionListener(shutdownListener);
reset();
}
});
optionsButton[3].setText(Lang.get("story.final.close"));
optionsButton[3].setEnabled(true);
for(final ActionListener al : original2)
{
optionsButton[3].removeActionListener(al);
}
optionsButton[3].addActionListener(shutdownListener);
}
}
/**
* Internal reset (subroutine method)
*/
private void reset()
{
log("=> Performing internal reset");
story.reset();
client.getUIBarHandler().resetUib();
client.getIMGHandler().reset();
client.getSSBHandler().reset();
client.getBDFHandler().reset();
log("=> Processing initial node again");
showNode(story.getInitialNode());
}
/**
* Reset all the options and return to a clean state for the options panel
*/
private void resetOptions()
{
for(int i = 0; i < optionsButton.length; i++)
{
options[i] = null;
final JButton button = optionsButton[i];
button.setForeground(normalButtonFg);
button.setEnabled(false);
button.setText("");
}
}
/**
* Triggered when an option is selected
*
* @param nodeOption
* The option selected
* @throws BSTException
*/
private void optionSelected(final NodeOption nodeOption) throws BSTException
{
int nextNode = nodeOption.getNextNode();
for(final ActionDescriptor oa : nodeOption.getDoOnClickActions())
{
oa.exec();
}
showNode(story.getNode(nextNode));
}
/**
* Log a message
*
* @param message
* the message to log
*/
public static void log(String message)
{
// TODO Add a better logging system
System.out.println(message);
}
/**
* Get the title of this story, used to get the title for the tab
*
* @return
*/
public String getTitle()
{
HashMap<String, String> tagMap = story.getTagMap();
return Lang.get("story.title").replace("$t", tagMap.getOrDefault("title", Lang.get("story.missingtitle"))).replace("$a", tagMap.getOrDefault("author", Lang.get("story.missingauthor")));
}
/**
* Check if there is anything to do after creation and we can continue
* running the story
*
* @return true if we can continue running the story, false otherwise
*/
public boolean postCreation()
{
log("Issuing NSFW warning");
if(story.hasTag("nsfw") && JOptionPane.showConfirmDialog(this, Lang.get("story.nsfw"), Lang.get("story.nsfw.title"), JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION)
{
log("=> Close");
return false;
}
else if(nodeIdLabel != null)
nodeIdLabel.setForeground(Color.RED);
return true;
}
/**
* Notify that the variable watcher is closing (this is used to reset the
* button's state
*/
protected void variableWatchClosing()
{
variableWatcherButton.setSelected(false);
variableWatcher.deathNotified();
variableWatcher.dispose();
}
/**
* Get the file the story is from
*
* @return the file originally put in the constructor
*/
public File getBSTFile()
{
return bstFile;
}
}
| openbst/src/main/java/utybo/branchingstorytree/swing/StoryPanel.java | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
*/
package utybo.branchingstorytree.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import com.google.gson.Gson;
import net.miginfocom.swing.MigLayout;
import utybo.branchingstorytree.api.BSTException;
import utybo.branchingstorytree.api.script.ActionDescriptor;
import utybo.branchingstorytree.api.story.BranchingStory;
import utybo.branchingstorytree.api.story.LogicalNode;
import utybo.branchingstorytree.api.story.NodeOption;
import utybo.branchingstorytree.api.story.SaveState;
import utybo.branchingstorytree.api.story.StoryNode;
import utybo.branchingstorytree.api.story.TextNode;
import utybo.branchingstorytree.swing.JScrollablePanel.ScrollableSizeHint;
@SuppressWarnings("serial")
public class StoryPanel extends JPanel
{
/**
* The story represented by this StoryPanel. This variable will change if
* the file is reload.
*/
protected BranchingStory story;
/**
* The panel for use with the UIB Module
*/
protected JPanel uibPanel;
/**
* The node currently on screen
*/
private StoryNode currentNode;
/**
* The {@link TabClient} linked to this panel
*/
private TabClient client;
/**
* The latest save state made - this is used with the save state buttons
*/
private SaveState latestSaveState;
/**
* The file this story is from
*/
private File bstFile;
/**
* The OpenBST window
*/
protected OpenBST parentWindow;
/**
* The node panel the text is displayed in
*/
private final NodePanel nodePanel;
/**
* The label displaying the current node ID.
*/
private JLabel nodeIdLabel;
/**
* The list of node options for the current node
*/
private NodeOption[] options;
/**
* An array of the Option Buttons available in the grid
*/
private JButton[] optionsButton;
/**
* The panel in which option buttons are placed
*/
private final JPanel optionPanel = new JPanel();
/**
* The regular foreground for option buttons when the "color" tag is not
* applied
*/
private Color normalButtonFg;
// --- Toolbar buttons ---
private JButton restoreSaveStateButton, exportSaveStateButton;
protected JToggleButton variableWatcherButton;
protected VariableWatchDialog variableWatcher;
private JButton backgroundButton;
/**
* Initialize the story panel
*
* @param story
* the story to create
* @param parentWindow
* the OpenBST instance we are creating this story from
* @param f
* the file the story is from
* @param client
* the client that will be linked to this story
*/
public StoryPanel(BranchingStory story, OpenBST parentWindow, File f, TabClient client)
{
log("=> Initial setup");
bstFile = f;
client.setStoryPanel(this);
this.story = story;
this.parentWindow = parentWindow;
this.client = client;
log("=> Creating visual elements");
setLayout(new MigLayout("hidemode 3", "[grow]", ""));
createToolbar();
if(story.hasTag("uib_layout"))
{
uibPanel = new JPanel();
add(uibPanel, "growx, wrap");
uibPanel.setVisible(false);
}
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBackground(Color.WHITE);
add(scrollPane, "grow, pushy, wrap");
nodePanel = new NodePanel(client.getIMGHandler());
nodePanel.setScrollableWidth(ScrollableSizeHint.FIT);
nodePanel.setScrollableHeight(ScrollableSizeHint.STRETCH);
scrollPane.setViewportView(nodePanel);
add(optionPanel, "growx");
setupStory();
}
/**
* Create the toolbar, enforcing the supertools tag
*/
private void createToolbar()
{
int toolbarLevel = readToolbarLevel();
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
if(toolbarLevel > 0)
{
toolBar.add(new AbstractAction(Lang.get("story.createss"), new ImageIcon(OpenBST.saveAsImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
latestSaveState = new SaveState(currentNode.getId(), story.getRegistry());
restoreSaveStateButton.setEnabled(true);
if(exportSaveStateButton != null)
exportSaveStateButton.setEnabled(true);
}
});
restoreSaveStateButton = toolBar.add(new AbstractAction(Lang.get("story.restoress"), new ImageIcon(OpenBST.undoImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.restoress.confirm"), Lang.get("story.restoress"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.undoBigImage)) == JOptionPane.YES_OPTION)
{
restoreSaveState(latestSaveState);
}
}
});
restoreSaveStateButton.setEnabled(false);
if(toolbarLevel > 1)
{
exportSaveStateButton = toolBar.add(new AbstractAction(Lang.get("story.exportss"), new ImageIcon(OpenBST.exportImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
final FileDialog jfc = new FileDialog(parentWindow, Lang.get("story.sslocation"), FileDialog.SAVE);
jfc.setLocationRelativeTo(parentWindow);
jfc.setIconImage(OpenBST.exportImage);
jfc.setVisible(true);
if(jfc.getFile() != null)
{
File file = new File(jfc.getFile().endsWith(".bss") ? jfc.getDirectory() + jfc.getFile() : jfc.getDirectory() + jfc.getFile() + ".bss");
Gson gson = new Gson();
file.delete();
try
{
file.createNewFile();
FileWriter writer = new FileWriter(file);
gson.toJson(new SaveState(currentNode.getId(), story.getRegistry()), writer);
writer.flush();
writer.close();
}
catch(IOException e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(parentWindow, Lang.get("story.exportss.error").replace("$m", e1.getMessage()).replace("$e", e1.getClass().getSimpleName()));
}
}
}
});
exportSaveStateButton.setEnabled(false);
toolBar.add(new AbstractAction(Lang.get("story.importss"), new ImageIcon(OpenBST.importImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
final FileDialog jfc = new FileDialog(parentWindow, Lang.get("story.sslocation"), FileDialog.LOAD);
jfc.setLocationRelativeTo(parentWindow);
jfc.setIconImage(OpenBST.importImage);
jfc.setVisible(true);
if(jfc.getFile() != null)
{
File file = new File(jfc.getDirectory() + jfc.getFile());
Gson gson = new Gson();
try
{
FileReader reader = new FileReader(file);
latestSaveState = gson.fromJson(reader, SaveState.class);
reader.close();
restoreSaveState(latestSaveState);
}
catch(IOException e1)
{
e1.printStackTrace();
JOptionPane.showMessageDialog(parentWindow, Lang.get("story.exportss.error").replace("$m", e1.getMessage()).replace("$e", e1.getClass().getSimpleName()));
}
}
}
});
if(toolbarLevel > 2)
{
toolBar.addSeparator();
toolBar.add(new AbstractAction(Lang.get("story.reset"), new ImageIcon(OpenBST.returnImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.reset.confirm"), Lang.get("story.reset"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.returnBigImage)) == JOptionPane.YES_OPTION)
{
reset();
}
}
});
toolBar.add(new AbstractAction(Lang.get("story.sreload"), new ImageIcon(OpenBST.refreshImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.sreload.confirm"), Lang.get("story.sreload.confirm.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.refreshBigImage)) == JOptionPane.YES_OPTION)
{
SaveState ss = new SaveState(currentNode.getId(), story.getRegistry());
reset();
reload();
reset();
restoreSaveState(ss);
}
}
});
toolBar.add(new AbstractAction(Lang.get("story.hreload"), new ImageIcon(OpenBST.synchronizeImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.hreload.confirm"), Lang.get("story.hreload.confirm.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.synchronizeBigImage)) == JOptionPane.YES_OPTION)
{
reset();
reload();
reset();
}
}
});
if(toolbarLevel > 3)
{
toolBar.addSeparator();
toolBar.add(new AbstractAction(Lang.get("story.jumptonode"), new ImageIcon(OpenBST.jumpImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
SpinnerNumberModel model = new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1);
JSpinner spinner = new JSpinner(model);
int i = JOptionPane.showOptionDialog(parentWindow, spinner, Lang.get("story.jumptonode"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(OpenBST.jumpBigImage), null, null);
if(i == JOptionPane.OK_OPTION)
{
showNode(story.getNode((Integer)spinner.getModel().getValue()));
}
}
});
variableWatcherButton = new JToggleButton("", new ImageIcon(OpenBST.addonSearchImage));
variableWatcherButton.addItemListener(e ->
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
variableWatcher = new VariableWatchDialog(StoryPanel.this);
variableWatcher.setVisible(true);
}
else if(e.getStateChange() == ItemEvent.DESELECTED)
{
variableWatchClosing();
}
});
variableWatcherButton.setToolTipText(Lang.get("story.variablewatcher"));
toolBar.add(variableWatcherButton);
toolBar.addSeparator();
nodeIdLabel = new JLabel(Lang.get("wait"));
nodeIdLabel.setVerticalAlignment(SwingConstants.CENTER);
nodeIdLabel.setEnabled(false);
toolBar.add(nodeIdLabel);
}
}
}
toolBar.addSeparator();
JLabel hintLabel = new JLabel(Lang.get("story.tip"));
hintLabel.setEnabled(false);
toolBar.add(hintLabel);
}
toolBar.add(Box.createHorizontalGlue());
toolBar.addSeparator();
backgroundButton = toolBar.add(new AbstractAction(Lang.get("story.seebackground"), new ImageIcon(OpenBST.pictureImage))
{
@Override
public void actionPerformed(ActionEvent e)
{
JDialog dialog = new JDialog(parentWindow);
dialog.add(new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
BufferedImage image = client.getIMGHandler().getCurrentBackground();
double scaleFactor = 1d;
if(image.getWidth() > image.getHeight())
{
scaleFactor = getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getParent().getSize());
}
else if(image.getHeight() > image.getWidth())
{
scaleFactor = getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getParent().getSize());
}
int scaleWidth = (int)Math.round(image.getWidth() * scaleFactor);
int scaleHeight = (int)Math.round(image.getHeight() * scaleFactor);
Image scaled = image.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
int width = getWidth() - 1;
int height = getHeight() - 1;
int x = (width - scaled.getWidth(this)) / 2;
int y = (height - scaled.getHeight(this)) / 2;
g.drawImage(scaled, x, y, this);
}
private double getScaleFactorToFit(Dimension masterSize, Dimension targetSize)
{
double dScaleWidth = getScaleFactor(masterSize.width, targetSize.width);
double dScaleHeight = getScaleFactor(masterSize.height, targetSize.height);
double dScale = Math.min(dScaleHeight, dScaleWidth);
return dScale;
}
private double getScaleFactor(int iMasterSize, int iTargetSize)
{
double dScale = 1;
if(iMasterSize > iTargetSize)
{
dScale = (double)iTargetSize / (double)iMasterSize;
}
else
{
dScale = (double)iTargetSize / (double)iMasterSize;
}
return dScale;
}
});
dialog.setTitle(Lang.get("story.background"));
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
dialog.setIconImage(OpenBST.pictureImage);
dialog.setSize(300, 300);
dialog.setLocationRelativeTo(parentWindow);
dialog.setVisible(true);
}
});
JToggleButton muteButton = new JToggleButton("", new ImageIcon(OpenBST.speakerImage));
muteButton.addActionListener(e ->
{
SSBClient ssb = client.getSSBHandler();
if(ssb != null)
{
ssb.setMuted(muteButton.isSelected());
muteButton.setIcon(new ImageIcon(muteButton.isSelected() ? OpenBST.muteImage : OpenBST.speakerImage));
}
});
muteButton.setToolTipText(Lang.get("story.mute"));
toolBar.add(muteButton);
toolBar.add(new AbstractAction(Lang.get("story.close"), new ImageIcon(OpenBST.closeImage))
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
if(JOptionPane.showConfirmDialog(parentWindow, Lang.get("story.close.confirm"), Lang.get("story.close"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, new ImageIcon(OpenBST.closeBigImage)) == JOptionPane.YES_OPTION)
{
client.getSSBHandler().shutdown();
parentWindow.removeStory(StoryPanel.this);
}
}
});
for(Component component : toolBar.getComponents())
{
if(component instanceof JButton)
{
((JButton)component).setHideActionText(false);
((JButton)component).setToolTipText(((JButton)component).getText());
((JButton)component).setText("");
}
}
add(toolBar, "growx, wrap");
}
/**
* Read the toolbar level
*
* @return an integer that represents the level specified in the
* "supertools" tag
*/
private int readToolbarLevel()
{
String value = story.getTag("supertools");
if(value == null)
return 4;
switch(value)
{
case "all":
return 4;
case "hidecheat":
return 3;
case "savestate":
return 2;
case "savestatenoio":
return 1;
case "none":
return 0;
default:
return 0;
}
}
/**
* Restore a previous save state by applying it to the story first and
* showing the node stored
*
* @param ss
*/
protected void restoreSaveState(SaveState ss)
{
ss.applySaveState(story);
showNode(story.getNode(ss.getNodeId()));
// Also notify modules that need to restore their state
client.getSSBHandler().restoreSaveState();
client.getIMGHandler().restoreSaveState();
try
{
client.getUIBarHandler().restoreState();
}
catch(BSTException e)
{
// TODO Indicate this exception happened
e.printStackTrace();
}
}
/**
* Setup of the story. This can be ran again if the story changed
*/
private void setupStory()
{
log("=> Analyzing options and deducing maximum option amount");
// Quick analysis of all the nodes to get the maximum amount of options
int maxOptions = 0;
for(final StoryNode sn : story.getAllNodes())
{
if(sn instanceof TextNode && ((TextNode)sn).getOptions().size() > maxOptions)
{
maxOptions = ((TextNode)sn).getOptions().size();
}
}
if(maxOptions < 4)
{
maxOptions = 4;
}
int rows = maxOptions / 2;
// Make sure the options are always a multiple of 2
if(maxOptions % 2 == 1)
{
rows++;
}
options = new NodeOption[rows * 2];
optionsButton = new JButton[rows * 2];
optionPanel.removeAll();
optionPanel.setLayout(new GridLayout(rows, 2, 5, 5));
for(int i = 0; i < options.length; i++)
{
final int optionId = i;
final JButton button = new JButton();
normalButtonFg = button.getForeground();
button.addActionListener(ev ->
{
try
{
optionSelected(options[optionId]);
}
catch(final BSTException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(this, Lang.get("story.error").replace("$n", "" + currentNode.getId()).replace("$m", e.getMessage()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
}
});
optionPanel.add(button);
optionsButton[i] = button;
button.setEnabled(false);
}
log("Displaying first node");
showNode(story.getInitialNode());
}
/**
* Reload the file (not clean, this is a subroutine method part of the
* entire reloading process)
*/
protected void reload()
{
story = parentWindow.loadFile(bstFile, client);
setupStory();
}
/**
* Show a specific node
*
* @param storyNode
* the node to show
*/
private void showNode(final StoryNode storyNode)
{
if(storyNode == null)
{
// The node does not exist
log("=! Node launched does not exist");
if(currentNode == null)
{
log("=! It was the initial node");
JOptionPane.showMessageDialog(this, Lang.get("story.missinginitial"), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
return;
}
else
{
JOptionPane.showMessageDialog(this, Lang.get("story.missingnode").replace("$n", "" + currentNode.getId()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
return;
}
}
log("=> Trying to show node : " + storyNode.getId());
currentNode = storyNode;
if(nodeIdLabel != null)
nodeIdLabel.setText("Node : " + currentNode.getId());
try
{
// If this is a LogicalNode, we need to solve it.
if(storyNode instanceof LogicalNode)
{
log("=> Solving logical node");
final int i = ((LogicalNode)storyNode).solve();
log("=> Logical node result : " + i);
// TODO Throw a nicer exception when an invalid value is returned
showNode(story.getNode(i));
}
// This is supposed to be executed when the StoryNode is a TextNode
if(storyNode instanceof TextNode)
{
log("=> Text node detected");
final TextNode textNode = (TextNode)storyNode;
log("=> Applying text");
nodePanel.applyNode(story, textNode);
log("Resetting options");
resetOptions();
log("Applying options for node : " + textNode.getId());
showOptions(textNode);
log("Updating UIB if necessary");
client.getUIBarHandler().updateUIB();
backgroundButton.setEnabled(client.getIMGHandler().getCurrentBackground() != null);
}
}
catch(final Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(this, Lang.get("story.error").replace("$n", "" + currentNode.getId()).replace("$m", e.getMessage()), Lang.get("error"), JOptionPane.ERROR_MESSAGE);
}
}
/**
* The options to show
*
* @param textNode
* @throws BSTException
*/
private void showOptions(final TextNode textNode) throws BSTException
{
log("=> Filtering valid options");
final ArrayList<NodeOption> validOptions = new ArrayList<>();
for(final NodeOption no : textNode.getOptions())
{
if(no.getChecker().check())
{
validOptions.add(no);
}
}
if(validOptions.size() > 0)
{
log("=> Valid options found (" + validOptions.size() + " valid on " + textNode.getOptions().size() + " total)");
log("=> Processing options");
for(int i = 0; i < validOptions.size(); i++)
{
final NodeOption option = validOptions.get(i);
final JButton button = optionsButton[i];
options[i] = option;
button.setEnabled(true);
if(i == 0)
button.requestFocus();
if(option.hasTag("color"))
{
final String color = option.getTag("color");
Color c = null;
if(color.startsWith("#"))
{
c = new Color(Integer.parseInt(color.substring(1), 16));
}
else
{
try
{
c = (Color)Color.class.getField(color).get(null);
}
catch(IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
{
System.err.println("COLOR DOES NOT EXIST : " + color);
e.printStackTrace();
}
}
if(c != null)
{
button.setForeground(c);
}
}
button.setText(option.getText());
}
}
else
{
log("=> No valid options found (" + validOptions.size() + " total");
log("=> Shwoing ending");
optionsButton[0].setText(Lang.get("story.final.end"));
optionsButton[1].setText(Lang.get("story.final.node").replace("$n", "" + textNode.getId()));
optionsButton[2].setText(Lang.get("story.final.restart"));
optionsButton[2].setEnabled(true);
optionsButton[2].requestFocus();
final ActionListener[] original = optionsButton[2].getActionListeners();
final ActionListener[] original2 = optionsButton[3].getActionListeners();
for(final ActionListener al : original)
{
optionsButton[2].removeActionListener(al);
}
final ActionListener shutdownListener = e -> parentWindow.removeStory(this);
optionsButton[2].addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
log("Resetting story");
for(final ActionListener al : original)
{
optionsButton[2].addActionListener(al);
}
for(final ActionListener al : original2)
{
optionsButton[3].addActionListener(al);
}
optionsButton[2].removeActionListener(this);
optionsButton[3].removeActionListener(shutdownListener);
reset();
}
});
optionsButton[3].setText(Lang.get("story.final.close"));
optionsButton[3].setEnabled(true);
for(final ActionListener al : original2)
{
optionsButton[3].removeActionListener(al);
}
optionsButton[3].addActionListener(shutdownListener);
}
}
/**
* Internal reset (subroutine method)
*/
private void reset()
{
log("=> Performing internal reset");
story.reset();
client.getUIBarHandler().resetUib();
client.getIMGHandler().reset();
client.getSSBHandler().reset();
client.getBDFHandler().reset();
log("=> Processing initial node again");
showNode(story.getInitialNode());
}
/**
* Reset all the options and return to a clean state for the options panel
*/
private void resetOptions()
{
for(int i = 0; i < optionsButton.length; i++)
{
options[i] = null;
final JButton button = optionsButton[i];
button.setForeground(normalButtonFg);
button.setEnabled(false);
button.setText("");
}
}
/**
* Triggered when an option is selected
*
* @param nodeOption
* The option selected
* @throws BSTException
*/
private void optionSelected(final NodeOption nodeOption) throws BSTException
{
int nextNode = nodeOption.getNextNode();
for(final ActionDescriptor oa : nodeOption.getDoOnClickActions())
{
oa.exec();
}
showNode(story.getNode(nextNode));
}
/**
* Log a message
*
* @param message
* the message to log
*/
public static void log(String message)
{
// TODO Add a better logging system
System.out.println(message);
}
/**
* Get the title of this story, used to get the title for the tab
*
* @return
*/
public String getTitle()
{
HashMap<String, String> tagMap = story.getTagMap();
return Lang.get("story.title").replace("$t", tagMap.getOrDefault("title", Lang.get("story.missingtitle"))).replace("$a", tagMap.getOrDefault("author", Lang.get("story.missingauthor")));
}
/**
* Check if there is anything to do after creation and we can continue
* running the story
*
* @return true if we can continue running the story, false otherwise
*/
public boolean postCreation()
{
log("Issuing NSFW warning");
if(story.hasTag("nsfw") && JOptionPane.showConfirmDialog(this, Lang.get("story.nsfw"), Lang.get("story.nsfw.title"), JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION)
{
log("=> Close");
return false;
}
else if(nodeIdLabel != null)
nodeIdLabel.setForeground(Color.RED);
return true;
}
/**
* Notify that the variable watcher is closing (this is used to reset the
* button's state
*/
protected void variableWatchClosing()
{
variableWatcherButton.setSelected(false);
variableWatcher.deathNotified();
variableWatcher.dispose();
}
/**
* Get the file the story is from
*
* @return the file originally put in the constructor
*/
public File getBSTFile()
{
return bstFile;
}
}
| OpenBST : Optimize background algorithm
Don't recalculate everything every time
| openbst/src/main/java/utybo/branchingstorytree/swing/StoryPanel.java | OpenBST : Optimize background algorithm | <ide><path>penbst/src/main/java/utybo/branchingstorytree/swing/StoryPanel.java
<ide>
<ide> backgroundButton = toolBar.add(new AbstractAction(Lang.get("story.seebackground"), new ImageIcon(OpenBST.pictureImage))
<ide> {
<add> private Dimension previousBounds;
<add> private Image previousImage;
<add> private int x, y;
<ide>
<ide> @Override
<ide> public void actionPerformed(ActionEvent e)
<ide> protected void paintComponent(Graphics g)
<ide> {
<ide> super.paintComponent(g);
<del> BufferedImage image = client.getIMGHandler().getCurrentBackground();
<del> double scaleFactor = 1d;
<del> if(image.getWidth() > image.getHeight())
<del> {
<del> scaleFactor = getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getParent().getSize());
<del> }
<del> else if(image.getHeight() > image.getWidth())
<del> {
<del> scaleFactor = getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getParent().getSize());
<del> }
<del> int scaleWidth = (int)Math.round(image.getWidth() * scaleFactor);
<del> int scaleHeight = (int)Math.round(image.getHeight() * scaleFactor);
<del>
<del> Image scaled = image.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
<del>
<add> Image image;
<ide> int width = getWidth() - 1;
<ide> int height = getHeight() - 1;
<del>
<del> int x = (width - scaled.getWidth(this)) / 2;
<del> int y = (height - scaled.getHeight(this)) / 2;
<del>
<del> g.drawImage(scaled, x, y, this);
<add> if(previousBounds != null && previousImage != null && getParent().getSize().equals(previousBounds))
<add> {
<add> image = previousImage;
<add> }
<add> else
<add> {
<add> BufferedImage bi = client.getIMGHandler().getCurrentBackground();
<add> double scaleFactor = 1d;
<add> if(bi.getWidth() > bi.getHeight())
<add> {
<add> scaleFactor = getScaleFactorToFit(new Dimension(bi.getWidth(), bi.getHeight()), getParent().getSize());
<add> }
<add> else if(bi.getHeight() > bi.getWidth())
<add> {
<add> scaleFactor = getScaleFactorToFit(new Dimension(bi.getWidth(), bi.getHeight()), getParent().getSize());
<add> }
<add> int scaleWidth = (int)Math.round(bi.getWidth() * scaleFactor);
<add> int scaleHeight = (int)Math.round(bi.getHeight() * scaleFactor);
<add>
<add> image = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_FAST);
<add>
<add> previousBounds = getParent().getSize();
<add> previousImage = image;
<add> x = (width - image.getWidth(this)) / 2;
<add> y = (height - image.getHeight(this)) / 2;
<add> }
<add>
<add> g.drawImage(image, x, y, this);
<ide> }
<ide>
<ide> private double getScaleFactorToFit(Dimension masterSize, Dimension targetSize) |
|
Java | apache-2.0 | 55f635f8c71448910a2b12b919da8635a33dce1e | 0 | ALEXGUOQ/async-http-client,hgl888/async-http-client,fengshao0907/async-http-client,wyyl1/async-http-client,Aulust/async-http-client,bomgar/async-http-client,afelisatti/async-http-client,drmaas/async-http-client,jroper/async-http-client,liuyb02/async-http-client,dotta/async-http-client,elijah513/async-http-client,jxauchengchao/async-http-client,nemoyixin/async-http-client,ooon/async-http-client,junjiemars/async-http-client,thinker-fang/async-http-client,magiccao/async-http-client,craigwblake/async-http-client-1,stepancheg/async-http-client,Aulust/async-http-client,olksdr/async-http-client,typesafehub/async-http-client | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.http.client.providers.netty;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.RandomAccessBody;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.ntlm.NTLMEngine;
import com.ning.http.client.ntlm.NTLMEngineException;
import com.ning.http.client.providers.netty.spnego.SpnegoEngine;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.CleanupChannelGroup;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.ning.http.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider<HttpResponse> {
private final static String HTTP_HANDLER = "httpHandler";
final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final ChannelGroup openChannels = new
CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if( removed ) {
maxConnections.decrementAndGet();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private final AtomicInteger maxConnections = new AtomicInteger();
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = false;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private final static SpnegoEngine spnegoEngine = new SpnegoEngine();
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() != null
&& NettyAsyncHttpProviderConfig.class.isAssignableFrom(config.getAsyncHttpProviderConfig().getClass())) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig != null && asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO) != null) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
} else {
socketChannelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
config.executorService());
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
this.config = config;
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
configureNetty();
trackConnections = (config.getMaxTotalConnections() != -1);
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s",
maxConnections.get(),
openChannels.toString(),
connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
plainBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
plainBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.EXECUTE_ASYNC_CONNECT) != null) {
executeConnectAsync = true;
} else if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.DISABLE_NESTED_REQUEST) != null) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
secureBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
}
private Channel lookupInCache(URI uri) {
final Channel channel = connectionsPool.poll(AsyncHttpProviderUtils.getBaseUrl(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && HTTPS.equalsIgnoreCase(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it,
* we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getBodyGenerator() != null) {
try {
body = future.getRequest().getBodyGenerator().createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(
new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
}
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null) {
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
writeFuture = channel.write(new BodyFileRegion((RandomAccessBody) body));
} else {
writeFuture = channel.write(new BodyChunkedInput(body));
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int delay = requestTimeout(config, future.getRequest().getPerRequestConfig());
if (delay != -1) {
ReaperFuture reaperFuture = new ReaperFuture(channel, future);
Future scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, delay, 500, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri,
boolean allowConnect, ChannelBuffer buffer) throws IOException {
String method = request.getMethod();
if (allowConnect && ((request.getProxyServer() != null || config.getProxyServer() != null) && HTTPS.equalsIgnoreCase(uri.getScheme()))) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer);
}
@SuppressWarnings("deprecation")
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
StringBuilder path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
ntlmEngine.generateType1Msg("NTLM " + realm.getNtlmDomain(), realm.getNtlmHost()));
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String authServer = proxyServer == null ? AsyncHttpProviderUtils.getBaseUrl(uri) : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(authServer);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else {
nettyRequest.setHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), bodyCharset));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for(Channel channel: openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final Collection<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f,
boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
URI uri = AsyncHttpProviderUtils.createUri(request.getUrl());
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
channel = lookupInCache(uri);
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null &&
!f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = uri.getScheme().compareToIgnoreCase(HTTPS) == 0 && proxyServer == null;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = buildRequest(config, request, uri, false, bufferedBytes);
if (f == null) {
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this);
} else {
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (IllegalStateException ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
throw ex;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && (!connectionsPool.canCacheConnection() ||
(config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()))) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()",t);
}
throw ex;
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
if (trackConnections) {
maxConnections.incrementAndGet();
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = useSSl ? secureBootstrap : plainBootstrap;
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
// Do no enable this with win.
if (System.getProperty("os.name").toLowerCase().indexOf("win") == -1) {
bootstrap.setOption("reuseAddress", asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.REUSE_ADDRESS));
}
try {
if (proxyServer == null || avoidProxy) {
channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), AsyncHttpProviderUtils.getPort(uri)));
} else {
channelFuture = bootstrap.connect(new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()));
}
} catch (Throwable t) {
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
abort(c.future(), new ConnectException("Connect times out"));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) {
int result;
if (perRequestConfig != null) {
int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs();
result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs());
} else {
result = config.getRequestTimeoutInMs();
}
return result;
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
ctx.setAttachment(new DiscardEvent());
if (ctx.getChannel() != null) {
openChannels.remove(ctx.getChannel());
}
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null || !ctx.getChannel().isOpen()) {
return;
}
log.debug("Closing Channel {} ", ctx.getChannel());
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
// The IdleStateHandler times out and he is calling us.
// We already closed the channel in IdleStateHandler#channelIdle
// so we have nothing to do
return;
}
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler<?> handler = future.getAsyncHandler();
Request request = future.getRequest();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ka.toLowerCase().equals("keep-alive"));
List<String> wwwAuth = getWwwAuth(response.getHeaders());
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, this);
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(handler).request(request).responseStatus(status).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
if (statusCode == 401
&& wwwAuth.size() > 0
&& realm != null
&& !future.getAndSetAuth(true)) {
final RequestBuilder builder = new RequestBuilder(future.getRequest());
future.setState(NettyResponseFuture.STATE.NEW);
if (!future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
builder.setUrl(future.getURI().toString());
}
Realm newRealm = null;
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
// TODO: Refactor and put this code out of here.
// NTLM
if (wwwAuth.get(0).startsWith("NTLM") || (wwwAuth.get(0).startsWith("Negotiate")
&& realm.getAuthScheme() == Realm.AuthScheme.NTLM)) {
String ntlmDomain = proxyServer == null ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = proxyServer == null ? realm.getNtlmHost() : proxyServer.getHost();
String prinicipal = proxyServer == null ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = proxyServer == null ? realm.getPassword() : proxyServer.getPassword();
if (!realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setNtlmMessageType2Received(true)
.build();
future.getAndSetAuth(false);
} else {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(prinicipal, password,
ntlmDomain, ntlmHost, serverChallenge);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.build();
}
// SPNEGO KERBEROS
} else if (wwwAuth.get(0).startsWith("Negotiate") && (realm.getAuthScheme() == Realm.AuthScheme.KERBEROS
|| realm.getAuthScheme() == Realm.AuthScheme.SPNEGO)) {
URI uri = URI.create(request.getUrl());
String authServer = proxyServer == null ? AsyncHttpProviderUtils.getBaseUrl(uri) : proxyServer.getHost();
try {
String challengeHeader = spnegoEngine.generateToken(authServer);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negociate " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(uri.getPath())
.setMethodName(request.getMethod())
.build();
} catch (Throwable throwable) {
abort(future, throwable);
return;
}
} else {
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(wwwAuth.get(0))
.build();
}
final Realm nr = newRealm;
log.debug("Sending authentication to {}", request.getUrl());
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
nextRequest(builder.setHeaders(headers).setRealm(nr).build(), future);
return null;
}
};
if (future.getKeepAlive() && response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
if (statusCode == 100) {
future.getAndSetWriteHeaders(false);
future.getAndSetWriteBody(true);
writeRequest(ctx.getChannel(), config, future, nettyRequest);
return;
}
String proxyAuth = response.getHeader(HttpHeaders.Names.PROXY_AUTHENTICATE);
if (statusCode == 407
&& proxyAuth != null
&& future.getRequest().getRealm() != null
&& !future.getAndSetAuth(true)) {
log.debug("Sending proxy authentication to {}", request.getUrl());
nextRequest(future.getRequest(), future);
return;
}
if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)
&& statusCode == 200) {
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
log.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());
if (future.getKeepAlive()) {
future.attachChannel(ctx.getChannel(), true);
}
final RequestBuilder builder = new RequestBuilder(future.getRequest());
try {
log.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
upgradeProtocol(ctx.getChannel().getPipeline(), request.getUrl());
} catch (Throwable ex) {
abort(future, ex);
}
nextRequest(builder.build(), future);
return;
}
boolean redirectEnabled = request.isRedirectEnabled() ? true : config.isRedirectEnabled();
if (redirectEnabled && (statusCode == 302 || statusCode == 301)) {
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
// We must allow 401 handling again.
future.getAndSetAuth(false);
String location = response.getHeader(HttpHeaders.Names.LOCATION);
URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
if (!uri.toString().equalsIgnoreCase(future.getURI().toString())) {
final RequestBuilder builder = new RequestBuilder(future.getRequest());
final URI initialConnectionUri = future.getURI();
final boolean initialConnectionKeepAlive = future.getKeepAlive();
future.setURI(uri);
final String newUrl = uri.toString();
log.debug("Redirecting to {}", newUrl);
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
drainChannel(ctx, future, initialConnectionKeepAlive, initialConnectionUri);
nextRequest(builder.setUrl(newUrl).build(), future);
return null;
}
};
if (response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, status)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(), response, this))) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), response, this));
}
finishUpdate(future, ctx, false);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), response, this));
markAsDoneAndCacheConnection(future, ctx);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
return;
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), null, this, chunk))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),
future.getHttpResponse(), this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx, !chunk.isLast());
}
}
}
} catch (Exception t) {
if (IOException.class.isAssignableFrom(t.getClass()) && config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(IOException.class.cast(t)).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
}
try {
abort(future, t);
} finally {
finishUpdate(future, ctx, false);
throw t;
}
}
}
private void drainChannel(final ChannelHandlerContext ctx, final NettyResponseFuture<?> future, final boolean keepAlive, final URI uri){
ctx.setAttachment(new AsyncCallable(future) {
public Object call() throws Exception {
if (keepAlive && ctx.getChannel().isReadable()) {
if (!connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(uri), ctx.getChannel())) {
finishChannel(ctx);
}
} else {
finishChannel(ctx);
}
return null;
}
});
}
private FilterContext handleIoException(FilterContext fc, NettyResponseFuture<?> future) {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
return fc;
}
private void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, HttpResponse response, ChannelHandlerContext ctx) throws IOException {
final Request newRequest = fc.getRequest();
future.setAsyncHandler(fc.getAsyncHandler());
future.setState(NettyResponseFuture.STATE.NEW);
future.touch();
log.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(newRequest, future);
return;
}
private List<String> getWwwAuth(List<Entry<String, String>> list) {
ArrayList<String> l = new ArrayList<String>();
for (Entry<String, String> e : list) {
if (e.getKey().equalsIgnoreCase("WWW-Authenticate")) {
l.add(e.getValue());
}
}
return l;
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future) throws IOException {
nextRequest(request, future, true);
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future, final boolean useCache) throws IOException {
execute(request, future, useCache, true, true);
}
private void abort(NettyResponseFuture<?> future, Throwable t) {
if (future.channel() != null && openChannels.contains(future.channel())) {
openChannels.remove(future.channel());
}
if (trackConnections) {
maxConnections.decrementAndGet();
}
log.debug("Aborting Future {}\n", future);
log.debug(t.getMessage(), t);
future.abort(t);
}
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException {
if (p.get(HTTP_HANDLER) != null) {
p.remove(HTTP_HANDLER);
}
if (scheme.startsWith(HTTPS)) {
if (p.get(SSL_HANDLER) == null) {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
} else {
p.addAfter(SSL_HANDLER, HTTP_HANDLER, new HttpClientCodec());
}
} else {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (isClose.get()) {
return;
}
connectionsPool.removeAll(ctx.getChannel());
Exception exception = null;
try {
super.channelClosed(ctx, e);
} catch (Exception ex) {
exception = ex;
}
log.debug("Channel Closed: {} with attachment {}", e.getChannel(), ctx.getAttachment());
if (ctx.getAttachment() instanceof AsyncCallable) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ctx.setAttachment(ac.future());
ac.call();
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
if (config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest() && !future.cannotBeReplay()) {
replayRequest(future, fc, null, ctx);
return;
}
}
if (future != null && !future.isDone()) {
if (!remotelyClosed(ctx.getChannel(), future)) {
abort(future, new IOException("Remotely Closed"));
}
}
} else {
closeChannel(ctx);
}
}
protected boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) {
if (isClose.get()) {
return false;
}
connectionsPool.removeAll(channel);
if (future == null && channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment() != null
&& NettyResponseFuture.class.isAssignableFrom(
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment().getClass())) {
future = (NettyResponseFuture<?>)
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
}
if (future == null || future.cannotBeReplay()) {
log.debug("Unable to recover future {}\n", future);
return false;
}
future.setState(NettyResponseFuture.STATE.RECONNECTED);
log.debug("Trying to recover request {}\n", future.getNettyRequest());
try {
nextRequest(future.getRequest(), future);
return true;
} catch (IOException iox) {
future.setState(NettyResponseFuture.STATE.CLOSED);
future.abort(iox);
log.error("Remotely Closed, unable to recover", iox);
}
return false;
}
private void markAsDoneAndCacheConnection(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx) throws MalformedURLException {
// We need to make sure everything is OK before adding the connection back to the pool.
try {
future.done(null);
} catch (Throwable t) {
// Never propagate exception once we know we are done.
log.debug(t.getMessage(), t);
}
if (!future.getKeepAlive()) {
closeChannel(ctx);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean isChunked) throws IOException {
if (isChunked && future.getKeepAlive()) {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
} else {
if (future.getKeepAlive() && ctx.getChannel().isReadable()) {
if (!connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(future.getURI()), ctx.getChannel())) {
finishChannel(ctx);
}
}
}
markAsDoneAndCacheConnection(future, ctx);
}
private boolean markChannelNotReadable(final ChannelHandlerContext ctx) {
// Catch any unexpected exception when marking the channel.
ctx.setAttachment(new DiscardEvent());
return true;
}
@SuppressWarnings("unchecked")
private final boolean updateStatusAndInterrupt(AsyncHandler handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateHeadersAndInterrupt(AsyncHandler handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateBodyAndInterrupt(AsyncHandler handler, HttpResponseBodyPart c) throws Exception {
return handler.onBodyPartReceived(c) != STATE.CONTINUE;
}
//Simple marker for stopping publishing bytes.
final static class DiscardEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Channel channel = e.getChannel();
Throwable cause = e.getCause();
NettyResponseFuture<?> future = null;
if (log.isDebugEnabled()) {
log.debug("exceptionCaught", cause);
}
try {
if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) {
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) ctx.getAttachment();
future.attachChannel(null, false);
future.touch();
if (IOException.class.isAssignableFrom(cause.getClass())){
if (config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, null, ctx);
return;
}
} else {
// Close the channel so the recovering can occurs.
try {
ctx.getChannel().close();
} catch (Throwable t) {
; // Swallow.
}
return;
}
}
if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
log.debug("Trying to recover from dead Channel: {}", channel);
return;
}
} else if (ctx.getAttachment() instanceof AsyncCallable) {
future = ((AsyncCallable) ctx.getAttachment()).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
log.debug("Was unable to recover Future: {}", future);
abort(future, cause);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
closeChannel(ctx);
ctx.sendUpstream(e);
}
protected static boolean abortOnConnectCloseException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketChannelImpl")
&& element.getMethodName().equals("checkConnect")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnDisconnectException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("org.jboss.netty.handler.ssl.SslHandler")
&& element.getMethodName().equals("channelDisconnected")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnReadCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("read")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
protected static boolean abortOnWriteCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("write")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int length = (int) request.getContentLength();
if (length == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
length = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (length >= 0) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
}
return length;
}
public static <T> NettyResponseFuture<T> newFuture(URI uri,
Request request,
AsyncHandler<T> asyncHandler,
HttpRequest nettyRequest,
AsyncHttpClientConfig config,
NettyAsyncHttpProvider provider) {
NettyResponseFuture<T> f = new NettyResponseFuture<T>(uri, request, asyncHandler, nettyRequest,
requestTimeout(config, request.getPerRequestConfig()), provider);
if (request.getHeaders().getFirstValue("Expect") != null
&& request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
f.getAndSetWriteBody(false);
}
return f;
}
private class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler asyncHandler;
private final NettyResponseFuture<?> future;
public ProgressListener(boolean notifyHeaders, AsyncHandler asyncHandler, NettyResponseFuture<?> future) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
this.future = future;
}
public void operationComplete(ChannelFuture cf) {
// The write operation failed. If the channel was cached, it means it got asynchronously closed.
// Let's retry a second time.
Throwable cause = cf.getCause();
if (cause != null && future.getState() != NettyResponseFuture.STATE.NEW) {
if (IllegalStateException.class.isAssignableFrom(cause.getClass())) {
log.debug(cause.getMessage(), cause);
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
if (ClosedChannelException.class.isAssignableFrom(cause.getClass())
|| abortOnReadCloseException(cause)
|| abortOnWriteCloseException(cause)) {
if (log.isDebugEnabled()) {
log.debug(cf.getCause() == null ? "" : cf.getCause().getMessage(), cf.getCause());
}
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
} else {
future.abort(cause);
}
return;
}
future.touch();
/**
* We need to make sure we aren't in the middle of an authorization process before publishing events
* as we will re-publish again the same event after the authorization, causing unpredictable behavior.
*/
Realm realm = future.getRequest().getRealm() != null ? future.getRequest().getRealm() : NettyAsyncHttpProvider.this.getConfig().getRealm();
boolean startPublishing = future.isInAuth()
|| realm == null
|| realm.getUsePreemptiveAuth() == true;
if (startPublishing && ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgress(amount, current, total);
}
}
}
/**
* Because some implementation of the ThreadSchedulingService do not clean up cancel task until they try to run
* them, we wrap the task with the future so the when the NettyResponseFuture cancel the reaper future
* this wrapper will release the references to the channel and the nettyResponseFuture immediately. Otherwise,
* the memory referenced this way will only be released after the request timeout period which can be arbitrary long.
*/
private final class ReaperFuture implements Future, Runnable {
private Future scheduledFuture;
private Channel channel;
private NettyResponseFuture<?> nettyResponseFuture;
public ReaperFuture(Channel channel, NettyResponseFuture<?> nettyResponseFuture) {
this.channel = channel;
this.nettyResponseFuture = nettyResponseFuture;
}
public void setScheduledFuture(Future scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
/**
* @Override
*/
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
//cleanup references to allow gc to reclaim memory independently
//of this Future lifecycle
this.channel = null;
this.nettyResponseFuture = null;
return this.scheduledFuture.cancel(mayInterruptIfRunning);
}
/**
* @Override
*/
public Object get() throws InterruptedException, ExecutionException {
return this.scheduledFuture.get();
}
/**
* @Override
*/
public Object get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException,
TimeoutException {
return this.scheduledFuture.get(timeout, unit);
}
/**
* @Override
*/
public boolean isCancelled() {
return this.scheduledFuture.isCancelled();
}
/**
* @Override
*/
public boolean isDone() {
return this.scheduledFuture.isDone();
}
/**
* @Override
*/
public synchronized void run() {
if (isClose.get()) {
return;
}
if (this.nettyResponseFuture != null && this.nettyResponseFuture.hasExpired()) {
log.debug("Request Timeout expired for {}\n", this.nettyResponseFuture);
int requestTimeout = config.getRequestTimeoutInMs();
PerRequestConfig p = this.nettyResponseFuture.getRequest().getPerRequestConfig();
if (p != null && p.getRequestTimeoutInMs() != -1) {
requestTimeout = p.getRequestTimeoutInMs();
}
closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
abort(this.nettyResponseFuture, new TimeoutException(String.format("No response received after %s", requestTimeout)));
this.nettyResponseFuture = null;
this.channel = null;
}
}
}
private abstract class AsyncCallable implements Callable<Object> {
private final NettyResponseFuture<?> future;
public AsyncCallable(NettyResponseFuture<?> future) {
this.future = future;
}
abstract public Object call() throws Exception;
public NettyResponseFuture<?> future() {
return future;
}
}
public static class ThreadLocalBoolean extends ThreadLocal<Boolean> {
private final boolean defaultValue;
public ThreadLocalBoolean() {
this(false);
}
public ThreadLocalBoolean(boolean defaultValue) {
this.defaultValue = defaultValue;
}
@Override
protected Boolean initialValue() {
return defaultValue ? Boolean.TRUE : Boolean.FALSE;
}
}
public static class OptimizedFileRegion implements FileRegion {
private final FileChannel file;
private final RandomAccessFile raf;
private final long position;
private final long count;
private long byteWritten;
public OptimizedFileRegion(RandomAccessFile raf, long position, long count) {
this.raf = raf;
this.file = raf.getChannel();
this.position = position;
this.count = count;
}
public long getPosition() {
return position;
}
public long getCount() {
return count;
}
public long transferTo(WritableByteChannel target, long position) throws IOException {
long count = this.count - position;
if (count < 0 || position < 0) {
throw new IllegalArgumentException(
"position out of range: " + position +
" (expected: 0 - " + (this.count - 1) + ")");
}
if (count == 0) {
return 0L;
}
long bw = file.transferTo(this.position + position, count, target);
byteWritten += bw;
if (byteWritten == raf.length()) {
releaseExternalResources();
}
return bw;
}
public void releaseExternalResources() {
try {
file.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
}
}
private static class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
private final ChannelBuffer content;
private final FileInputStream file;
private int byteRead = 0;
public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ChannelBuffer content, File file) throws IOException {
super(headers);
this.content = content;
if (file != null) {
this.file = new FileInputStream(file);
} else {
this.file = null;
}
}
@Override
public void getBytes(byte[] bytes) {
if (content.writableBytes() != 0) {
content.getBytes(byteRead, bytes);
byteRead += bytes.length;
} else if (file != null) {
try {
byteRead += file.read(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
protected AsyncHttpClientConfig getConfig() {
return config;
}
private static class NonConnectionsPool implements ConnectionsPool<String, Channel> {
public boolean offer(String uri, Channel connection) {
return false;
}
public Channel poll(String uri) {
return null;
}
public boolean removeAll(Channel connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
}
}
}
| src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.http.client.providers.netty;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.RandomAccessBody;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.ntlm.NTLMEngine;
import com.ning.http.client.ntlm.NTLMEngineException;
import com.ning.http.client.providers.netty.spnego.SpnegoEngine;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.CleanupChannelGroup;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.ning.http.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider<HttpResponse> {
private final static String HTTP_HANDLER = "httpHandler";
final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final ChannelGroup openChannels = new
CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if( removed ) {
maxConnections.decrementAndGet();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private final AtomicInteger maxConnections = new AtomicInteger();
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = false;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private final static SpnegoEngine spnegoEngine = new SpnegoEngine();
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() != null
&& NettyAsyncHttpProviderConfig.class.isAssignableFrom(config.getAsyncHttpProviderConfig().getClass())) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig != null && asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO) != null) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
} else {
socketChannelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
config.executorService());
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
this.config = config;
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
configureNetty();
trackConnections = (config.getMaxTotalConnections() != -1);
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s",
maxConnections.get(),
openChannels.toString(),
connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
plainBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
plainBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.EXECUTE_ASYNC_CONNECT) != null) {
executeConnectAsync = true;
} else if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.DISABLE_NESTED_REQUEST) != null) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
secureBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
}
private Channel lookupInCache(URI uri) {
final Channel channel = connectionsPool.poll(AsyncHttpProviderUtils.getBaseUrl(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && HTTPS.equalsIgnoreCase(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it,
* we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getBodyGenerator() != null) {
try {
body = future.getRequest().getBodyGenerator().createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(
new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
}
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null) {
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
writeFuture = channel.write(new BodyFileRegion((RandomAccessBody) body));
} else {
writeFuture = channel.write(new BodyChunkedInput(body));
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int delay = requestTimeout(config, future.getRequest().getPerRequestConfig());
if (delay != -1) {
ReaperFuture reaperFuture = new ReaperFuture(channel, future);
Future scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, delay, 500, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri,
boolean allowConnect, ChannelBuffer buffer) throws IOException {
String method = request.getMethod();
if (allowConnect && ((request.getProxyServer() != null || config.getProxyServer() != null) && HTTPS.equalsIgnoreCase(uri.getScheme()))) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer);
}
@SuppressWarnings("deprecation")
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
StringBuilder path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
ntlmEngine.generateType1Msg("NTLM " + realm.getNtlmDomain(), realm.getNtlmHost()));
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String authServer = proxyServer == null ? AsyncHttpProviderUtils.getBaseUrl(uri) : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(authServer);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else {
nettyRequest.setHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), bodyCharset));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for(Channel channel: openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final Collection<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f,
boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
URI uri = AsyncHttpProviderUtils.createUri(request.getUrl());
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
channel = lookupInCache(uri);
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null &&
!f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = uri.getScheme().compareToIgnoreCase(HTTPS) == 0 && proxyServer == null;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = buildRequest(config, request, uri, false, bufferedBytes);
if (f == null) {
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this);
} else {
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (IllegalStateException ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
throw ex;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && (!connectionsPool.canCacheConnection() ||
(config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()))) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()",t);
}
throw ex;
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
if (trackConnections) {
maxConnections.incrementAndGet();
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = useSSl ? secureBootstrap : plainBootstrap;
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
// Do no enable this with win.
if (System.getProperty("os.name").toLowerCase().indexOf("win") == -1) {
bootstrap.setOption("reuseAddress", asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.REUSE_ADDRESS));
}
try {
if (proxyServer == null || avoidProxy) {
channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), AsyncHttpProviderUtils.getPort(uri)));
} else {
channelFuture = bootstrap.connect(new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()));
}
} catch (Throwable t) {
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
abort(c.future(), new ConnectException("Connect times out"));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) {
int result;
if (perRequestConfig != null) {
int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs();
result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs());
} else {
result = config.getRequestTimeoutInMs();
}
return result;
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
log.debug("Closing Channel {} ", ctx.getChannel());
ctx.setAttachment(new DiscardEvent());
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null) {
return;
}
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
openChannels.remove(ctx.getChannel());
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
// The IdleStateHandler times out and he is calling us.
// We already closed the channel in IdleStateHandler#channelIdle
// so we have nothing to do
return;
}
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler<?> handler = future.getAsyncHandler();
Request request = future.getRequest();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ka.toLowerCase().equals("keep-alive"));
List<String> wwwAuth = getWwwAuth(response.getHeaders());
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, this);
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(handler).request(request).responseStatus(status).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
if (statusCode == 401
&& wwwAuth.size() > 0
&& realm != null
&& !future.getAndSetAuth(true)) {
final RequestBuilder builder = new RequestBuilder(future.getRequest());
future.setState(NettyResponseFuture.STATE.NEW);
if (!future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
builder.setUrl(future.getURI().toString());
}
Realm newRealm = null;
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
// TODO: Refactor and put this code out of here.
// NTLM
if (wwwAuth.get(0).startsWith("NTLM") || (wwwAuth.get(0).startsWith("Negotiate")
&& realm.getAuthScheme() == Realm.AuthScheme.NTLM)) {
String ntlmDomain = proxyServer == null ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = proxyServer == null ? realm.getNtlmHost() : proxyServer.getHost();
String prinicipal = proxyServer == null ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = proxyServer == null ? realm.getPassword() : proxyServer.getPassword();
if (!realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setNtlmMessageType2Received(true)
.build();
future.getAndSetAuth(false);
} else {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(prinicipal, password,
ntlmDomain, ntlmHost, serverChallenge);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.build();
}
// SPNEGO KERBEROS
} else if (wwwAuth.get(0).startsWith("Negotiate") && (realm.getAuthScheme() == Realm.AuthScheme.KERBEROS
|| realm.getAuthScheme() == Realm.AuthScheme.SPNEGO)) {
URI uri = URI.create(request.getUrl());
String authServer = proxyServer == null ? AsyncHttpProviderUtils.getBaseUrl(uri) : proxyServer.getHost();
try {
String challengeHeader = spnegoEngine.generateToken(authServer);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negociate " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(uri.getPath())
.setMethodName(request.getMethod())
.build();
} catch (Throwable throwable) {
abort(future, throwable);
return;
}
} else {
newRealm = new Realm.RealmBuilder().clone(realm)
.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(wwwAuth.get(0))
.build();
}
final Realm nr = newRealm;
log.debug("Sending authentication to {}", request.getUrl());
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
nextRequest(builder.setHeaders(headers).setRealm(nr).build(), future);
return null;
}
};
if (future.getKeepAlive() && response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
if (statusCode == 100) {
future.getAndSetWriteHeaders(false);
future.getAndSetWriteBody(true);
writeRequest(ctx.getChannel(), config, future, nettyRequest);
return;
}
String proxyAuth = response.getHeader(HttpHeaders.Names.PROXY_AUTHENTICATE);
if (statusCode == 407
&& proxyAuth != null
&& future.getRequest().getRealm() != null
&& !future.getAndSetAuth(true)) {
log.debug("Sending proxy authentication to {}", request.getUrl());
nextRequest(future.getRequest(), future);
return;
}
if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)
&& statusCode == 200) {
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
log.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());
if (future.getKeepAlive()) {
future.attachChannel(ctx.getChannel(), true);
}
final RequestBuilder builder = new RequestBuilder(future.getRequest());
try {
log.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
upgradeProtocol(ctx.getChannel().getPipeline(), request.getUrl());
} catch (Throwable ex) {
abort(future, ex);
}
nextRequest(builder.build(), future);
return;
}
boolean redirectEnabled = request.isRedirectEnabled() ? true : config.isRedirectEnabled();
if (redirectEnabled && (statusCode == 302 || statusCode == 301)) {
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
// We must allow 401 handling again.
future.getAndSetAuth(false);
String location = response.getHeader(HttpHeaders.Names.LOCATION);
URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
if (!uri.toString().equalsIgnoreCase(future.getURI().toString())) {
final RequestBuilder builder = new RequestBuilder(future.getRequest());
final URI initialConnectionUri = future.getURI();
final boolean initialConnectionKeepAlive = future.getKeepAlive();
future.setURI(uri);
final String newUrl = uri.toString();
log.debug("Redirecting to {}", newUrl);
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
drainChannel(ctx, future, initialConnectionKeepAlive, initialConnectionUri);
nextRequest(builder.setUrl(newUrl).build(), future);
return null;
}
};
if (response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, status)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(), response, this))) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), response, this));
}
finishUpdate(future, ctx, false);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), response, this));
markAsDoneAndCacheConnection(future, ctx);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
return;
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(), null, this, chunk))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),
future.getHttpResponse(), this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx, !chunk.isLast());
}
}
}
} catch (Exception t) {
if (IOException.class.isAssignableFrom(t.getClass()) && config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(IOException.class.cast(t)).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
}
try {
abort(future, t);
} finally {
finishUpdate(future, ctx, false);
throw t;
}
}
}
private void drainChannel(final ChannelHandlerContext ctx, final NettyResponseFuture<?> future, final boolean keepAlive, final URI uri){
ctx.setAttachment(new AsyncCallable(future) {
public Object call() throws Exception {
if (keepAlive && ctx.getChannel().isReadable()) {
if (!connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(uri), ctx.getChannel())) {
finishChannel(ctx);
}
} else {
finishChannel(ctx);
}
return null;
}
});
}
private FilterContext handleIoException(FilterContext fc, NettyResponseFuture<?> future) {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
return fc;
}
private void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, HttpResponse response, ChannelHandlerContext ctx) throws IOException {
final Request newRequest = fc.getRequest();
future.setAsyncHandler(fc.getAsyncHandler());
future.setState(NettyResponseFuture.STATE.NEW);
future.touch();
log.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(newRequest, future);
return;
}
private List<String> getWwwAuth(List<Entry<String, String>> list) {
ArrayList<String> l = new ArrayList<String>();
for (Entry<String, String> e : list) {
if (e.getKey().equalsIgnoreCase("WWW-Authenticate")) {
l.add(e.getValue());
}
}
return l;
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future) throws IOException {
nextRequest(request, future, true);
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future, final boolean useCache) throws IOException {
execute(request, future, useCache, true, true);
}
private void abort(NettyResponseFuture<?> future, Throwable t) {
if (future.channel() != null && openChannels.contains(future.channel())) {
openChannels.remove(future.channel());
}
if (trackConnections) {
maxConnections.decrementAndGet();
}
log.debug("Aborting Future {}\n", future);
log.debug(t.getMessage(), t);
future.abort(t);
}
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException {
if (p.get(HTTP_HANDLER) != null) {
p.remove(HTTP_HANDLER);
}
if (scheme.startsWith(HTTPS)) {
if (p.get(SSL_HANDLER) == null) {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
} else {
p.addAfter(SSL_HANDLER, HTTP_HANDLER, new HttpClientCodec());
}
} else {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (isClose.get()) {
return;
}
connectionsPool.removeAll(ctx.getChannel());
Exception exception = null;
try {
super.channelClosed(ctx, e);
} catch (Exception ex) {
exception = ex;
}
log.debug("Channel Closed: {} with attachment {}", e.getChannel(), ctx.getAttachment());
if (ctx.getAttachment() instanceof AsyncCallable) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ctx.setAttachment(ac.future());
ac.call();
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
if (config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest() && !future.cannotBeReplay()) {
replayRequest(future, fc, null, ctx);
return;
}
}
if (future != null && !future.isDone()) {
if (!remotelyClosed(ctx.getChannel(), future)) {
abort(future, new IOException("Remotely Closed"));
}
}
} else {
closeChannel(ctx);
}
}
protected boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) {
if (isClose.get()) {
return false;
}
connectionsPool.removeAll(channel);
if (future == null && channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment() != null
&& NettyResponseFuture.class.isAssignableFrom(
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment().getClass())) {
future = (NettyResponseFuture<?>)
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
}
if (future == null || future.cannotBeReplay()) {
log.debug("Unable to recover future {}\n", future);
return false;
}
future.setState(NettyResponseFuture.STATE.RECONNECTED);
log.debug("Trying to recover request {}\n", future.getNettyRequest());
try {
nextRequest(future.getRequest(), future);
return true;
} catch (IOException iox) {
future.setState(NettyResponseFuture.STATE.CLOSED);
future.abort(iox);
log.error("Remotely Closed, unable to recover", iox);
}
return false;
}
private void markAsDoneAndCacheConnection(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx) throws MalformedURLException {
// We need to make sure everything is OK before adding the connection back to the pool.
try {
future.done(null);
} catch (Throwable t) {
// Never propagate exception once we know we are done.
log.debug(t.getMessage(), t);
}
if (!future.getKeepAlive()) {
closeChannel(ctx);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean isChunked) throws IOException {
if (isChunked && future.getKeepAlive()) {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
} else {
if (future.getKeepAlive() && ctx.getChannel().isReadable()) {
if (!connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(future.getURI()), ctx.getChannel())) {
finishChannel(ctx);
}
}
}
markAsDoneAndCacheConnection(future, ctx);
}
private boolean markChannelNotReadable(final ChannelHandlerContext ctx) {
// Catch any unexpected exception when marking the channel.
ctx.setAttachment(new DiscardEvent());
return true;
}
@SuppressWarnings("unchecked")
private final boolean updateStatusAndInterrupt(AsyncHandler handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateHeadersAndInterrupt(AsyncHandler handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateBodyAndInterrupt(AsyncHandler handler, HttpResponseBodyPart c) throws Exception {
return handler.onBodyPartReceived(c) != STATE.CONTINUE;
}
//Simple marker for stopping publishing bytes.
final static class DiscardEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Channel channel = e.getChannel();
Throwable cause = e.getCause();
NettyResponseFuture<?> future = null;
if (log.isDebugEnabled()) {
log.debug("exceptionCaught", cause);
}
try {
if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) {
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) ctx.getAttachment();
future.attachChannel(null, false);
future.touch();
if (IOException.class.isAssignableFrom(cause.getClass())){
if (config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, null, ctx);
return;
}
} else {
// Close the channel so the recovering can occurs.
try {
ctx.getChannel().close();
} catch (Throwable t) {
; // Swallow.
}
return;
}
}
if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
log.debug("Trying to recover from dead Channel: {}", channel);
return;
}
} else if (ctx.getAttachment() instanceof AsyncCallable) {
future = ((AsyncCallable) ctx.getAttachment()).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
log.debug("Was unable to recover Future: {}", future);
abort(future, cause);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
closeChannel(ctx);
ctx.sendUpstream(e);
}
protected static boolean abortOnConnectCloseException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketChannelImpl")
&& element.getMethodName().equals("checkConnect")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnDisconnectException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("org.jboss.netty.handler.ssl.SslHandler")
&& element.getMethodName().equals("channelDisconnected")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnReadCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("read")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
protected static boolean abortOnWriteCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("write")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int length = (int) request.getContentLength();
if (length == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
length = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (length >= 0) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
}
return length;
}
public static <T> NettyResponseFuture<T> newFuture(URI uri,
Request request,
AsyncHandler<T> asyncHandler,
HttpRequest nettyRequest,
AsyncHttpClientConfig config,
NettyAsyncHttpProvider provider) {
NettyResponseFuture<T> f = new NettyResponseFuture<T>(uri, request, asyncHandler, nettyRequest,
requestTimeout(config, request.getPerRequestConfig()), provider);
if (request.getHeaders().getFirstValue("Expect") != null
&& request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
f.getAndSetWriteBody(false);
}
return f;
}
private class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler asyncHandler;
private final NettyResponseFuture<?> future;
public ProgressListener(boolean notifyHeaders, AsyncHandler asyncHandler, NettyResponseFuture<?> future) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
this.future = future;
}
public void operationComplete(ChannelFuture cf) {
// The write operation failed. If the channel was cached, it means it got asynchronously closed.
// Let's retry a second time.
Throwable cause = cf.getCause();
if (cause != null && future.getState() != NettyResponseFuture.STATE.NEW) {
if (IllegalStateException.class.isAssignableFrom(cause.getClass())) {
log.debug(cause.getMessage(), cause);
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
if (ClosedChannelException.class.isAssignableFrom(cause.getClass())
|| abortOnReadCloseException(cause)
|| abortOnWriteCloseException(cause)) {
if (log.isDebugEnabled()) {
log.debug(cf.getCause() == null ? "" : cf.getCause().getMessage(), cf.getCause());
}
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
} else {
future.abort(cause);
}
return;
}
future.touch();
/**
* We need to make sure we aren't in the middle of an authorization process before publishing events
* as we will re-publish again the same event after the authorization, causing unpredictable behavior.
*/
Realm realm = future.getRequest().getRealm() != null ? future.getRequest().getRealm() : NettyAsyncHttpProvider.this.getConfig().getRealm();
boolean startPublishing = future.isInAuth()
|| realm == null
|| realm.getUsePreemptiveAuth() == true;
if (startPublishing && ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgress(amount, current, total);
}
}
}
/**
* Because some implementation of the ThreadSchedulingService do not clean up cancel task until they try to run
* them, we wrap the task with the future so the when the NettyResponseFuture cancel the reaper future
* this wrapper will release the references to the channel and the nettyResponseFuture immediately. Otherwise,
* the memory referenced this way will only be released after the request timeout period which can be arbitrary long.
*/
private final class ReaperFuture implements Future, Runnable {
private Future scheduledFuture;
private Channel channel;
private NettyResponseFuture<?> nettyResponseFuture;
public ReaperFuture(Channel channel, NettyResponseFuture<?> nettyResponseFuture) {
this.channel = channel;
this.nettyResponseFuture = nettyResponseFuture;
}
public void setScheduledFuture(Future scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
/**
* @Override
*/
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
//cleanup references to allow gc to reclaim memory independently
//of this Future lifecycle
this.channel = null;
this.nettyResponseFuture = null;
return this.scheduledFuture.cancel(mayInterruptIfRunning);
}
/**
* @Override
*/
public Object get() throws InterruptedException, ExecutionException {
return this.scheduledFuture.get();
}
/**
* @Override
*/
public Object get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException,
TimeoutException {
return this.scheduledFuture.get(timeout, unit);
}
/**
* @Override
*/
public boolean isCancelled() {
return this.scheduledFuture.isCancelled();
}
/**
* @Override
*/
public boolean isDone() {
return this.scheduledFuture.isDone();
}
/**
* @Override
*/
public synchronized void run() {
if (isClose.get()) {
return;
}
if (this.nettyResponseFuture != null && this.nettyResponseFuture.hasExpired()) {
log.debug("Request Timeout expired for {}\n", this.nettyResponseFuture);
int requestTimeout = config.getRequestTimeoutInMs();
PerRequestConfig p = this.nettyResponseFuture.getRequest().getPerRequestConfig();
if (p != null && p.getRequestTimeoutInMs() != -1) {
requestTimeout = p.getRequestTimeoutInMs();
}
abort(this.nettyResponseFuture, new TimeoutException(String.format("No response received after %s", requestTimeout)));
closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
this.nettyResponseFuture = null;
this.channel = null;
}
}
}
private abstract class AsyncCallable implements Callable<Object> {
private final NettyResponseFuture<?> future;
public AsyncCallable(NettyResponseFuture<?> future) {
this.future = future;
}
abstract public Object call() throws Exception;
public NettyResponseFuture<?> future() {
return future;
}
}
public static class ThreadLocalBoolean extends ThreadLocal<Boolean> {
private final boolean defaultValue;
public ThreadLocalBoolean() {
this(false);
}
public ThreadLocalBoolean(boolean defaultValue) {
this.defaultValue = defaultValue;
}
@Override
protected Boolean initialValue() {
return defaultValue ? Boolean.TRUE : Boolean.FALSE;
}
}
public static class OptimizedFileRegion implements FileRegion {
private final FileChannel file;
private final RandomAccessFile raf;
private final long position;
private final long count;
private long byteWritten;
public OptimizedFileRegion(RandomAccessFile raf, long position, long count) {
this.raf = raf;
this.file = raf.getChannel();
this.position = position;
this.count = count;
}
public long getPosition() {
return position;
}
public long getCount() {
return count;
}
public long transferTo(WritableByteChannel target, long position) throws IOException {
long count = this.count - position;
if (count < 0 || position < 0) {
throw new IllegalArgumentException(
"position out of range: " + position +
" (expected: 0 - " + (this.count - 1) + ")");
}
if (count == 0) {
return 0L;
}
long bw = file.transferTo(this.position + position, count, target);
byteWritten += bw;
if (byteWritten == raf.length()) {
releaseExternalResources();
}
return bw;
}
public void releaseExternalResources() {
try {
file.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
}
}
private static class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
private final ChannelBuffer content;
private final FileInputStream file;
private int byteRead = 0;
public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ChannelBuffer content, File file) throws IOException {
super(headers);
this.content = content;
if (file != null) {
this.file = new FileInputStream(file);
} else {
this.file = null;
}
}
@Override
public void getBytes(byte[] bytes) {
if (content.writableBytes() != 0) {
content.getBytes(byteRead, bytes);
byteRead += bytes.length;
} else if (file != null) {
try {
byteRead += file.read(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
protected AsyncHttpClientConfig getConfig() {
return config;
}
private static class NonConnectionsPool implements ConnectionsPool<String, Channel> {
public boolean offer(String uri, Channel connection) {
return false;
}
public Channel poll(String uri) {
return null;
}
public boolean removeAll(Channel connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
}
}
}
| Fix for https://issues.sonatype.org/browse/AHC-50
("Orphaned open connections after request timeout")
Improve original fix provided by Jenny Loomis
| src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java | Fix for https://issues.sonatype.org/browse/AHC-50 ("Orphaned open connections after request timeout") | <ide><path>rc/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
<ide> }
<ide>
<ide> private void finishChannel(final ChannelHandlerContext ctx) {
<add> ctx.setAttachment(new DiscardEvent());
<add>
<add> if (ctx.getChannel() != null) {
<add> openChannels.remove(ctx.getChannel());
<add> }
<add>
<add> // The channel may have already been removed if a timeout occurred, and this method may be called just after.
<add> if (ctx.getChannel() == null || !ctx.getChannel().isOpen()) {
<add> return;
<add> }
<add>
<ide> log.debug("Closing Channel {} ", ctx.getChannel());
<del>
<del> ctx.setAttachment(new DiscardEvent());
<del>
<del> // The channel may have already been removed if a timeout occurred, and this method may be called just after.
<del> if (ctx.getChannel() == null) {
<del> return;
<del> }
<ide>
<ide> try {
<ide> ctx.getChannel().close();
<ide> } catch (Throwable t) {
<ide> log.debug("Error closing a connection", t);
<ide> }
<del> openChannels.remove(ctx.getChannel());
<ide> }
<ide>
<ide> @Override
<ide> if (p != null && p.getRequestTimeoutInMs() != -1) {
<ide> requestTimeout = p.getRequestTimeoutInMs();
<ide> }
<del>
<add>
<add> closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
<ide> abort(this.nettyResponseFuture, new TimeoutException(String.format("No response received after %s", requestTimeout)));
<del> closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
<ide>
<ide> this.nettyResponseFuture = null;
<ide> this.channel = null; |
|
Java | apache-2.0 | 129b9a3938b423f4622c42adbd6ce6cfd1d7539e | 0 | fooljohnny/elasticsearch,springning/elasticsearch,hechunwen/elasticsearch,ivansun1010/elasticsearch,dongaihua/highlight-elasticsearch,bawse/elasticsearch,combinatorist/elasticsearch,caengcjd/elasticsearch,strapdata/elassandra,Widen/elasticsearch,mnylen/elasticsearch,dataduke/elasticsearch,franklanganke/elasticsearch,andrestc/elasticsearch,martinstuga/elasticsearch,pritishppai/elasticsearch,markllama/elasticsearch,YosuaMichael/elasticsearch,nomoa/elasticsearch,jchampion/elasticsearch,zhiqinghuang/elasticsearch,lmenezes/elasticsearch,Collaborne/elasticsearch,jeteve/elasticsearch,Stacey-Gammon/elasticsearch,scottsom/elasticsearch,HarishAtGitHub/elasticsearch,Charlesdong/elasticsearch,HarishAtGitHub/elasticsearch,andrejserafim/elasticsearch,gmarz/elasticsearch,mortonsykes/elasticsearch,mm0/elasticsearch,fubuki/elasticsearch,qwerty4030/elasticsearch,apepper/elasticsearch,Collaborne/elasticsearch,rajanm/elasticsearch,Chhunlong/elasticsearch,boliza/elasticsearch,xpandan/elasticsearch,snikch/elasticsearch,Fsero/elasticsearch,bestwpw/elasticsearch,girirajsharma/elasticsearch,anti-social/elasticsearch,jaynblue/elasticsearch,markharwood/elasticsearch,abibell/elasticsearch,overcome/elasticsearch,wittyameta/elasticsearch,nellicus/elasticsearch,pranavraman/elasticsearch,artnowo/elasticsearch,Siddartha07/elasticsearch,SergVro/elasticsearch,aparo/elasticsearch,likaiwalkman/elasticsearch,aglne/elasticsearch,sscarduzio/elasticsearch,snikch/elasticsearch,opendatasoft/elasticsearch,petmit/elasticsearch,xingguang2013/elasticsearch,andrestc/elasticsearch,jsgao0/elasticsearch,Liziyao/elasticsearch,ajhalani/elasticsearch,fekaputra/elasticsearch,dataduke/elasticsearch,libosu/elasticsearch,zkidkid/elasticsearch,ulkas/elasticsearch,polyfractal/elasticsearch,vorce/es-metrics,kimimj/elasticsearch,sauravmondallive/elasticsearch,jprante/elasticsearch,ImpressTV/elasticsearch,sarwarbhuiyan/elasticsearch,ydsakyclguozi/elasticsearch,mcku/elasticsearch,JervyShi/elasticsearch,aparo/elasticsearch,lzo/elasticsearch-1,kalburgimanjunath/elasticsearch,hydro2k/elasticsearch,MjAbuz/elasticsearch,tahaemin/elasticsearch,kaneshin/elasticsearch,dylan8902/elasticsearch,s1monw/elasticsearch,jprante/elasticsearch,smflorentino/elasticsearch,chrismwendt/elasticsearch,NBSW/elasticsearch,lightslife/elasticsearch,mnylen/elasticsearch,elancom/elasticsearch,18098924759/elasticsearch,wittyameta/elasticsearch,djschny/elasticsearch,kunallimaye/elasticsearch,fred84/elasticsearch,Widen/elasticsearch,nazarewk/elasticsearch,18098924759/elasticsearch,spiegela/elasticsearch,ThalaivaStars/OrgRepo1,ESamir/elasticsearch,18098924759/elasticsearch,lydonchandra/elasticsearch,sc0ttkclark/elasticsearch,Ansh90/elasticsearch,mjhennig/elasticsearch,raishiv/elasticsearch,alexksikes/elasticsearch,huanzhong/elasticsearch,feiqitian/elasticsearch,infusionsoft/elasticsearch,ThiagoGarciaAlves/elasticsearch,JackyMai/elasticsearch,alexksikes/elasticsearch,opendatasoft/elasticsearch,kalburgimanjunath/elasticsearch,combinatorist/elasticsearch,Stacey-Gammon/elasticsearch,Collaborne/elasticsearch,jsgao0/elasticsearch,JackyMai/elasticsearch,Fsero/elasticsearch,glefloch/elasticsearch,a2lin/elasticsearch,gfyoung/elasticsearch,mrorii/elasticsearch,libosu/elasticsearch,lydonchandra/elasticsearch,fubuki/elasticsearch,ydsakyclguozi/elasticsearch,ouyangkongtong/elasticsearch,hanswang/elasticsearch,schonfeld/elasticsearch,dantuffery/elasticsearch,adrianbk/elasticsearch,beiske/elasticsearch,mmaracic/elasticsearch,vrkansagara/elasticsearch,drewr/elasticsearch,lightslife/elasticsearch,franklanganke/elasticsearch,sauravmondallive/elasticsearch,jango2015/elasticsearch,elancom/elasticsearch,EasonYi/elasticsearch,smflorentino/elasticsearch,pablocastro/elasticsearch,knight1128/elasticsearch,ImpressTV/elasticsearch,andrewvc/elasticsearch,elancom/elasticsearch,zkidkid/elasticsearch,awislowski/elasticsearch,yanjunh/elasticsearch,anti-social/elasticsearch,scottsom/elasticsearch,ivansun1010/elasticsearch,hirdesh2008/elasticsearch,ZTE-PaaS/elasticsearch,dataduke/elasticsearch,tkssharma/elasticsearch,Rygbee/elasticsearch,jpountz/elasticsearch,i-am-Nathan/elasticsearch,wayeast/elasticsearch,gingerwizard/elasticsearch,tkssharma/elasticsearch,alexbrasetvik/elasticsearch,Fsero/elasticsearch,ThiagoGarciaAlves/elasticsearch,koxa29/elasticsearch,amit-shar/elasticsearch,kcompher/elasticsearch,YosuaMichael/elasticsearch,Charlesdong/elasticsearch,ckclark/elasticsearch,truemped/elasticsearch,apepper/elasticsearch,hafkensite/elasticsearch,Flipkart/elasticsearch,caengcjd/elasticsearch,queirozfcom/elasticsearch,s1monw/elasticsearch,lydonchandra/elasticsearch,hafkensite/elasticsearch,iacdingping/elasticsearch,nomoa/elasticsearch,btiernay/elasticsearch,jimczi/elasticsearch,umeshdangat/elasticsearch,adrianbk/elasticsearch,kingaj/elasticsearch,tebriel/elasticsearch,wayeast/elasticsearch,jimhooker2002/elasticsearch,Rygbee/elasticsearch,mcku/elasticsearch,vrkansagara/elasticsearch,strapdata/elassandra,ajhalani/elasticsearch,lmenezes/elasticsearch,vvcephei/elasticsearch,bestwpw/elasticsearch,springning/elasticsearch,uschindler/elasticsearch,huypx1292/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,davidvgalbraith/elasticsearch,btiernay/elasticsearch,weipinghe/elasticsearch,tsohil/elasticsearch,AleksKochev/elasticsearch,chirilo/elasticsearch,rajanm/elasticsearch,coding0011/elasticsearch,sreeramjayan/elasticsearch,pablocastro/elasticsearch,dylan8902/elasticsearch,golubev/elasticsearch,mute/elasticsearch,maddin2016/elasticsearch,davidvgalbraith/elasticsearch,clintongormley/elasticsearch,karthikjaps/elasticsearch,knight1128/elasticsearch,Flipkart/elasticsearch,wangtuo/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,sposam/elasticsearch,Kakakakakku/elasticsearch,areek/elasticsearch,Microsoft/elasticsearch,LewayneNaidoo/elasticsearch,glefloch/elasticsearch,uboness/elasticsearch,springning/elasticsearch,kimimj/elasticsearch,mmaracic/elasticsearch,kalburgimanjunath/elasticsearch,brandonkearby/elasticsearch,nellicus/elasticsearch,btiernay/elasticsearch,palecur/elasticsearch,strapdata/elassandra5-rc,Chhunlong/elasticsearch,iamjakob/elasticsearch,mikemccand/elasticsearch,codebunt/elasticsearch,AndreKR/elasticsearch,sdauletau/elasticsearch,MisterAndersen/elasticsearch,liweinan0423/elasticsearch,ricardocerq/elasticsearch,Helen-Zhao/elasticsearch,mapr/elasticsearch,himanshuag/elasticsearch,zhaocloud/elasticsearch,khiraiwa/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Charlesdong/elasticsearch,cnfire/elasticsearch-1,petmit/elasticsearch,wimvds/elasticsearch,YosuaMichael/elasticsearch,Fsero/elasticsearch,golubev/elasticsearch,slavau/elasticsearch,dataduke/elasticsearch,skearns64/elasticsearch,Rygbee/elasticsearch,likaiwalkman/elasticsearch,zeroctu/elasticsearch,peschlowp/elasticsearch,nilabhsagar/elasticsearch,wayeast/elasticsearch,hydro2k/elasticsearch,sauravmondallive/elasticsearch,Liziyao/elasticsearch,karthikjaps/elasticsearch,areek/elasticsearch,brwe/elasticsearch,tahaemin/elasticsearch,alexksikes/elasticsearch,fooljohnny/elasticsearch,GlenRSmith/elasticsearch,gmarz/elasticsearch,wenpos/elasticsearch,myelin/elasticsearch,sdauletau/elasticsearch,martinstuga/elasticsearch,kevinkluge/elasticsearch,hirdesh2008/elasticsearch,wittyameta/elasticsearch,xuzha/elasticsearch,winstonewert/elasticsearch,loconsolutions/elasticsearch,xingguang2013/elasticsearch,jimczi/elasticsearch,petabytedata/elasticsearch,springning/elasticsearch,LeoYao/elasticsearch,mapr/elasticsearch,libosu/elasticsearch,drewr/elasticsearch,kubum/elasticsearch,mjason3/elasticsearch,nezirus/elasticsearch,ivansun1010/elasticsearch,boliza/elasticsearch,codebunt/elasticsearch,lmtwga/elasticsearch,micpalmia/elasticsearch,andrejserafim/elasticsearch,luiseduardohdbackup/elasticsearch,obourgain/elasticsearch,jchampion/elasticsearch,milodky/elasticsearch,kenshin233/elasticsearch,pritishppai/elasticsearch,dpursehouse/elasticsearch,Shekharrajak/elasticsearch,lmtwga/elasticsearch,Shekharrajak/elasticsearch,mapr/elasticsearch,TonyChai24/ESSource,Chhunlong/elasticsearch,fernandozhu/elasticsearch,ImpressTV/elasticsearch,hirdesh2008/elasticsearch,Fsero/elasticsearch,ThalaivaStars/OrgRepo1,onegambler/elasticsearch,andrejserafim/elasticsearch,LeoYao/elasticsearch,vroyer/elasticassandra,milodky/elasticsearch,shreejay/elasticsearch,pozhidaevak/elasticsearch,onegambler/elasticsearch,jprante/elasticsearch,alexksikes/elasticsearch,nazarewk/elasticsearch,iantruslove/elasticsearch,chrismwendt/elasticsearch,brandonkearby/elasticsearch,avikurapati/elasticsearch,MjAbuz/elasticsearch,AndreKR/elasticsearch,acchen97/elasticsearch,aparo/elasticsearch,mjason3/elasticsearch,mkis-/elasticsearch,szroland/elasticsearch,humandb/elasticsearch,drewr/elasticsearch,masterweb121/elasticsearch,alexkuk/elasticsearch,fforbeck/elasticsearch,VukDukic/elasticsearch,vingupta3/elasticsearch,overcome/elasticsearch,StefanGor/elasticsearch,micpalmia/elasticsearch,liweinan0423/elasticsearch,sc0ttkclark/elasticsearch,fekaputra/elasticsearch,gingerwizard/elasticsearch,rlugojr/elasticsearch,wittyameta/elasticsearch,StefanGor/elasticsearch,ivansun1010/elasticsearch,kunallimaye/elasticsearch,PhaedrusTheGreek/elasticsearch,Uiho/elasticsearch,overcome/elasticsearch,amit-shar/elasticsearch,acchen97/elasticsearch,nknize/elasticsearch,mcku/elasticsearch,hanswang/elasticsearch,nknize/elasticsearch,HarishAtGitHub/elasticsearch,ulkas/elasticsearch,mute/elasticsearch,libosu/elasticsearch,sposam/elasticsearch,humandb/elasticsearch,libosu/elasticsearch,szroland/elasticsearch,LewayneNaidoo/elasticsearch,polyfractal/elasticsearch,himanshuag/elasticsearch,wuranbo/elasticsearch,vietlq/elasticsearch,szroland/elasticsearch,mgalushka/elasticsearch,Kakakakakku/elasticsearch,vietlq/elasticsearch,schonfeld/elasticsearch,knight1128/elasticsearch,hanst/elasticsearch,tkssharma/elasticsearch,nilabhsagar/elasticsearch,jw0201/elastic,mohsinh/elasticsearch,djschny/elasticsearch,koxa29/elasticsearch,jeteve/elasticsearch,codebunt/elasticsearch,Brijeshrpatel9/elasticsearch,iantruslove/elasticsearch,awislowski/elasticsearch,MjAbuz/elasticsearch,aglne/elasticsearch,sreeramjayan/elasticsearch,markwalkom/elasticsearch,slavau/elasticsearch,btiernay/elasticsearch,ESamir/elasticsearch,s1monw/elasticsearch,beiske/elasticsearch,mikemccand/elasticsearch,chrismwendt/elasticsearch,ouyangkongtong/elasticsearch,hafkensite/elasticsearch,nellicus/elasticsearch,nilabhsagar/elasticsearch,markwalkom/elasticsearch,vroyer/elassandra,qwerty4030/elasticsearch,aglne/elasticsearch,tahaemin/elasticsearch,tsohil/elasticsearch,rento19962/elasticsearch,markharwood/elasticsearch,areek/elasticsearch,milodky/elasticsearch,kubum/elasticsearch,SergVro/elasticsearch,slavau/elasticsearch,weipinghe/elasticsearch,mgalushka/elasticsearch,NBSW/elasticsearch,martinstuga/elasticsearch,adrianbk/elasticsearch,camilojd/elasticsearch,yuy168/elasticsearch,obourgain/elasticsearch,tebriel/elasticsearch,ricardocerq/elasticsearch,Shepard1212/elasticsearch,chirilo/elasticsearch,hafkensite/elasticsearch,abibell/elasticsearch,aglne/elasticsearch,AleksKochev/elasticsearch,mjhennig/elasticsearch,javachengwc/elasticsearch,petabytedata/elasticsearch,henakamaMSFT/elasticsearch,wimvds/elasticsearch,socialrank/elasticsearch,masaruh/elasticsearch,mnylen/elasticsearch,robin13/elasticsearch,cnfire/elasticsearch-1,Liziyao/elasticsearch,gfyoung/elasticsearch,yuy168/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,salyh/elasticsearch,areek/elasticsearch,ricardocerq/elasticsearch,mm0/elasticsearch,elasticdog/elasticsearch,Stacey-Gammon/elasticsearch,nrkkalyan/elasticsearch,MichaelLiZhou/elasticsearch,Charlesdong/elasticsearch,JervyShi/elasticsearch,mmaracic/elasticsearch,Asimov4/elasticsearch,artnowo/elasticsearch,pritishppai/elasticsearch,chrismwendt/elasticsearch,NBSW/elasticsearch,avikurapati/elasticsearch,hanst/elasticsearch,marcuswr/elasticsearch-dateline,KimTaehee/elasticsearch,djschny/elasticsearch,zeroctu/elasticsearch,bawse/elasticsearch,bawse/elasticsearch,camilojd/elasticsearch,sposam/elasticsearch,luiseduardohdbackup/elasticsearch,ulkas/elasticsearch,wittyameta/elasticsearch,acchen97/elasticsearch,ouyangkongtong/elasticsearch,geidies/elasticsearch,MisterAndersen/elasticsearch,rhoml/elasticsearch,NBSW/elasticsearch,dpursehouse/elasticsearch,markllama/elasticsearch,lmtwga/elasticsearch,sjohnr/elasticsearch,sneivandt/elasticsearch,petmit/elasticsearch,kimimj/elasticsearch,mute/elasticsearch,alexshadow007/elasticsearch,onegambler/elasticsearch,kevinkluge/elasticsearch,wbowling/elasticsearch,Clairebi/ElasticsearchClone,khiraiwa/elasticsearch,wittyameta/elasticsearch,GlenRSmith/elasticsearch,lzo/elasticsearch-1,strapdata/elassandra5-rc,peschlowp/elasticsearch,Microsoft/elasticsearch,Charlesdong/elasticsearch,tkssharma/elasticsearch,wbowling/elasticsearch,raishiv/elasticsearch,mortonsykes/elasticsearch,KimTaehee/elasticsearch,pranavraman/elasticsearch,lydonchandra/elasticsearch,NBSW/elasticsearch,martinstuga/elasticsearch,rento19962/elasticsearch,MjAbuz/elasticsearch,likaiwalkman/elasticsearch,abibell/elasticsearch,truemped/elasticsearch,sscarduzio/elasticsearch,infusionsoft/elasticsearch,koxa29/elasticsearch,kubum/elasticsearch,tebriel/elasticsearch,overcome/elasticsearch,elancom/elasticsearch,apepper/elasticsearch,queirozfcom/elasticsearch,truemped/elasticsearch,amit-shar/elasticsearch,codebunt/elasticsearch,overcome/elasticsearch,wbowling/elasticsearch,sneivandt/elasticsearch,winstonewert/elasticsearch,ckclark/elasticsearch,palecur/elasticsearch,F0lha/elasticsearch,ydsakyclguozi/elasticsearch,gmarz/elasticsearch,xuzha/elasticsearch,xpandan/elasticsearch,markharwood/elasticsearch,JervyShi/elasticsearch,scorpionvicky/elasticsearch,xuzha/elasticsearch,wangtuo/elasticsearch,himanshuag/elasticsearch,heng4fun/elasticsearch,javachengwc/elasticsearch,apepper/elasticsearch,PhaedrusTheGreek/elasticsearch,markharwood/elasticsearch,vingupta3/elasticsearch,boliza/elasticsearch,xpandan/elasticsearch,Clairebi/ElasticsearchClone,vinsonlou/elasticsearch,rajanm/elasticsearch,vrkansagara/elasticsearch,JSCooke/elasticsearch,vroyer/elasticassandra,uboness/elasticsearch,sneivandt/elasticsearch,maddin2016/elasticsearch,knight1128/elasticsearch,thecocce/elasticsearch,hydro2k/elasticsearch,btiernay/elasticsearch,peschlowp/elasticsearch,pritishppai/elasticsearch,liweinan0423/elasticsearch,loconsolutions/elasticsearch,Rygbee/elasticsearch,fforbeck/elasticsearch,18098924759/elasticsearch,hydro2k/elasticsearch,mjason3/elasticsearch,chrismwendt/elasticsearch,knight1128/elasticsearch,yuy168/elasticsearch,lks21c/elasticsearch,dylan8902/elasticsearch,tcucchietti/elasticsearch,clintongormley/elasticsearch,zhiqinghuang/elasticsearch,jaynblue/elasticsearch,kimchy/elasticsearch,snikch/elasticsearch,heng4fun/elasticsearch,acchen97/elasticsearch,dpursehouse/elasticsearch,IanvsPoplicola/elasticsearch,mm0/elasticsearch,btiernay/elasticsearch,nezirus/elasticsearch,HonzaKral/elasticsearch,pranavraman/elasticsearch,myelin/elasticsearch,lmtwga/elasticsearch,sjohnr/elasticsearch,xpandan/elasticsearch,iamjakob/elasticsearch,C-Bish/elasticsearch,rhoml/elasticsearch,mortonsykes/elasticsearch,diendt/elasticsearch,SergVro/elasticsearch,bawse/elasticsearch,yanjunh/elasticsearch,diendt/elasticsearch,scorpionvicky/elasticsearch,sreeramjayan/elasticsearch,lchennup/elasticsearch,jchampion/elasticsearch,F0lha/elasticsearch,sneivandt/elasticsearch,pranavraman/elasticsearch,cnfire/elasticsearch-1,nrkkalyan/elasticsearch,aglne/elasticsearch,sc0ttkclark/elasticsearch,mkis-/elasticsearch,sjohnr/elasticsearch,cwurm/elasticsearch,kkirsche/elasticsearch,Shepard1212/elasticsearch,jango2015/elasticsearch,mcku/elasticsearch,huanzhong/elasticsearch,smflorentino/elasticsearch,artnowo/elasticsearch,dylan8902/elasticsearch,wbowling/elasticsearch,koxa29/elasticsearch,xingguang2013/elasticsearch,yongminxia/elasticsearch,huanzhong/elasticsearch,nknize/elasticsearch,Shekharrajak/elasticsearch,aparo/elasticsearch,brandonkearby/elasticsearch,codebunt/elasticsearch,janmejay/elasticsearch,jsgao0/elasticsearch,gmarz/elasticsearch,Widen/elasticsearch,sdauletau/elasticsearch,jimczi/elasticsearch,lks21c/elasticsearch,wenpos/elasticsearch,dylan8902/elasticsearch,likaiwalkman/elasticsearch,rento19962/elasticsearch,njlawton/elasticsearch,MetSystem/elasticsearch,vietlq/elasticsearch,alexbrasetvik/elasticsearch,thecocce/elasticsearch,Helen-Zhao/elasticsearch,nomoa/elasticsearch,javachengwc/elasticsearch,mbrukman/elasticsearch,Flipkart/elasticsearch,pritishppai/elasticsearch,myelin/elasticsearch,mute/elasticsearch,vingupta3/elasticsearch,wbowling/elasticsearch,brwe/elasticsearch,wuranbo/elasticsearch,kunallimaye/elasticsearch,henakamaMSFT/elasticsearch,mute/elasticsearch,yuy168/elasticsearch,mohit/elasticsearch,ImpressTV/elasticsearch,Brijeshrpatel9/elasticsearch,mcku/elasticsearch,djschny/elasticsearch,sposam/elasticsearch,yongminxia/elasticsearch,EasonYi/elasticsearch,kevinkluge/elasticsearch,fekaputra/elasticsearch,MichaelLiZhou/elasticsearch,onegambler/elasticsearch,feiqitian/elasticsearch,ThalaivaStars/OrgRepo1,wimvds/elasticsearch,sc0ttkclark/elasticsearch,rajanm/elasticsearch,djschny/elasticsearch,coding0011/elasticsearch,zkidkid/elasticsearch,spiegela/elasticsearch,KimTaehee/elasticsearch,yynil/elasticsearch,bawse/elasticsearch,brandonkearby/elasticsearch,Clairebi/ElasticsearchClone,luiseduardohdbackup/elasticsearch,combinatorist/elasticsearch,zhiqinghuang/elasticsearch,linglaiyao1314/elasticsearch,SergVro/elasticsearch,jeteve/elasticsearch,Uiho/elasticsearch,yynil/elasticsearch,kcompher/elasticsearch,ydsakyclguozi/elasticsearch,Shekharrajak/elasticsearch,mbrukman/elasticsearch,kingaj/elasticsearch,Fsero/elasticsearch,F0lha/elasticsearch,lightslife/elasticsearch,awislowski/elasticsearch,khiraiwa/elasticsearch,MjAbuz/elasticsearch,strapdata/elassandra-test,henakamaMSFT/elasticsearch,luiseduardohdbackup/elasticsearch,nomoa/elasticsearch,easonC/elasticsearch,petabytedata/elasticsearch,KimTaehee/elasticsearch,cwurm/elasticsearch,zkidkid/elasticsearch,weipinghe/elasticsearch,AshishThakur/elasticsearch,iantruslove/elasticsearch,kingaj/elasticsearch,vvcephei/elasticsearch,sauravmondallive/elasticsearch,phani546/elasticsearch,Helen-Zhao/elasticsearch,GlenRSmith/elasticsearch,ivansun1010/elasticsearch,huanzhong/elasticsearch,Uiho/elasticsearch,i-am-Nathan/elasticsearch,elancom/elasticsearch,feiqitian/elasticsearch,mohsinh/elasticsearch,martinstuga/elasticsearch,wenpos/elasticsearch,xingguang2013/elasticsearch,F0lha/elasticsearch,Liziyao/elasticsearch,petmit/elasticsearch,trangvh/elasticsearch,amit-shar/elasticsearch,ulkas/elasticsearch,mohit/elasticsearch,koxa29/elasticsearch,boliza/elasticsearch,kaneshin/elasticsearch,Brijeshrpatel9/elasticsearch,jw0201/elastic,mikemccand/elasticsearch,hanst/elasticsearch,yynil/elasticsearch,opendatasoft/elasticsearch,fernandozhu/elasticsearch,Asimov4/elasticsearch,apepper/elasticsearch,markwalkom/elasticsearch,LeoYao/elasticsearch,nazarewk/elasticsearch,Collaborne/elasticsearch,weipinghe/elasticsearch,scorpionvicky/elasticsearch,javachengwc/elasticsearch,sdauletau/elasticsearch,petabytedata/elasticsearch,golubev/elasticsearch,geidies/elasticsearch,fekaputra/elasticsearch,mute/elasticsearch,sarwarbhuiyan/elasticsearch,Siddartha07/elasticsearch,sscarduzio/elasticsearch,btiernay/elasticsearch,ricardocerq/elasticsearch,xuzha/elasticsearch,nellicus/elasticsearch,franklanganke/elasticsearch,jw0201/elastic,yongminxia/elasticsearch,socialrank/elasticsearch,opendatasoft/elasticsearch,kenshin233/elasticsearch,polyfractal/elasticsearch,weipinghe/elasticsearch,glefloch/elasticsearch,TonyChai24/ESSource,obourgain/elasticsearch,ckclark/elasticsearch,chirilo/elasticsearch,njlawton/elasticsearch,kimimj/elasticsearch,dongjoon-hyun/elasticsearch,kubum/elasticsearch,abibell/elasticsearch,jpountz/elasticsearch,Fsero/elasticsearch,kalburgimanjunath/elasticsearch,szroland/elasticsearch,rento19962/elasticsearch,zeroctu/elasticsearch,JSCooke/elasticsearch,jchampion/elasticsearch,micpalmia/elasticsearch,wimvds/elasticsearch,shreejay/elasticsearch,MichaelLiZhou/elasticsearch,StefanGor/elasticsearch,koxa29/elasticsearch,C-Bish/elasticsearch,milodky/elasticsearch,hanswang/elasticsearch,YosuaMichael/elasticsearch,Flipkart/elasticsearch,anti-social/elasticsearch,F0lha/elasticsearch,sjohnr/elasticsearch,shreejay/elasticsearch,avikurapati/elasticsearch,phani546/elasticsearch,PhaedrusTheGreek/elasticsearch,AndreKR/elasticsearch,wayeast/elasticsearch,salyh/elasticsearch,iantruslove/elasticsearch,kenshin233/elasticsearch,jpountz/elasticsearch,iacdingping/elasticsearch,bestwpw/elasticsearch,libosu/elasticsearch,marcuswr/elasticsearch-dateline,i-am-Nathan/elasticsearch,bestwpw/elasticsearch,iamjakob/elasticsearch,glefloch/elasticsearch,rlugojr/elasticsearch,sdauletau/elasticsearch,Flipkart/elasticsearch,zhiqinghuang/elasticsearch,ImpressTV/elasticsearch,pozhidaevak/elasticsearch,sreeramjayan/elasticsearch,dantuffery/elasticsearch,vietlq/elasticsearch,ThalaivaStars/OrgRepo1,adrianbk/elasticsearch,acchen97/elasticsearch,clintongormley/elasticsearch,andrewvc/elasticsearch,markwalkom/elasticsearch,mohit/elasticsearch,AleksKochev/elasticsearch,rento19962/elasticsearch,springning/elasticsearch,jeteve/elasticsearch,qwerty4030/elasticsearch,alexbrasetvik/elasticsearch,strapdata/elassandra,pablocastro/elasticsearch,mbrukman/elasticsearch,lks21c/elasticsearch,jimhooker2002/elasticsearch,adrianbk/elasticsearch,luiseduardohdbackup/elasticsearch,acchen97/elasticsearch,episerver/elasticsearch,jbertouch/elasticsearch,vroyer/elasticassandra,Ansh90/elasticsearch,markharwood/elasticsearch,jaynblue/elasticsearch,ajhalani/elasticsearch,TonyChai24/ESSource,hirdesh2008/elasticsearch,tkssharma/elasticsearch,SergVro/elasticsearch,scottsom/elasticsearch,dpursehouse/elasticsearch,iamjakob/elasticsearch,yongminxia/elasticsearch,liweinan0423/elasticsearch,rhoml/elasticsearch,strapdata/elassandra-test,lchennup/elasticsearch,schonfeld/elasticsearch,qwerty4030/elasticsearch,iacdingping/elasticsearch,amaliujia/elasticsearch,episerver/elasticsearch,markllama/elasticsearch,strapdata/elassandra-test,kunallimaye/elasticsearch,alexshadow007/elasticsearch,mnylen/elasticsearch,aglne/elasticsearch,uschindler/elasticsearch,wenpos/elasticsearch,girirajsharma/elasticsearch,aparo/elasticsearch,sjohnr/elasticsearch,onegambler/elasticsearch,maddin2016/elasticsearch,kenshin233/elasticsearch,wimvds/elasticsearch,tahaemin/elasticsearch,fernandozhu/elasticsearch,mgalushka/elasticsearch,henakamaMSFT/elasticsearch,kcompher/elasticsearch,pritishppai/elasticsearch,infusionsoft/elasticsearch,nrkkalyan/elasticsearch,Siddartha07/elasticsearch,vorce/es-metrics,ZTE-PaaS/elasticsearch,masaruh/elasticsearch,loconsolutions/elasticsearch,alexshadow007/elasticsearch,a2lin/elasticsearch,MaineC/elasticsearch,anti-social/elasticsearch,mmaracic/elasticsearch,mapr/elasticsearch,lzo/elasticsearch-1,masaruh/elasticsearch,markllama/elasticsearch,kunallimaye/elasticsearch,myelin/elasticsearch,hirdesh2008/elasticsearch,MaineC/elasticsearch,ESamir/elasticsearch,mortonsykes/elasticsearch,hydro2k/elasticsearch,sc0ttkclark/elasticsearch,yynil/elasticsearch,schonfeld/elasticsearch,loconsolutions/elasticsearch,brwe/elasticsearch,kubum/elasticsearch,girirajsharma/elasticsearch,dylan8902/elasticsearch,lchennup/elasticsearch,MisterAndersen/elasticsearch,zhaocloud/elasticsearch,dantuffery/elasticsearch,18098924759/elasticsearch,snikch/elasticsearch,ThiagoGarciaAlves/elasticsearch,socialrank/elasticsearch,C-Bish/elasticsearch,yongminxia/elasticsearch,kcompher/elasticsearch,wayeast/elasticsearch,overcome/elasticsearch,girirajsharma/elasticsearch,himanshuag/elasticsearch,jaynblue/elasticsearch,sarwarbhuiyan/elasticsearch,robin13/elasticsearch,sscarduzio/elasticsearch,slavau/elasticsearch,trangvh/elasticsearch,achow/elasticsearch,Microsoft/elasticsearch,caengcjd/elasticsearch,ajhalani/elasticsearch,lightslife/elasticsearch,alexkuk/elasticsearch,likaiwalkman/elasticsearch,hydro2k/elasticsearch,VukDukic/elasticsearch,peschlowp/elasticsearch,yuy168/elasticsearch,petabytedata/elasticsearch,StefanGor/elasticsearch,jeteve/elasticsearch,sc0ttkclark/elasticsearch,hechunwen/elasticsearch,vietlq/elasticsearch,yongminxia/elasticsearch,obourgain/elasticsearch,humandb/elasticsearch,phani546/elasticsearch,alexkuk/elasticsearch,nrkkalyan/elasticsearch,likaiwalkman/elasticsearch,YosuaMichael/elasticsearch,GlenRSmith/elasticsearch,Chhunlong/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,fekaputra/elasticsearch,Asimov4/elasticsearch,vorce/es-metrics,coding0011/elasticsearch,petabytedata/elasticsearch,socialrank/elasticsearch,ThalaivaStars/OrgRepo1,HarishAtGitHub/elasticsearch,himanshuag/elasticsearch,linglaiyao1314/elasticsearch,abhijitiitr/es,yuy168/elasticsearch,tcucchietti/elasticsearch,jbertouch/elasticsearch,andrejserafim/elasticsearch,easonC/elasticsearch,raishiv/elasticsearch,sarwarbhuiyan/elasticsearch,YosuaMichael/elasticsearch,pablocastro/elasticsearch,hechunwen/elasticsearch,umeshdangat/elasticsearch,AshishThakur/elasticsearch,knight1128/elasticsearch,pablocastro/elasticsearch,wuranbo/elasticsearch,Kakakakakku/elasticsearch,diendt/elasticsearch,ckclark/elasticsearch,jimhooker2002/elasticsearch,zhiqinghuang/elasticsearch,martinstuga/elasticsearch,vvcephei/elasticsearch,marcuswr/elasticsearch-dateline,andrestc/elasticsearch,jbertouch/elasticsearch,abibell/elasticsearch,AndreKR/elasticsearch,fubuki/elasticsearch,rajanm/elasticsearch,dongjoon-hyun/elasticsearch,slavau/elasticsearch,lzo/elasticsearch-1,hechunwen/elasticsearch,rmuir/elasticsearch,s1monw/elasticsearch,mnylen/elasticsearch,peschlowp/elasticsearch,TonyChai24/ESSource,mm0/elasticsearch,fubuki/elasticsearch,qwerty4030/elasticsearch,rhoml/elasticsearch,Ansh90/elasticsearch,Collaborne/elasticsearch,wenpos/elasticsearch,masaruh/elasticsearch,lks21c/elasticsearch,lchennup/elasticsearch,MetSystem/elasticsearch,jprante/elasticsearch,golubev/elasticsearch,elasticdog/elasticsearch,yanjunh/elasticsearch,JackyMai/elasticsearch,liweinan0423/elasticsearch,vietlq/elasticsearch,davidvgalbraith/elasticsearch,mikemccand/elasticsearch,jchampion/elasticsearch,AleksKochev/elasticsearch,salyh/elasticsearch,JSCooke/elasticsearch,kevinkluge/elasticsearch,davidvgalbraith/elasticsearch,fred84/elasticsearch,vrkansagara/elasticsearch,cwurm/elasticsearch,franklanganke/elasticsearch,socialrank/elasticsearch,Clairebi/ElasticsearchClone,clintongormley/elasticsearch,geidies/elasticsearch,Stacey-Gammon/elasticsearch,lightslife/elasticsearch,mrorii/elasticsearch,tebriel/elasticsearch,masterweb121/elasticsearch,njlawton/elasticsearch,Microsoft/elasticsearch,iantruslove/elasticsearch,loconsolutions/elasticsearch,mohsinh/elasticsearch,sscarduzio/elasticsearch,Kakakakakku/elasticsearch,tahaemin/elasticsearch,Uiho/elasticsearch,yanjunh/elasticsearch,rajanm/elasticsearch,achow/elasticsearch,rento19962/elasticsearch,geidies/elasticsearch,mbrukman/elasticsearch,clintongormley/elasticsearch,ZTE-PaaS/elasticsearch,nellicus/elasticsearch,tsohil/elasticsearch,mrorii/elasticsearch,amit-shar/elasticsearch,himanshuag/elasticsearch,sarwarbhuiyan/elasticsearch,LeoYao/elasticsearch,gingerwizard/elasticsearch,MichaelLiZhou/elasticsearch,nellicus/elasticsearch,marcuswr/elasticsearch-dateline,zhiqinghuang/elasticsearch,achow/elasticsearch,masterweb121/elasticsearch,KimTaehee/elasticsearch,mkis-/elasticsearch,luiseduardohdbackup/elasticsearch,mnylen/elasticsearch,adrianbk/elasticsearch,wangyuxue/elasticsearch,mbrukman/elasticsearch,kaneshin/elasticsearch,mortonsykes/elasticsearch,naveenhooda2000/elasticsearch,camilojd/elasticsearch,strapdata/elassandra,spiegela/elasticsearch,rlugojr/elasticsearch,winstonewert/elasticsearch,fooljohnny/elasticsearch,gingerwizard/elasticsearch,heng4fun/elasticsearch,wayeast/elasticsearch,HonzaKral/elasticsearch,KimTaehee/elasticsearch,janmejay/elasticsearch,rmuir/elasticsearch,LeoYao/elasticsearch,Ansh90/elasticsearch,milodky/elasticsearch,Shekharrajak/elasticsearch,queirozfcom/elasticsearch,fred84/elasticsearch,beiske/elasticsearch,wimvds/elasticsearch,TonyChai24/ESSource,Siddartha07/elasticsearch,huypx1292/elasticsearch,jpountz/elasticsearch,strapdata/elassandra-test,polyfractal/elasticsearch,hanst/elasticsearch,ouyangkongtong/elasticsearch,raishiv/elasticsearch,kkirsche/elasticsearch,ckclark/elasticsearch,phani546/elasticsearch,AshishThakur/elasticsearch,sposam/elasticsearch,onegambler/elasticsearch,linglaiyao1314/elasticsearch,Clairebi/ElasticsearchClone,humandb/elasticsearch,caengcjd/elasticsearch,skearns64/elasticsearch,dataduke/elasticsearch,xuzha/elasticsearch,spiegela/elasticsearch,schonfeld/elasticsearch,brwe/elasticsearch,areek/elasticsearch,vroyer/elassandra,sreeramjayan/elasticsearch,pozhidaevak/elasticsearch,winstonewert/elasticsearch,iacdingping/elasticsearch,strapdata/elassandra5-rc,hanswang/elasticsearch,lydonchandra/elasticsearch,PhaedrusTheGreek/elasticsearch,xpandan/elasticsearch,ZTE-PaaS/elasticsearch,ThiagoGarciaAlves/elasticsearch,spiegela/elasticsearch,nazarewk/elasticsearch,mohit/elasticsearch,strapdata/elassandra,fernandozhu/elasticsearch,JackyMai/elasticsearch,pranavraman/elasticsearch,Shepard1212/elasticsearch,alexkuk/elasticsearch,Widen/elasticsearch,jbertouch/elasticsearch,raishiv/elasticsearch,pozhidaevak/elasticsearch,kimchy/elasticsearch,artnowo/elasticsearch,dpursehouse/elasticsearch,wangyuxue/elasticsearch,myelin/elasticsearch,kimchy/elasticsearch,VukDukic/elasticsearch,NBSW/elasticsearch,andrestc/elasticsearch,pozhidaevak/elasticsearch,episerver/elasticsearch,fforbeck/elasticsearch,jango2015/elasticsearch,andrejserafim/elasticsearch,artnowo/elasticsearch,mkis-/elasticsearch,robin13/elasticsearch,Asimov4/elasticsearch,MaineC/elasticsearch,tebriel/elasticsearch,mapr/elasticsearch,mmaracic/elasticsearch,mm0/elasticsearch,hirdesh2008/elasticsearch,opendatasoft/elasticsearch,amaliujia/elasticsearch,C-Bish/elasticsearch,Widen/elasticsearch,amit-shar/elasticsearch,slavau/elasticsearch,queirozfcom/elasticsearch,xpandan/elasticsearch,vrkansagara/elasticsearch,naveenhooda2000/elasticsearch,scottsom/elasticsearch,fred84/elasticsearch,jw0201/elastic,HarishAtGitHub/elasticsearch,ouyangkongtong/elasticsearch,iamjakob/elasticsearch,feiqitian/elasticsearch,amit-shar/elasticsearch,kenshin233/elasticsearch,ydsakyclguozi/elasticsearch,nazarewk/elasticsearch,salyh/elasticsearch,abhijitiitr/es,markwalkom/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,zeroctu/elasticsearch,drewr/elasticsearch,caengcjd/elasticsearch,fooljohnny/elasticsearch,kalimatas/elasticsearch,Rygbee/elasticsearch,LewayneNaidoo/elasticsearch,tkssharma/elasticsearch,yynil/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,schonfeld/elasticsearch,Uiho/elasticsearch,HarishAtGitHub/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,fooljohnny/elasticsearch,brandonkearby/elasticsearch,kalburgimanjunath/elasticsearch,Collaborne/elasticsearch,zhaocloud/elasticsearch,queirozfcom/elasticsearch,fooljohnny/elasticsearch,kingaj/elasticsearch,kevinkluge/elasticsearch,JSCooke/elasticsearch,elasticdog/elasticsearch,yongminxia/elasticsearch,naveenhooda2000/elasticsearch,huanzhong/elasticsearch,hanst/elasticsearch,davidvgalbraith/elasticsearch,chirilo/elasticsearch,achow/elasticsearch,maddin2016/elasticsearch,linglaiyao1314/elasticsearch,heng4fun/elasticsearch,karthikjaps/elasticsearch,amaliujia/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,henakamaMSFT/elasticsearch,nknize/elasticsearch,YosuaMichael/elasticsearch,robin13/elasticsearch,Microsoft/elasticsearch,mkis-/elasticsearch,feiqitian/elasticsearch,MichaelLiZhou/elasticsearch,wangtuo/elasticsearch,IanvsPoplicola/elasticsearch,skearns64/elasticsearch,infusionsoft/elasticsearch,iacdingping/elasticsearch,humandb/elasticsearch,umeshdangat/elasticsearch,MjAbuz/elasticsearch,mm0/elasticsearch,synhershko/elasticsearch,fubuki/elasticsearch,gfyoung/elasticsearch,zeroctu/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,strapdata/elassandra-test,easonC/elasticsearch,nrkkalyan/elasticsearch,infusionsoft/elasticsearch,sdauletau/elasticsearch,Helen-Zhao/elasticsearch,kcompher/elasticsearch,zhaocloud/elasticsearch,PhaedrusTheGreek/elasticsearch,hanst/elasticsearch,fekaputra/elasticsearch,weipinghe/elasticsearch,smflorentino/elasticsearch,andrestc/elasticsearch,schonfeld/elasticsearch,shreejay/elasticsearch,jango2015/elasticsearch,kenshin233/elasticsearch,pablocastro/elasticsearch,Ansh90/elasticsearch,rmuir/elasticsearch,iacdingping/elasticsearch,caengcjd/elasticsearch,a2lin/elasticsearch,fubuki/elasticsearch,mjason3/elasticsearch,kkirsche/elasticsearch,mute/elasticsearch,amaliujia/elasticsearch,weipinghe/elasticsearch,kalimatas/elasticsearch,huanzhong/elasticsearch,umeshdangat/elasticsearch,maddin2016/elasticsearch,vvcephei/elasticsearch,karthikjaps/elasticsearch,hechunwen/elasticsearch,sauravmondallive/elasticsearch,sdauletau/elasticsearch,AndreKR/elasticsearch,IanvsPoplicola/elasticsearch,jaynblue/elasticsearch,chirilo/elasticsearch,tsohil/elasticsearch,wangtuo/elasticsearch,ThalaivaStars/OrgRepo1,acchen97/elasticsearch,easonC/elasticsearch,kkirsche/elasticsearch,lzo/elasticsearch-1,slavau/elasticsearch,micpalmia/elasticsearch,Shepard1212/elasticsearch,ESamir/elasticsearch,mgalushka/elasticsearch,jimhooker2002/elasticsearch,khiraiwa/elasticsearch,kaneshin/elasticsearch,camilojd/elasticsearch,wuranbo/elasticsearch,xuzha/elasticsearch,a2lin/elasticsearch,alexbrasetvik/elasticsearch,jango2015/elasticsearch,TonyChai24/ESSource,lks21c/elasticsearch,AshishThakur/elasticsearch,sarwarbhuiyan/elasticsearch,strapdata/elassandra5-rc,kalimatas/elasticsearch,gmarz/elasticsearch,iantruslove/elasticsearch,nrkkalyan/elasticsearch,Chhunlong/elasticsearch,mikemccand/elasticsearch,Shekharrajak/elasticsearch,KimTaehee/elasticsearch,feiqitian/elasticsearch,camilojd/elasticsearch,heng4fun/elasticsearch,dongjoon-hyun/elasticsearch,jimhooker2002/elasticsearch,Kakakakakku/elasticsearch,markllama/elasticsearch,Rygbee/elasticsearch,Brijeshrpatel9/elasticsearch,NBSW/elasticsearch,mohsinh/elasticsearch,gingerwizard/elasticsearch,s1monw/elasticsearch,lightslife/elasticsearch,golubev/elasticsearch,cnfire/elasticsearch-1,MetSystem/elasticsearch,palecur/elasticsearch,dongjoon-hyun/elasticsearch,EasonYi/elasticsearch,elancom/elasticsearch,sc0ttkclark/elasticsearch,a2lin/elasticsearch,socialrank/elasticsearch,naveenhooda2000/elasticsearch,umeshdangat/elasticsearch,masterweb121/elasticsearch,humandb/elasticsearch,zhaocloud/elasticsearch,wangtuo/elasticsearch,karthikjaps/elasticsearch,brwe/elasticsearch,diendt/elasticsearch,Liziyao/elasticsearch,cnfire/elasticsearch-1,IanvsPoplicola/elasticsearch,infusionsoft/elasticsearch,uschindler/elasticsearch,snikch/elasticsearch,avikurapati/elasticsearch,achow/elasticsearch,sposam/elasticsearch,davidvgalbraith/elasticsearch,cnfire/elasticsearch-1,infusionsoft/elasticsearch,rhoml/elasticsearch,pranavraman/elasticsearch,phani546/elasticsearch,nezirus/elasticsearch,MetSystem/elasticsearch,kubum/elasticsearch,achow/elasticsearch,sjohnr/elasticsearch,zhiqinghuang/elasticsearch,Widen/elasticsearch,mcku/elasticsearch,masterweb121/elasticsearch,jprante/elasticsearch,springning/elasticsearch,kalimatas/elasticsearch,kingaj/elasticsearch,clintongormley/elasticsearch,jpountz/elasticsearch,ulkas/elasticsearch,rlugojr/elasticsearch,mbrukman/elasticsearch,linglaiyao1314/elasticsearch,ckclark/elasticsearch,jsgao0/elasticsearch,episerver/elasticsearch,wuranbo/elasticsearch,rmuir/elasticsearch,andrejserafim/elasticsearch,fred84/elasticsearch,truemped/elasticsearch,Widen/elasticsearch,winstonewert/elasticsearch,kkirsche/elasticsearch,andrestc/elasticsearch,camilojd/elasticsearch,vietlq/elasticsearch,janmejay/elasticsearch,abibell/elasticsearch,mjason3/elasticsearch,jchampion/elasticsearch,geidies/elasticsearch,thecocce/elasticsearch,coding0011/elasticsearch,rmuir/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,vingupta3/elasticsearch,zkidkid/elasticsearch,Collaborne/elasticsearch,EasonYi/elasticsearch,vvcephei/elasticsearch,jsgao0/elasticsearch,kaneshin/elasticsearch,opendatasoft/elasticsearch,lzo/elasticsearch-1,jimhooker2002/elasticsearch,janmejay/elasticsearch,ESamir/elasticsearch,onegambler/elasticsearch,ouyangkongtong/elasticsearch,mjhennig/elasticsearch,karthikjaps/elasticsearch,petmit/elasticsearch,scottsom/elasticsearch,hanswang/elasticsearch,franklanganke/elasticsearch,yuy168/elasticsearch,humandb/elasticsearch,robin13/elasticsearch,Chhunlong/elasticsearch,kunallimaye/elasticsearch,i-am-Nathan/elasticsearch,MetSystem/elasticsearch,vrkansagara/elasticsearch,LeoYao/elasticsearch,uboness/elasticsearch,kevinkluge/elasticsearch,anti-social/elasticsearch,kimimj/elasticsearch,sauravmondallive/elasticsearch,IanvsPoplicola/elasticsearch,Uiho/elasticsearch,wbowling/elasticsearch,springning/elasticsearch,Charlesdong/elasticsearch,phani546/elasticsearch,lchennup/elasticsearch,JervyShi/elasticsearch,kalburgimanjunath/elasticsearch,mnylen/elasticsearch,PhaedrusTheGreek/elasticsearch,thecocce/elasticsearch,sneivandt/elasticsearch,nrkkalyan/elasticsearch,ImpressTV/elasticsearch,i-am-Nathan/elasticsearch,LeoYao/elasticsearch,truemped/elasticsearch,Clairebi/ElasticsearchClone,Helen-Zhao/elasticsearch,cwurm/elasticsearch,nomoa/elasticsearch,dongjoon-hyun/elasticsearch,socialrank/elasticsearch,luiseduardohdbackup/elasticsearch,coding0011/elasticsearch,vroyer/elassandra,bestwpw/elasticsearch,dongaihua/highlight-elasticsearch,elasticdog/elasticsearch,iacdingping/elasticsearch,polyfractal/elasticsearch,fforbeck/elasticsearch,StefanGor/elasticsearch,scorpionvicky/elasticsearch,boliza/elasticsearch,vingupta3/elasticsearch,hechunwen/elasticsearch,abhijitiitr/es,jimhooker2002/elasticsearch,adrianbk/elasticsearch,areek/elasticsearch,rento19962/elasticsearch,awislowski/elasticsearch,kimimj/elasticsearch,Siddartha07/elasticsearch,diendt/elasticsearch,hafkensite/elasticsearch,areek/elasticsearch,alexksikes/elasticsearch,Brijeshrpatel9/elasticsearch,zeroctu/elasticsearch,AshishThakur/elasticsearch,masterweb121/elasticsearch,janmejay/elasticsearch,VukDukic/elasticsearch,hanswang/elasticsearch,vingupta3/elasticsearch,hydro2k/elasticsearch,tahaemin/elasticsearch,mgalushka/elasticsearch,thecocce/elasticsearch,truemped/elasticsearch,kevinkluge/elasticsearch,lmtwga/elasticsearch,salyh/elasticsearch,JackyMai/elasticsearch,hanswang/elasticsearch,diendt/elasticsearch,chirilo/elasticsearch,MisterAndersen/elasticsearch,mjhennig/elasticsearch,mkis-/elasticsearch,geidies/elasticsearch,lchennup/elasticsearch,strapdata/elassandra-test,skearns64/elasticsearch,synhershko/elasticsearch,jimczi/elasticsearch,combinatorist/elasticsearch,EasonYi/elasticsearch,jimczi/elasticsearch,skearns64/elasticsearch,marcuswr/elasticsearch-dateline,mjhennig/elasticsearch,MetSystem/elasticsearch,F0lha/elasticsearch,Rygbee/elasticsearch,kimimj/elasticsearch,fekaputra/elasticsearch,codebunt/elasticsearch,scorpionvicky/elasticsearch,tcucchietti/elasticsearch,C-Bish/elasticsearch,kaneshin/elasticsearch,golubev/elasticsearch,wbowling/elasticsearch,likaiwalkman/elasticsearch,gingerwizard/elasticsearch,Asimov4/elasticsearch,mgalushka/elasticsearch,Brijeshrpatel9/elasticsearch,ZTE-PaaS/elasticsearch,tsohil/elasticsearch,mcku/elasticsearch,snikch/elasticsearch,amaliujia/elasticsearch,18098924759/elasticsearch,wangyuxue/elasticsearch,javachengwc/elasticsearch,jango2015/elasticsearch,nellicus/elasticsearch,zhaocloud/elasticsearch,andrewvc/elasticsearch,pritishppai/elasticsearch,MjAbuz/elasticsearch,obourgain/elasticsearch,rmuir/elasticsearch,Kakakakakku/elasticsearch,huypx1292/elasticsearch,palecur/elasticsearch,ulkas/elasticsearch,SergVro/elasticsearch,shreejay/elasticsearch,jango2015/elasticsearch,mapr/elasticsearch,pablocastro/elasticsearch,Stacey-Gammon/elasticsearch,uschindler/elasticsearch,zeroctu/elasticsearch,Ansh90/elasticsearch,MisterAndersen/elasticsearch,tebriel/elasticsearch,AshishThakur/elasticsearch,markllama/elasticsearch,mmaracic/elasticsearch,njlawton/elasticsearch,trangvh/elasticsearch,kubum/elasticsearch,apepper/elasticsearch,alexshadow007/elasticsearch,Brijeshrpatel9/elasticsearch,aparo/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,xingguang2013/elasticsearch,hirdesh2008/elasticsearch,kingaj/elasticsearch,knight1128/elasticsearch,ckclark/elasticsearch,fforbeck/elasticsearch,beiske/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,avikurapati/elasticsearch,achow/elasticsearch,kcompher/elasticsearch,Shepard1212/elasticsearch,smflorentino/elasticsearch,Ansh90/elasticsearch,naveenhooda2000/elasticsearch,mohsinh/elasticsearch,HarishAtGitHub/elasticsearch,janmejay/elasticsearch,jsgao0/elasticsearch,vingupta3/elasticsearch,dantuffery/elasticsearch,markwalkom/elasticsearch,kunallimaye/elasticsearch,vvcephei/elasticsearch,tcucchietti/elasticsearch,milodky/elasticsearch,tahaemin/elasticsearch,AleksKochev/elasticsearch,jpountz/elasticsearch,franklanganke/elasticsearch,MichaelLiZhou/elasticsearch,andrestc/elasticsearch,GlenRSmith/elasticsearch,amaliujia/elasticsearch,Liziyao/elasticsearch,khiraiwa/elasticsearch,abibell/elasticsearch,mbrukman/elasticsearch,kalimatas/elasticsearch,Chhunlong/elasticsearch,iamjakob/elasticsearch,mohit/elasticsearch,Flipkart/elasticsearch,wimvds/elasticsearch,lmtwga/elasticsearch,nilabhsagar/elasticsearch,nknize/elasticsearch,mrorii/elasticsearch,iamjakob/elasticsearch,dataduke/elasticsearch,jaynblue/elasticsearch,nilabhsagar/elasticsearch,MetSystem/elasticsearch,szroland/elasticsearch,jbertouch/elasticsearch,himanshuag/elasticsearch,TonyChai24/ESSource,yynil/elasticsearch,mrorii/elasticsearch,strapdata/elassandra5-rc,djschny/elasticsearch,vinsonlou/elasticsearch,JervyShi/elasticsearch,elancom/elasticsearch,beiske/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,episerver/elasticsearch,huypx1292/elasticsearch,alexbrasetvik/elasticsearch,lchennup/elasticsearch,ThiagoGarciaAlves/elasticsearch,huypx1292/elasticsearch,huypx1292/elasticsearch,truemped/elasticsearch,EasonYi/elasticsearch,JervyShi/elasticsearch,VukDukic/elasticsearch,fernandozhu/elasticsearch,LewayneNaidoo/elasticsearch,ouyangkongtong/elasticsearch,masterweb121/elasticsearch,karthikjaps/elasticsearch,loconsolutions/elasticsearch,rhoml/elasticsearch,MichaelLiZhou/elasticsearch,cnfire/elasticsearch-1,rlugojr/elasticsearch,ricardocerq/elasticsearch,abhijitiitr/es,18098924759/elasticsearch,linglaiyao1314/elasticsearch,jeteve/elasticsearch,caengcjd/elasticsearch,gfyoung/elasticsearch,awislowski/elasticsearch,Asimov4/elasticsearch,franklanganke/elasticsearch,szroland/elasticsearch,hafkensite/elasticsearch,drewr/elasticsearch,wayeast/elasticsearch,djschny/elasticsearch,yanjunh/elasticsearch,mrorii/elasticsearch,alexshadow007/elasticsearch,ivansun1010/elasticsearch,strapdata/elassandra-test,EasonYi/elasticsearch,HonzaKral/elasticsearch,JSCooke/elasticsearch,girirajsharma/elasticsearch,mm0/elasticsearch,cwurm/elasticsearch,beiske/elasticsearch,elasticdog/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,tkssharma/elasticsearch,palecur/elasticsearch,lightslife/elasticsearch,queirozfcom/elasticsearch,lmtwga/elasticsearch,dantuffery/elasticsearch,anti-social/elasticsearch,LewayneNaidoo/elasticsearch,easonC/elasticsearch,drewr/elasticsearch,markllama/elasticsearch,khiraiwa/elasticsearch,abhijitiitr/es,vorce/es-metrics,Charlesdong/elasticsearch,queirozfcom/elasticsearch,Uiho/elasticsearch,Siddartha07/elasticsearch,combinatorist/elasticsearch,nezirus/elasticsearch,dataduke/elasticsearch,javachengwc/elasticsearch,alexkuk/elasticsearch,bestwpw/elasticsearch,drewr/elasticsearch,girirajsharma/elasticsearch,vorce/es-metrics,apepper/elasticsearch,ThiagoGarciaAlves/elasticsearch,hafkensite/elasticsearch,kcompher/elasticsearch,njlawton/elasticsearch,linglaiyao1314/elasticsearch,PhaedrusTheGreek/elasticsearch,markharwood/elasticsearch,glefloch/elasticsearch,sposam/elasticsearch,Siddartha07/elasticsearch,alexbrasetvik/elasticsearch,masaruh/elasticsearch,mjhennig/elasticsearch,lydonchandra/elasticsearch,smflorentino/elasticsearch,nezirus/elasticsearch,dylan8902/elasticsearch,sarwarbhuiyan/elasticsearch,xingguang2013/elasticsearch,jbertouch/elasticsearch,jeteve/elasticsearch,wittyameta/elasticsearch,xingguang2013/elasticsearch,tcucchietti/elasticsearch,skearns64/elasticsearch,bestwpw/elasticsearch,kkirsche/elasticsearch,huanzhong/elasticsearch,kalburgimanjunath/elasticsearch,kingaj/elasticsearch,ajhalani/elasticsearch,polyfractal/elasticsearch,trangvh/elasticsearch,micpalmia/elasticsearch,lzo/elasticsearch-1,petabytedata/elasticsearch,tsohil/elasticsearch,gfyoung/elasticsearch,MaineC/elasticsearch,AndreKR/elasticsearch,alexkuk/elasticsearch,ydsakyclguozi/elasticsearch,Shekharrajak/elasticsearch,gingerwizard/elasticsearch,iantruslove/elasticsearch,ImpressTV/elasticsearch,trangvh/elasticsearch,mjhennig/elasticsearch,tsohil/elasticsearch,MaineC/elasticsearch,ulkas/elasticsearch,Liziyao/elasticsearch,kenshin233/elasticsearch,ESamir/elasticsearch,easonC/elasticsearch,beiske/elasticsearch,sreeramjayan/elasticsearch,uboness/elasticsearch,jw0201/elastic,jw0201/elastic,mgalushka/elasticsearch,thecocce/elasticsearch,pranavraman/elasticsearch,lydonchandra/elasticsearch | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query.xcontent;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.settings.IndexSettings;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.common.collect.Lists.*;
import static org.elasticsearch.common.lucene.search.Queries.*;
/**
* @author kimchy (shay.banon)
*/
public class BoolQueryParser extends AbstractIndexComponent implements XContentQueryParser {
public static final String NAME = "bool";
@Inject public BoolQueryParser(Index index, @IndexSettings Settings settings) {
super(index, settings);
BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount()));
}
@Override public String[] names() {
return new String[]{NAME};
}
@Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
boolean disableCoord = false;
float boost = 1.0f;
int minimumNumberShouldMatch = -1;
List<BooleanClause> clauses = newArrayList();
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("must".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST));
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST_NOT));
} else if ("should".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.SHOULD));
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("must".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST));
}
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST_NOT));
}
} else if ("should".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.SHOULD));
}
}
} else if (token.isValue()) {
if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) {
disableCoord = parser.booleanValue();
} else if ("minimum_number_should_match".equals(currentFieldName) || "minimumNumberShouldMatch".equals(currentFieldName)) {
minimumNumberShouldMatch = parser.intValue();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
}
}
}
BooleanQuery query = new BooleanQuery(disableCoord);
for (BooleanClause clause : clauses) {
query.add(clause);
}
query.setBoost(boost);
if (minimumNumberShouldMatch != -1) {
query.setMinimumNumberShouldMatch(minimumNumberShouldMatch);
}
return optimizeQuery(fixNegativeQueryIfNeeded(query));
}
}
| modules/elasticsearch/src/main/java/org/elasticsearch/index/query/xcontent/BoolQueryParser.java | /*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query.xcontent;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.settings.IndexSettings;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.common.collect.Lists.*;
import static org.elasticsearch.common.lucene.search.Queries.*;
/**
* @author kimchy (shay.banon)
*/
public class BoolQueryParser extends AbstractIndexComponent implements XContentQueryParser {
public static final String NAME = "bool";
@Inject public BoolQueryParser(Index index, @IndexSettings Settings settings) {
super(index, settings);
}
@Override public String[] names() {
return new String[]{NAME};
}
@Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
boolean disableCoord = false;
float boost = 1.0f;
int minimumNumberShouldMatch = -1;
List<BooleanClause> clauses = newArrayList();
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("must".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST));
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST_NOT));
} else if ("should".equals(currentFieldName)) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.SHOULD));
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("must".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST));
}
} else if ("must_not".equals(currentFieldName) || "mustNot".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.MUST_NOT));
}
} else if ("should".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
clauses.add(new BooleanClause(parseContext.parseInnerQuery(), BooleanClause.Occur.SHOULD));
}
}
} else if (token.isValue()) {
if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) {
disableCoord = parser.booleanValue();
} else if ("minimum_number_should_match".equals(currentFieldName) || "minimumNumberShouldMatch".equals(currentFieldName)) {
minimumNumberShouldMatch = parser.intValue();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
}
}
}
BooleanQuery query = new BooleanQuery(disableCoord);
for (BooleanClause clause : clauses) {
query.add(clause);
}
query.setBoost(boost);
if (minimumNumberShouldMatch != -1) {
query.setMinimumNumberShouldMatch(minimumNumberShouldMatch);
}
return optimizeQuery(fixNegativeQueryIfNeeded(query));
}
}
| Query DSL: Allow to control (globally) the max clause count for `bool` query (defaults to 1024), closes #482.
| modules/elasticsearch/src/main/java/org/elasticsearch/index/query/xcontent/BoolQueryParser.java | Query DSL: Allow to control (globally) the max clause count for `bool` query (defaults to 1024), closes #482. | <ide><path>odules/elasticsearch/src/main/java/org/elasticsearch/index/query/xcontent/BoolQueryParser.java
<ide>
<ide> @Inject public BoolQueryParser(Index index, @IndexSettings Settings settings) {
<ide> super(index, settings);
<add> BooleanQuery.setMaxClauseCount(settings.getAsInt("index.query.bool.max_clause_count", BooleanQuery.getMaxClauseCount()));
<ide> }
<ide>
<ide> @Override public String[] names() { |
|
Java | mit | error: pathspec 'BOJ/16479/Main.java' did not match any file(s) known to git
| 89e596a67c5e6de470567497a6fc3795742cd210 | 1 | ISKU/Algorithm | /*
* Author: Minho Kim (ISKU)
* Date: November 21, 2018
* E-mail: [email protected]
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/16479
*/
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double k = sc.nextDouble();
double d1 = sc.nextDouble();
double d2 = sc.nextDouble();
System.out.printf("%.6f", (k * k) - ((d1 - d2) * (d1 - d2) / 4));
}
} | BOJ/16479/Main.java | BOJ #16479: 컵라면 측정하기
| BOJ/16479/Main.java | BOJ #16479: 컵라면 측정하기 | <ide><path>OJ/16479/Main.java
<add>/*
<add> * Author: Minho Kim (ISKU)
<add> * Date: November 21, 2018
<add> * E-mail: [email protected]
<add> *
<add> * https://github.com/ISKU/Algorithm
<add> * https://www.acmicpc.net/problem/16479
<add> */
<add>
<add>import java.util.*;
<add>
<add>public class Main {
<add> public static void main(String[] args) {
<add> Scanner sc = new Scanner(System.in);
<add> double k = sc.nextDouble();
<add> double d1 = sc.nextDouble();
<add> double d2 = sc.nextDouble();
<add> System.out.printf("%.6f", (k * k) - ((d1 - d2) * (d1 - d2) / 4));
<add> }
<add>} |
|
Java | mit | 1ed9922ac7b19ee6f52ceb2e3946dd991683b841 | 0 | coinspark/sparkbit,ychaim/sparkbit,ychaim/sparkbit,coinspark/sparkbit,coinspark/sparkbit,ychaim/sparkbit | /*
* SparkBit
*
* Copyright 2014 Coin Sciences Ltd
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sparkbit.jsonrpc;
import java.io.IOException;
import com.bitmechanic.barrister.*;
import com.bitmechanic.barrister.Contract;
import com.bitmechanic.barrister.Server;
import com.bitmechanic.barrister.JacksonSerializer;
import org.sparkbit.jsonrpc.autogen.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SparkBitServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(SparkBitServlet.class);
private Contract contract;
private Server server;
private JacksonSerializer serializer;
private static long counter = 0;
public SparkBitServlet() {
// Serialize requests/responses as JSON using Jackson
serializer = new JacksonSerializer();
}
public void init(ServletConfig config) throws ServletException {
try {
// SIMON: EDIT JSON FILE NAME
// Load the contract from the IDL JSON file
contract = Contract.load(getClass().getResourceAsStream("/sparkbit_api.json"));
server = new Server(contract);
// SIMON: EDIT NAME OF CLASS
// Register our service implementation
server.addHandler(sparkbit.class, new SparkBitJSONRPCServiceImpl());
}
catch (Exception e) {
throw new ServletException(e);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
try {
long requestID = ++counter;
log.info("----------------------------------------------------");
log.info("*** Request # " + requestID + " RECEIVED");
final StopWatch stopwatch = new StopWatch();
stopwatch.start();
InputStream is = req.getInputStream();
OutputStream os = resp.getOutputStream();
resp.addHeader("Content-Type", "application/json");
// This will deserialize the request and invoke
// our ContactServiceImpl code based on the method and params
// specified in the request. The result, including any
// RpcException (if thrown), will be serialized to the OutputStream
// server.call(serializer, is, os);
log.info("remote host = " + req.getRemoteHost());
log.info("request URL = " + req.getRequestURL().toString());
// log.info("session ID = " + req.getRequestedSessionId());
// We use a modified version of the above call so that we can filter 'stop' for localhost
mycall(req.getRemoteHost(), server, serializer, is, os);
is.close();
os.close();
stopwatch.stop();
log.info("*** Request # " + requestID + " FINISHED - processing time = " + stopwatch);
}
catch (Exception e) {
throw new ServletException(e);
}
}
/**
* Reads a RpcRequest from the input stream, deserializes it, invokes the
* matching handler method, serializes the result, and writes it to the
* output stream.
*
* @param remoteHost the host of the caller
* @param server The jetty server we will pass the call onto
* @param ser Serializer to use to decode the request from the input stream,
* and serialize the result to the the output stream
* @param is InputStream to read the request from
* @param os OutputStream to write the response to
* @throws IOException If there is a problem reading or writing to either
* stream, or if the request cannot be deserialized.
*/
@SuppressWarnings("unchecked")
public void mycall(String remoteHost, Server server, Serializer ser, InputStream is, OutputStream os)
throws IOException {
Object obj = null;
try {
obj = ser.readMapOrList(is);
} catch (Exception e) {
String msg = "Unable to deserialize request: " + e.getMessage();
ser.write(new RpcResponse(null, RpcException.Error.PARSE.exc(msg)).marshal(), os);
return;
}
if (obj instanceof List) {
List list = (List) obj;
List respList = new ArrayList();
for (Object o : list) {
RpcRequest rpcReq = new RpcRequest((Map) o);
// System.out.println(">>>> LIST CAST: (Map) o = " + (Map)o );
respList.add(server.call(rpcReq).marshal()); // modified
}
ser.write(respList, os);
} else if (obj instanceof Map) {
// Modified: only allow stop method if remote host is actually localhost 127.0.0.1
String method = (String)((Map)obj).get("method");
// log.info("method = " + method);
/* Map<Object, Object> m = (Map)obj;
for (Map.Entry<Object, Object> entrySet : m.entrySet()) {
Object key = entrySet.getKey();
Object value = entrySet.getValue();
log.info(key + " = " + value);
}
*/
if (method.equals("sparkbit.stop") && !remoteHost.equals("127.0.0.1")) {
ser.write(new RpcResponse(null, RpcException.Error.INVALID_REQ.exc("Invalid Request - You can only invoke stop from localhost")).marshal(), os);
} else {
RpcRequest rpcReq = new RpcRequest((Map) obj);
ser.write(server.call(rpcReq).marshal(), os); // modified
}
} else {
ser.write(new RpcResponse(null, RpcException.Error.INVALID_REQ.exc("Invalid Request")).marshal(), os);
}
}
}
| src/main/java/org/sparkbit/jsonrpc/SparkBitServlet.java | /*
* SparkBit
*
* Copyright 2014 Coin Sciences Ltd
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sparkbit.jsonrpc;
import java.io.IOException;
import com.bitmechanic.barrister.*;
import com.bitmechanic.barrister.Contract;
import com.bitmechanic.barrister.Server;
import com.bitmechanic.barrister.JacksonSerializer;
import org.sparkbit.jsonrpc.autogen.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SparkBitServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(SparkBitServlet.class);
private Contract contract;
private Server server;
private JacksonSerializer serializer;
private static long counter = 0;
public SparkBitServlet() {
// Serialize requests/responses as JSON using Jackson
serializer = new JacksonSerializer();
}
public void init(ServletConfig config) throws ServletException {
try {
// SIMON: EDIT JSON FILE NAME
// Load the contract from the IDL JSON file
contract = Contract.load(getClass().getResourceAsStream("/sparkbit_api.json"));
server = new Server(contract);
// SIMON: EDIT NAME OF CLASS
// Register our service implementation
server.addHandler(sparkbit.class, new SparkBitJSONRPCServiceImpl());
}
catch (Exception e) {
throw new ServletException(e);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
try {
long requestID = ++counter;
log.info("----------------------------------------------------");
log.info("*** Request # " + requestID + " RECEIVED");
final StopWatch stopwatch = new StopWatch();
stopwatch.start();
InputStream is = req.getInputStream();
OutputStream os = resp.getOutputStream();
resp.addHeader("Content-Type", "application/json");
// This will deserialize the request and invoke
// our ContactServiceImpl code based on the method and params
// specified in the request. The result, including any
// RpcException (if thrown), will be serialized to the OutputStream
// server.call(serializer, is, os);
log.info("remote host = " + req.getRemoteHost());
log.info("request URL = " + req.getRequestURL().toString());
// log.info("session ID = " + req.getRequestedSessionId());
// We use a modified version of the above call so that we can filter 'stop' for localhost
mycall(req.getRemoteHost(), server, serializer, is, os);
is.close();
os.close();
stopwatch.stop();
log.info("*** Request # " + requestID + " FINISHED - processing time = " + stopwatch);
}
catch (Exception e) {
throw new ServletException(e);
}
}
/**
* Reads a RpcRequest from the input stream, deserializes it, invokes the
* matching handler method, serializes the result, and writes it to the
* output stream.
*
* @param remoteHost the host of the caller
* @param server The jetty server we will pass the call onto
* @param ser Serializer to use to decode the request from the input stream,
* and serialize the result to the the output stream
* @param is InputStream to read the request from
* @param os OutputStream to write the response to
* @throws IOException If there is a problem reading or writing to either
* stream, or if the request cannot be deserialized.
*/
@SuppressWarnings("unchecked")
public void mycall(String remoteHost, Server server, Serializer ser, InputStream is, OutputStream os)
throws IOException {
Object obj = null;
try {
obj = ser.readMapOrList(is);
} catch (Exception e) {
String msg = "Unable to deserialize request: " + e.getMessage();
ser.write(new RpcResponse(null, RpcException.Error.PARSE.exc(msg)).marshal(), os);
return;
}
if (obj instanceof List) {
List list = (List) obj;
List respList = new ArrayList();
for (Object o : list) {
RpcRequest rpcReq = new RpcRequest((Map) o);
// System.out.println(">>>> LIST CAST: (Map) o = " + (Map)o );
respList.add(server.call(rpcReq).marshal()); // modified
}
ser.write(respList, os);
} else if (obj instanceof Map) {
// Modified: only allow stop method if remote host is actually localhost 127.0.0.1
String method = (String)((Map)obj).get("method");
log.info("method = " + method);
if (method.equals("sparkbit.stop") && !remoteHost.equals("127.0.0.1")) {
ser.write(new RpcResponse(null, RpcException.Error.INVALID_REQ.exc("Invalid Request - You can only invoke stop from localhost")).marshal(), os);
} else {
RpcRequest rpcReq = new RpcRequest((Map) obj);
ser.write(server.call(rpcReq).marshal(), os); // modified
}
} else {
ser.write(new RpcResponse(null, RpcException.Error.INVALID_REQ.exc("Invalid Request")).marshal(), os);
}
}
} | Added but commented out some debug statements.
| src/main/java/org/sparkbit/jsonrpc/SparkBitServlet.java | Added but commented out some debug statements. | <ide><path>rc/main/java/org/sparkbit/jsonrpc/SparkBitServlet.java
<ide> // Modified: only allow stop method if remote host is actually localhost 127.0.0.1
<ide> String method = (String)((Map)obj).get("method");
<ide>
<del> log.info("method = " + method);
<add>// log.info("method = " + method);
<add>/* Map<Object, Object> m = (Map)obj;
<add> for (Map.Entry<Object, Object> entrySet : m.entrySet()) {
<add> Object key = entrySet.getKey();
<add> Object value = entrySet.getValue();
<add> log.info(key + " = " + value);
<add> }
<add>*/
<ide>
<ide> if (method.equals("sparkbit.stop") && !remoteHost.equals("127.0.0.1")) {
<ide> ser.write(new RpcResponse(null, RpcException.Error.INVALID_REQ.exc("Invalid Request - You can only invoke stop from localhost")).marshal(), os); |
|
JavaScript | mit | 943016ccb937bb40c30d8f1ab13b40c4dc71701a | 0 | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { FormModal, useNotifications, useApi, useLoading, useModals } from 'react-components';
import { setPaymentMethod } from 'proton-shared/lib/api/payments';
import { PAYMENT_METHOD_TYPES } from 'proton-shared/lib/constants';
import Card from './Card';
import useCard from './useCard';
import toDetails from './toDetails';
import { handlePaymentToken } from './paymentTokenHelper';
const EditCardModal = ({ card: existingCard, onClose, onChange, ...rest }) => {
const api = useApi();
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const { createModal } = useModals();
const title = existingCard ? c('Title').t`Edit credit/debit card` : c('Title').t`Add credit/debit card`;
const { card, updateCard, errors, isValid } = useCard(existingCard);
const handleSubmit = async (event) => {
if (!isValid) {
event.preventDefault();
return;
}
// 1 CHF to allow card authorizations
const { Payment } = await handlePaymentToken({
params: {
Amount: 100,
Currency: 'CHF',
Payment: {
Type: PAYMENT_METHOD_TYPES.CARD,
Details: toDetails(card)
}
},
api,
createModal
});
await api(setPaymentMethod(Payment));
await onChange();
onClose();
createNotification({ text: c('Success').t`Payment method updated` });
};
return (
<FormModal
small
onSubmit={() => withLoading(handleSubmit())}
onClose={onClose}
title={title}
loading={loading}
submit={c('Action').t`Save`}
{...rest}
>
<Card card={card} errors={errors} onChange={updateCard} loading={loading} />
</FormModal>
);
};
EditCardModal.propTypes = {
card: PropTypes.object,
onClose: PropTypes.func,
onChange: PropTypes.func.isRequired
};
export default EditCardModal;
| packages/components/containers/payments/EditCardModal.js | import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { FormModal, useNotifications, useApi, useLoading, useModals } from 'react-components';
import { setPaymentMethod } from 'proton-shared/lib/api/payments';
import { PAYMENT_METHOD_TYPES } from 'proton-shared/lib/constants';
import Card from './Card';
import useCard from './useCard';
import toDetails from './toDetails';
import { handlePaymentToken } from './paymentTokenHelper';
const EditCardModal = ({ card: existingCard, onClose, onChange, ...rest }) => {
const api = useApi();
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const { createModal } = useModals();
const title = existingCard ? c('Title').t`Edit credit/debit card` : c('Title').t`Add credit/debit card`;
const { card, updateCard, errors, isValid } = useCard(existingCard);
const handleSubmit = async (event) => {
if (!isValid) {
event.preventDefault();
return;
}
// 1 CHF to allow card authorizations
const { Payment } = handlePaymentToken({
params: {
Amount: 100,
Currency: 'CHF',
Payment: {
Type: PAYMENT_METHOD_TYPES.CARD,
Details: toDetails(card)
}
},
api,
createModal
});
await api(setPaymentMethod(Payment));
await onChange();
onClose();
createNotification({ text: c('Success').t`Payment method updated` });
};
return (
<FormModal
small
onSubmit={() => withLoading(handleSubmit())}
onClose={onClose}
title={title}
loading={loading}
submit={c('Action').t`Save`}
{...rest}
>
<Card card={card} errors={errors} onChange={updateCard} loading={loading} />
</FormModal>
);
};
EditCardModal.propTypes = {
card: PropTypes.object,
onClose: PropTypes.func,
onChange: PropTypes.func.isRequired
};
export default EditCardModal;
| Hotfix - handlePaymentToken returns a Promise
| packages/components/containers/payments/EditCardModal.js | Hotfix - handlePaymentToken returns a Promise | <ide><path>ackages/components/containers/payments/EditCardModal.js
<ide> return;
<ide> }
<ide> // 1 CHF to allow card authorizations
<del> const { Payment } = handlePaymentToken({
<add> const { Payment } = await handlePaymentToken({
<ide> params: {
<ide> Amount: 100,
<ide> Currency: 'CHF', |
|
Java | apache-2.0 | 12c5e198c1f4ea3e4818db1cf87fb93dcb2fb113 | 0 | google/auto,eamonnmcmanus/auto,eamonnmcmanus/auto,eamonnmcmanus/auto,google/auto,google/auto | /*
* Copyright 2014 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.value;
import static com.google.common.base.StandardSystemProperty.JAVA_HOME;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.auto.value.processor.AutoAnnotationProcessor;
import com.google.auto.value.processor.AutoOneOfProcessor;
import com.google.auto.value.processor.AutoValueProcessor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.processing.Processor;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests that we can compile our AutoValue tests using the Eclipse batch compiler. Since the tests
* exercise many AutoValue subtleties, the ability to compile them all is a good indication of
* Eclipse support.
*/
@RunWith(JUnit4.class)
public class CompileWithEclipseTest {
private static final String SOURCE_ROOT = System.getProperty("basedir");
@BeforeClass
public static void setSourceRoot() {
assertWithMessage("basedir property must be set - test must be run from Maven")
.that(SOURCE_ROOT).isNotNull();
}
public @Rule TemporaryFolder tmp = new TemporaryFolder();
private static final ImmutableSet<String> IGNORED_TEST_FILES =
ImmutableSet.of("AutoValueNotEclipseTest.java", "CompileWithEclipseTest.java");
private static final Predicate<File> JAVA_FILE =
f -> f.getName().endsWith(".java") && !IGNORED_TEST_FILES.contains(f.getName());
private static final Predicate<File> JAVA8_TEST =
f -> f.getName().equals("AutoValueJava8Test.java")
|| f.getName().equals("AutoOneOfJava8Test.java")
|| f.getName().equals("EmptyExtension.java");
@Test
public void compileWithEclipseJava6() throws Exception {
compileWithEclipse("6", JAVA_FILE.and(JAVA8_TEST.negate()));
}
@Test
public void compileWithEclipseJava8() throws Exception {
compileWithEclipse("8", JAVA_FILE);
}
private void compileWithEclipse(String version, Predicate<File> predicate) throws IOException {
File sourceRootFile = new File(SOURCE_ROOT);
File javaDir = new File(sourceRootFile, "src/main/java");
File javatestsDir = new File(sourceRootFile, "src/test/java");
Set<File> sources =
new ImmutableSet.Builder<File>()
.addAll(filesUnderDirectory(javaDir, predicate))
.addAll(filesUnderDirectory(javatestsDir, predicate))
.build();
assertThat(sources).isNotEmpty();
JavaCompiler compiler = new EclipseCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// This hack is only needed in a Google-internal Java 8 environment where symbolic links make it
// hard for ecj to find the boot class path. Elsewhere it is unnecessary but harmless. Notably,
// on Java 9+ there is no rt.jar. There, fileManager.getLocation(PLATFORM_CLASS_PATH) returns
// null, because the relevant classes are in modules inside
// fileManager.getLocation(SYSTEM_MODULES).
File rtJar = new File(JAVA_HOME.value() + "/lib/rt.jar");
if (rtJar.exists()) {
List<File> bootClassPath = ImmutableList.<File>builder()
.add(rtJar)
.addAll(fileManager.getLocation(StandardLocation.PLATFORM_CLASS_PATH))
.build();
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
}
Iterable<? extends JavaFileObject> sourceFileObjects =
fileManager.getJavaFileObjectsFromFiles(sources);
String outputDir = tmp.getRoot().toString();
ImmutableList<String> options =
ImmutableList.of("-d", outputDir, "-s", outputDir, "-source", version, "-target", version);
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, null, options, null, sourceFileObjects);
// Explicitly supply an empty list of extensions for AutoValueProcessor, because otherwise this
// test will pick up a test one and get confused.
AutoValueProcessor autoValueProcessor = new AutoValueProcessor(ImmutableList.of());
ImmutableList<? extends Processor> processors =
ImmutableList.of(
autoValueProcessor, new AutoOneOfProcessor(), new AutoAnnotationProcessor());
task.setProcessors(processors);
assertWithMessage("Compilation should succeed").that(task.call()).isTrue();
}
private static ImmutableSet<File> filesUnderDirectory(File dir, Predicate<File> predicate)
throws IOException {
assertWithMessage(dir.toString()).that(dir.isDirectory()).isTrue();
try (Stream<Path> paths = Files.walk(dir.toPath())) {
return paths.map(Path::toFile).filter(predicate).collect(toImmutableSet());
}
}
}
| value/src/it/functional/src/test/java/com/google/auto/value/CompileWithEclipseTest.java | /*
* Copyright 2014 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.value;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.auto.value.processor.AutoAnnotationProcessor;
import com.google.auto.value.processor.AutoOneOfProcessor;
import com.google.auto.value.processor.AutoValueProcessor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.processing.Processor;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/**
* Tests that we can compile our AutoValue tests using the Eclipse batch compiler. Since the tests
* exercise many AutoValue subtleties, the ability to compile them all is a good indication of
* Eclipse support.
*/
public class CompileWithEclipseTest {
private static final String SOURCE_ROOT = System.getProperty("basedir");
@BeforeClass
public static void setSourceRoot() {
assertWithMessage("basedir property must be set - test must be run from Maven")
.that(SOURCE_ROOT).isNotNull();
}
public @Rule TemporaryFolder tmp = new TemporaryFolder();
private static final ImmutableSet<String> IGNORED_TEST_FILES =
ImmutableSet.of("AutoValueNotEclipseTest.java", "CompileWithEclipseTest.java");
private static final Predicate<File> JAVA_FILE =
f -> f.getName().endsWith(".java") && !IGNORED_TEST_FILES.contains(f.getName());
private static final Predicate<File> JAVA8_TEST =
f -> f.getName().equals("AutoValueJava8Test.java")
|| f.getName().equals("AutoOneOfJava8Test.java")
|| f.getName().equals("EmptyExtension.java");
@Test
public void compileWithEclipseJava6() throws Exception {
compileWithEclipse("6", JAVA_FILE.and(JAVA8_TEST.negate()));
}
@Test
public void compileWithEclipseJava8() throws Exception {
compileWithEclipse("8", JAVA_FILE);
}
private void compileWithEclipse(String version, Predicate<File> predicate) throws IOException {
File sourceRootFile = new File(SOURCE_ROOT);
File javaDir = new File(sourceRootFile, "src/main/java");
File javatestsDir = new File(sourceRootFile, "src/test/java");
Set<File> sources =
new ImmutableSet.Builder<File>()
.addAll(filesUnderDirectory(javaDir, predicate))
.addAll(filesUnderDirectory(javatestsDir, predicate))
.build();
assertThat(sources).isNotEmpty();
JavaCompiler compiler = new EclipseCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// This hack is only needed in a Google-internal Java 8 environment where symbolic links make it
// hard for ecj to find the boot class path. Elsewhere it is unnecessary but harmless. Notably,
// on Java 9+ there is no rt.jar. There, fileManager.getLocation(PLATFORM_CLASS_PATH) returns
// null, because the relevant classes are in modules inside
// fileManager.getLocation(SYSTEM_MODULES).
File rtJar = new File(System.getProperty("java.home") + "/lib/rt.jar");
if (rtJar.exists()) {
List<File> bootClassPath = ImmutableList.<File>builder()
.add(rtJar)
.addAll(fileManager.getLocation(StandardLocation.PLATFORM_CLASS_PATH))
.build();
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
}
Iterable<? extends JavaFileObject> sourceFileObjects =
fileManager.getJavaFileObjectsFromFiles(sources);
String outputDir = tmp.getRoot().toString();
ImmutableList<String> options =
ImmutableList.of("-d", outputDir, "-s", outputDir, "-source", version, "-target", version);
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, null, options, null, sourceFileObjects);
// Explicitly supply an empty list of extensions for AutoValueProcessor, because otherwise this
// test will pick up a test one and get confused.
AutoValueProcessor autoValueProcessor = new AutoValueProcessor(ImmutableList.of());
ImmutableList<? extends Processor> processors =
ImmutableList.of(
autoValueProcessor, new AutoOneOfProcessor(), new AutoAnnotationProcessor());
task.setProcessors(processors);
assertWithMessage("Compilation should succeed").that(task.call()).isTrue();
}
private static ImmutableSet<File> filesUnderDirectory(File dir, Predicate<File> predicate)
throws IOException {
assertWithMessage(dir.toString()).that(dir.isDirectory()).isTrue();
return Files.walk(dir.toPath()).map(Path::toFile).filter(predicate).collect(toImmutableSet());
}
}
| Use try-with-resources for Files.walk. Otherwise the Stream is not closed correctly.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=300791938
| value/src/it/functional/src/test/java/com/google/auto/value/CompileWithEclipseTest.java | Use try-with-resources for Files.walk. Otherwise the Stream is not closed correctly. | <ide><path>alue/src/it/functional/src/test/java/com/google/auto/value/CompileWithEclipseTest.java
<ide> */
<ide> package com.google.auto.value;
<ide>
<add>import static com.google.common.base.StandardSystemProperty.JAVA_HOME;
<ide> import static com.google.common.collect.ImmutableSet.toImmutableSet;
<ide> import static com.google.common.truth.Truth.assertThat;
<ide> import static com.google.common.truth.Truth.assertWithMessage;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide> import java.util.function.Predicate;
<add>import java.util.stream.Stream;
<ide> import javax.annotation.processing.Processor;
<ide> import javax.tools.JavaCompiler;
<ide> import javax.tools.JavaFileObject;
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<ide> import org.junit.rules.TemporaryFolder;
<add>import org.junit.runner.RunWith;
<add>import org.junit.runners.JUnit4;
<ide>
<ide> /**
<ide> * Tests that we can compile our AutoValue tests using the Eclipse batch compiler. Since the tests
<ide> * exercise many AutoValue subtleties, the ability to compile them all is a good indication of
<ide> * Eclipse support.
<ide> */
<add>@RunWith(JUnit4.class)
<ide> public class CompileWithEclipseTest {
<ide> private static final String SOURCE_ROOT = System.getProperty("basedir");
<ide>
<ide> // on Java 9+ there is no rt.jar. There, fileManager.getLocation(PLATFORM_CLASS_PATH) returns
<ide> // null, because the relevant classes are in modules inside
<ide> // fileManager.getLocation(SYSTEM_MODULES).
<del> File rtJar = new File(System.getProperty("java.home") + "/lib/rt.jar");
<add> File rtJar = new File(JAVA_HOME.value() + "/lib/rt.jar");
<ide> if (rtJar.exists()) {
<ide> List<File> bootClassPath = ImmutableList.<File>builder()
<ide> .add(rtJar)
<ide> private static ImmutableSet<File> filesUnderDirectory(File dir, Predicate<File> predicate)
<ide> throws IOException {
<ide> assertWithMessage(dir.toString()).that(dir.isDirectory()).isTrue();
<del> return Files.walk(dir.toPath()).map(Path::toFile).filter(predicate).collect(toImmutableSet());
<add> try (Stream<Path> paths = Files.walk(dir.toPath())) {
<add> return paths.map(Path::toFile).filter(predicate).collect(toImmutableSet());
<add> }
<ide> }
<ide> } |
|
JavaScript | mit | e12ebf82c0d2af1581f14e08931594100116f8d8 | 0 | usnistgov/corr,usnistgov/corr,usnistgov/corr,faical-yannick-congo/corr,faical-yannick-congo/corr,faical-yannick-congo/corr,faical-yannick-congo/corr | // Diff edit callback
function diffEdit(diff_id){
var diff_update = document.getElementById('update-diff-'+diff_id);
diff_update.innerHTML = "<a id='update-action' onclick='diffSave(\""+diff_id+"\");' class='btn-floating activator btn-move-up waves-effect waves-light darken-2 right'><i class='mdi-content-save'></i></a>";
var method = document.getElementById('diff-method-'+diff_id);
var proposition = document.getElementById('diff-proposition-'+diff_id);
var status = document.getElementById('diff-status-'+diff_id);
method.removeAttribute("readonly");
proposition.removeAttribute("readonly");
status.removeAttribute("readonly");
}
// Diff save callback
function diffSave(diff_id){
var diff_update = document.getElementById('update-diff-'+diff_id);
diff_update.innerHTML = "<a id='update-action' onclick='diffEdit(\""+diff_id+"\");' class='btn-floating activator btn-move-up waves-effect waves-light darken-2 right'><i class='mdi-editor-mode-edit'></i></a>";
var method = document.getElementById('diff-method-'+diff_id);
var proposition = document.getElementById('diff-proposition-'+diff_id);
var status = document.getElementById('diff-status-'+diff_id);
var diff = new Diff(user.session, diff_id);
diff.save(method.value, proposition.value, status.value);
}
// Diff remove callback
function diffRemove(diff_id){
Materialize.toast("<span>Delete "+diff_id+"</span><a class=\"btn light-blue\" href=\"http://"+config.host+":"+config.port+"/cloud/v0.1/private/"+user.session+"/diff/remove/"+diff_id+"\">Confirm</a>", 5000);
}
// Diff remove agreement callback
function diffRemoveAgree(session, diff_id){
console.log("in diffRemoveAgree!");
var diff = new Diff(session, diff_id);
diff.trash();
window.location.reload();
} | corr-view/frontend/js/callbacks/diff.js | // Diff edit callback
function diffEdit(diff_id){
var diff_update = document.getElementById('update-diff-'+diff_id);
diff_update.innerHTML = "<a id='update-action' onclick='diffSave(\""+diff_id+"\");' class='btn-floating activator btn-move-up waves-effect waves-light darken-2 right'><i class='mdi-content-save'></i></a>";
var method = document.getElementById('diff-method-'+diff_id);
var proposition = document.getElementById('diff-proposition-'+diff_id);
var status = document.getElementById('diff-status-'+diff_id);
method.removeAttribute("readonly");
proposition.removeAttribute("readonly");
status.removeAttribute("readonly");
}
// Diff save callback
function diffSave(diff_id){
var diff_update = document.getElementById('update-diff-'+diff_id);
diff_update.innerHTML = "<a id='update-action' onclick='diffEdit(\""+diff_id+"\");' class='btn-floating activator btn-move-up waves-effect waves-light darken-2 right'><i class='mdi-editor-mode-edit'></i></a>";
var method = document.getElementById('diff-method-'+diff_id);
var proposition = document.getElementById('diff-proposition-'+diff_id);
var status = document.getElementById('diff-status-'+diff_id);
var diff = new Diff(user.session, diff_id);
diff.save(method.value, description.value, status.value);
}
// Diff remove callback
function diffRemove(diff_id){
Materialize.toast("<span>Delete "+diff_id+"</span><a class=\"btn light-blue\" href=\"http://"+config.host+":"+config.port+"/cloud/v0.1/private/"+user.session+"/diff/remove/"+diff_id+"\">Confirm</a>", 5000);
}
// Diff remove agreement callback
function diffRemoveAgree(session, diff_id){
console.log("in diffRemoveAgree!");
var diff = new Diff(session, diff_id);
diff.trash();
window.location.reload();
} | Fixing diff edition issue.
| corr-view/frontend/js/callbacks/diff.js | Fixing diff edition issue. | <ide><path>orr-view/frontend/js/callbacks/diff.js
<ide> var proposition = document.getElementById('diff-proposition-'+diff_id);
<ide> var status = document.getElementById('diff-status-'+diff_id);
<ide> var diff = new Diff(user.session, diff_id);
<del> diff.save(method.value, description.value, status.value);
<add> diff.save(method.value, proposition.value, status.value);
<ide> }
<ide>
<ide> // Diff remove callback |
|
JavaScript | mit | dc03096bf21d5d9fb4e1602ce8731ae32ba81155 | 0 | must-/OpenBazaar,dionyziz/OpenBazaar,dionyziz/OpenBazaar,habibmasuro/OpenBazaar,must-/OpenBazaar,Renelvon/OpenBazaar,blakejakopovic/OpenBazaar,NolanZhao/OpenBazaar,rllola/OpenBazaar,NolanZhao/OpenBazaar,bankonme/OpenBazaar,bglassy/OpenBazaar,must-/OpenBazaar,dionyziz/OpenBazaar,Renelvon/OpenBazaar,rllola/OpenBazaar,blakejakopovic/OpenBazaar,bankonme/OpenBazaar,freebazaar/FreeBazaar,dionyziz/OpenBazaar,habibmasuro/OpenBazaar,blakejakopovic/OpenBazaar,matiasbastos/OpenBazaar,habibmasuro/OpenBazaar,saltduck/OpenBazaar,atsuyim/OpenBazaar,tortxof/OpenBazaar,akhavr/OpenBazaar,bglassy/OpenBazaar,akhavr/OpenBazaar,Renelvon/OpenBazaar,saltduck/OpenBazaar,mirrax/OpenBazaar,habibmasuro/OpenBazaar,atsuyim/OpenBazaar,freebazaar/FreeBazaar,matiasbastos/OpenBazaar,matiasbastos/OpenBazaar,freebazaar/FreeBazaar,matiasbastos/OpenBazaar,dionyziz/OpenBazaar,bankonme/OpenBazaar,NolanZhao/OpenBazaar,blakejakopovic/OpenBazaar,akhavr/OpenBazaar,tortxof/OpenBazaar,akhavr/OpenBazaar,saltduck/OpenBazaar,atsuyim/OpenBazaar,saltduck/OpenBazaar,freebazaar/FreeBazaar,tortxof/OpenBazaar,mirrax/OpenBazaar,freebazaar/FreeBazaar,Renelvon/OpenBazaar,must-/OpenBazaar,NolanZhao/OpenBazaar,mirrax/OpenBazaar,bankonme/OpenBazaar,akhavr/OpenBazaar,atsuyim/OpenBazaar,tortxof/OpenBazaar,mirrax/OpenBazaar,rllola/OpenBazaar,bglassy/OpenBazaar,rllola/OpenBazaar,bglassy/OpenBazaar | /**
* Market controller.
*
* @desc This controller is the main controller for the market.
* It contains all of the single page application logic.
* @param {!angular.Scope} $scope
* @constructor
*/
angular.module('app')
.controller('Market', ['$scope', '$route', '$interval', '$routeParams', '$location', 'Connection',
function($scope, $route, $interval, $routeParams, $location, Connection) {
$scope.newuser = true; // Should show welcome screen?
$scope.page = false; // Market page has been loaded
$scope.dashboard = true; // Show dashboard
$scope.myInfoPanel = true; // Show information panel
$scope.shouts = []; // Shout messages
$scope.newShout = "";
$scope.searching = "";
$scope.currentReviews = [];
$scope.myOrders = [];
$scope.myReviews = [];
$scope.peers = [];
$scope.reviews = {};
$scope.$emit('sidebar', true);
Connection.send('get_btc_ticker', {});
/**
* Establish message handlers
* @msg - message from websocket to pass on to handler
*/
$scope.$evalAsync( function( $scope ) {
var listeners = Connection.$$listeners;
if(!listeners.hasOwnProperty('order_notify')) {
Connection.$on('order_notify', function(e, msg){ $scope.order_notify(msg); });
}
if(!listeners.hasOwnProperty('republish_notify')) {
Connection.$on('republish_notify', function(e, msg){ $scope.republish_notify(msg); });
}
if(!listeners.hasOwnProperty('inbox_notify')) {
Connection.$on('inbox_notify', function(e, msg){ $scope.inbox_notify(msg); });
}
Connection.$on('peer', function(e, msg){ $scope.add_peer(msg); });
Connection.$on('goodbye', function(e, msg){ $scope.goodbye(msg); });
Connection.$on('hello_response', function(e, msg){ $scope.hello_response(msg); });
listeners.peers = [];
Connection.$on('peers', function(e, msg){ $scope.update_peers(msg); });
Connection.$on('peer_remove', function(e, msg){ $scope.remove_peer(msg); });
if(!listeners.hasOwnProperty('inbox_count')) {
Connection.$on('inbox_count', function (e, msg) {
$scope.parse_inbox_count(msg);
});
}
Connection.$on('myself', function(e, msg){ $scope.parse_myself(msg); });
Connection.$on('shout', function(e, msg){ $scope.parse_shout(msg); });
listeners.btc_ticker = [];
Connection.$on('btc_ticker', function(e, msg){ $scope.parse_btc_ticker(msg); });
Connection.$on('log_output', function(e, msg){ $scope.parse_log_output(msg); });
Connection.$on('messages', function(e, msg){ $scope.parse_messages(msg); });
Connection.$on('notaries', function(e, msg){ $scope.parse_notaries(msg); });
Connection.$on('reputation', function(e, msg){ $scope.parse_reputation(msg); });
Connection.$on('burn_info_available', function(e, msg){ $scope.parse_burn_info(msg); });
Connection.$on('inbox_messages', function(e, msg){ $scope.parse_inbox_messages(msg); });
Connection.$on('inbox_sent_messages', function(e, msg){ $scope.parse_inbox_sent_messages(msg); });
Connection.$on('hello', function(e, msg){
console.log('Received a hello', msg);
$scope.add_peer({
'guid': msg.senderGUID,
'uri': msg.uri,
'pubkey': msg.pubkey,
'nick': msg.senderNick
});
});
});
// Listen for Sidebar mods
$scope.$on('sidebar', function(event, visible) {
$scope.sidebar = visible;
});
var refresh_peers = function() {
Connection.send('peers', {});
};
$interval(refresh_peers, 30000, 0, true);
/**
* Create a shout and send it to all connected peers
* Display it in the interface
*/
$scope.createShout = function() {
if($scope.newShout === '') {
return;
}
// launch a shout
var newShout = {
'type': 'shout',
'text': $scope.newShout,
'pubkey': $scope.myself.pubkey,
'senderGUID': $scope.myself.guid,
'avatar_url': $scope.myself.settings.avatar_url ? $scope.myself.settings.avatar_url : ''
};
Connection.send('shout', newShout);
$scope.shouts.push(newShout);
$scope.newShout = '';
};
/**
* Handles inbox count message from the server
* @msg - Message from server
*/
$scope.parse_inbox_count = function(msg) {
console.log('Inbox count', msg);
$scope.inbox_count = msg.count;
if (!$scope.$$phase) {
$scope.$apply();
}
};
// Toggle the sidebar hidden/shown
$scope.toggleSidebar = function() {
$scope.sidebar = !$scope.sidebar;
};
// Hide the sidebar
$scope.hideSidebar = function() {
$scope.sidebar = false;
};
// Show the sidebar
$scope.showSidebar = function() {
$scope.sidebar = true;
};
/**
* [LEGACY] Adds review to a page
* @pubkey -
* @review -
*/
var add_review_to_page = function(pubkey, review) {
var found = false;
console.log("Add review");
if (!$scope.reviews.hasOwnProperty(pubkey)) {
$scope.reviews[pubkey] = [];
}
$scope.reviews[pubkey].forEach(function(_review) {
if (_review.sig == review.sig && _review.subject == review.subject && _review.pubkey == review.pubkey) {
console.log("Found a review for this market");
found = true;
}
});
if (!found) {
// check if the review is about me
if ($scope.myself.pubkey == review.subject) {
console.log("Found review for myself");
$scope.myReviews.push(review);
}
$scope.reviews[pubkey].push(review);
}
};
/**
* Send log line to GUI
* @msg - Message from server
*/
$scope.parse_log_output = function(msg) {
console.log(msg);
$scope.log_output += msg.line;
};
/**
* Load notaries array into the GUI
* @msg - Message from server
*/
$scope.parse_notaries = function(msg) {
$scope.trusted_notaries = msg.notaries;
};
$scope.parse_welcome = function(msg) {
console.log(msg);
};
$scope.guid_to_avatar = function(guid) {
};
$scope.getNumber = function(num) {
return new Array(num);
};
$scope.orders_page_changed = function() {
console.log(this.orders_current_page);
var query = {
'page': this.orders_current_page - 1,
'merchant': $scope.merchant
};
Connection.send('query_orders', query);
};
$scope.parse_contracts = function(msg) {
console.log(msg);
var page = msg.page;
$scope.contracts = msg.contracts.contracts;
$scope.total_contracts = msg.contracts.total_contracts;
$scope.contracts_pages = $scope.total_contracts % 10;
console.log('contracts', $scope.total_contracts);
$scope.contracts_current_page = (page > 0) ? page - 1 : 0;
console.log($scope);
for (var key in msg.contracts.contracts) {
var obj = msg.contracts.contracts[key];
for (var prop in obj) {
if (prop == 'item_images' && jQuery.isEmptyObject(msg.contracts.contracts[key].item_images)) {
msg.contracts.contracts[key].item_images = "img/no-photo.png";
}
}
}
$scope.contract2 = {};
};
$scope.message = {};
$scope.parse_messages = function(msg) {
if (msg !== null &&
msg.messages !== null &&
msg.messages.messages !== null &&
msg.messages.messages.inboxMessages !== null) {
$scope.messages = msg.messages.messages.inboxMessages;
$scope.message = {};
}
};
$scope.inbox_messages = {};
$scope.inbox_sent_messages = {};
$scope.parse_inbox_messages = function(msg) {
console.log(msg);
$scope.inbox_messages = msg.messages;
};
$scope.parse_inbox_sent_messages = function(msg) {
console.log(msg);
$scope.inbox_sent_messages = msg.messages;
};
$scope.parse_burn_info = function(msg) {
// console.log('Burn info available!');
var SATOSHIS_IN_BITCOIN = 100000000;
var amountInSatoshis = msg.amount;
var bitcoins = msg.amount / SATOSHIS_IN_BITCOIN;
bitcoins = Math.round(bitcoins * 10000) / 10000;
// console.log(bitcoins);
console.log('Trust Pledge:', bitcoins+'BTC', msg.addr);
$scope.settings.burnAmount = bitcoins;
$scope.settings.burnAddr = msg.addr;
};
// Peer information has arrived
$scope.parse_reputation = function(msg) {
console.log('Parsing reputation', msg.reviews);
msg.reviews.forEach(function(review) {
add_review_to_page(review.subject, review);
});
};
// Check if peer is already known by comparing the public key
$scope.add_peer = function(msg) {
var alreadyExists = false;
angular.forEach($scope.peers,function(peer,index){
if(peer.pubkey === msg.pubkey){
alreadyExists = true;
}
});
if(!alreadyExists){
$scope.peers.push(msg);
}
};
$scope.goodbye = function(msg) {
console.log('Goodbye');
/* get index if peer is already known */
var index = [-1].concat($scope.myself.peers).reduce(
function(previousValue, currentValue, index, array) {
return currentValue.guid == msg.senderGUID ? index : previousValue;
});
if (index >= 0) {
/* it is a new peer */
console.log('Removing peer');
$scope.myself.peers.splice(index, 1);
$scope.peers = $scope.myself.peers;
}
};
$scope.hello_response = function(msg) {
console.log('Hello Response', msg);
refresh_peers();
};
$scope.update_peers = function(msg) {
console.log('Refresh peers: ', msg);
$scope.peers = msg.peers;
};
$scope.remove_peer = function(msg) {
console.log('Remove peer: ', msg);
$scope.peers = $scope.peers.filter(function(element) {
return element.uri != msg.uri;
});
};
$scope.review = {
rating: 5,
text: ""
};
$scope.addReview = function() {
var query = {
'type': 'review',
'pubkey': $scope.page.pubkey,
'text': $scope.review.text,
'rating': parseInt($scope.review.rating)
};
Connection.send('review', query);
// store in appropriate format (its different than push format :P)
add_review_to_page($scope.page.pubkey, {
type: 'review',
'pubkey': $scope.myself.pubkey,
'subject': $scope.page.pubkey,
'rating': query.rating,
text: query.text
});
$scope.review.rating = 5;
$scope.review.text = '';
$scope.showReviewForm = false;
};
// My information has arrived
$scope.parse_myself = function(msg) {
$scope.myself = msg;
// Settings
$scope.settings = msg.settings;
//msg.reputation.forEach(function(review) {
// add_review_to_page($scope.myself.pubkey, review)
//});
msg.peers.forEach(function(peer) {
if(peer.guid !== '') {
$scope.add_peer(peer);
}
});
};
// A shout has arrived
$scope.parse_shout = function(msg) {
$scope.shouts.push(msg);
console.log('Shout', $scope.shouts);
};
$scope.parse_btc_ticker = function(msg) {
var data = JSON.parse(msg.data);
console.log('BTC Ticker', data.USD);
$scope.last_price_usd = data.USD.last;
};
$scope.checkOrderCount = function() {
Connection.send('check_order_count', {});
};
$scope.settings = {
email: '',
PGPPubKey: '',
bitmessage: '',
pubkey: '',
secret: '',
nickname: '',
welcome: '',
trustedArbiters: {},
trustedNotaries: {}
};
$scope.order_notify = function(msg) {
console.log(msg);
Notifier.info('Order Update', msg.msg);
};
$scope.republish_notify = function(msg) {
Notifier.info('Network Update', msg.msg);
};
$scope.inbox_notify = function(msg) {
console.log(msg);
Notifier.info('"' + msg.msg.subject + '"', 'Message from ' + msg.msg.senderNick);
};
// Create a new order and send to the network
$scope.newOrder = {
message: '',
tx: '',
listingKey: '',
productTotal: ''
};
$scope.createOrder = function() {
$scope.creatingOrder = false;
var newOrder = {
'text': $scope.newOrder.message,
'state': 'New',
'buyer': $scope.myself.pubkey,
'seller': $scope.page.pubkey,
'listingKey': $scope.newOrder.pubkey
};
Connection.send('order', newOrder);
$scope.sentOrder = true;
$scope.showDashboardPanel('orders');
$('#pill-orders').addClass('active').siblings().removeClass('active').blur();
$("#orderSuccessAlert").alert();
window.setTimeout(function() {
$("#orderSuccessAlert").alert('close');
}, 5000);
};
$scope.payOrder = function(order) {
order.state = 'Paid';
order.tx = $scope.newOrder.tx;
$scope.newOrder.tx = '';
Connection.send('order', order);
};
$scope.receiveOrder = function(order) {
order.state = 'Received';
Connection.send('order', order);
};
$scope.sendOrder = function(order) {
order.state = 'Sent';
Connection.send('order', order);
$scope.queryMyOrder(0);
};
$scope.cancelOrder = function(order) {
order.state = 'cancelled';
Connection.send('order', order);
};
$scope.addArbiter = function(arbiter) {
var arbiterGUID = (arbiter !== '') ? arbiter : $('#inputArbiterGUID').val();
$('#inputArbiterGUID').val('');
// TODO: Check for valid arbiter GUID
//if(arbiterGUID.length != 38 || !arbiterGUID.match(/^[0-9a-zA-Z]+$/)) {
// alert('Incorrect format for GUID');
// return;
//}
if (!$scope.settings.trustedArbiters) {
$scope.settings.trustedArbiters = [];
}
$scope.settings.trustedArbiters.push(arbiterGUID);
// Dedupe arbiter GUIDs
var uniqueArbiters = [];
$.each($scope.settings.trustedArbiters, function(i, el) {
if ($.inArray(el, uniqueArbiters) === -1) {
uniqueArbiters.push(el);
}
});
$scope.settings.trustedArbiters = uniqueArbiters;
$scope.saveSettings(false);
Notifier.success('Success', 'Arbiter added successfully.');
};
$scope.removeArbiter = function(arbiterGUID) {
// Dedupe arbiter GUIDs
var uniqueArbiters = $scope.settings.trustedArbiters;
$.each($scope.settings.trustedArbiters, function(i, el) {
if (el == arbiterGUID) {
uniqueArbiters.splice(i, 1);
}
});
$scope.settings.trustedArbiters = uniqueArbiters;
$scope.saveSettings(false);
Notifier.success('Success', 'Arbiter removed successfully.');
};
$scope.compose_message = function(size, myself, address, subject) {
$scope.$broadcast("compose_message", {
size: size,
myself: myself,
bm_address: address,
subject: subject
});
};
$scope.clearDHTData = function() {
Connection.send('clear_dht_data', {});
Notifier.success('Success', 'DHT cache cleared');
};
$scope.clearPeers = function() {
Connection.send('clear_peers_data', {});
Notifier.success('Success', 'Peers table cleared');
};
function resetPanels() {
$scope.messagesPanel = false;
$scope.reviewsPanel = false;
$scope.productCatalogPanel = false;
$scope.settingsPanel = false;
$scope.arbitrationPanel = false;
$scope.ordersPanel = false;
$scope.myInfoPanel = false;
$scope.searchPanel = false;
}
$scope.showDashboardPanel = function(panelName, e) {
if (e) {
e.preventDefault();
}
resetPanels();
if (panelName != 'myInfo') {
$scope.hideSidebar();
$('#dashboard-container').removeClass('col-sm-8').addClass('col-sm-12');
} else {
$scope.showSidebar();
$('#dashboard-container').removeClass('col-sm-12').addClass('col-sm-8');
}
$scope.dashboard = true;
$scope.page = false;
switch (panelName) {
case 'messages':
$scope.queryMessages();
$scope.messagesPanel = true;
break;
case 'reviews':
$scope.reviewsPanel = true;
break;
case 'arbitration':
$scope.arbitrationPanel = true;
break;
case 'myInfo':
$scope.myInfoPanel = true;
break;
}
};
$scope.getNotaries = function() {
Connection.send('get_notaries', {});
};
$scope.goToStore = function(url, guid) {
$scope.awaitingStore = guid;
$scope.page = null;
$scope.go(url);
};
$scope.go = function (url) {
$location.path(url);
};
/**
* Query the network for a merchant and then
* show the page
* @guid - GUID of page to load
*/
$scope.queryShop = function(guid) {
$scope.awaitingShop = guid;
console.log('Querying for shop [market]: ', guid);
var query = {
'type': 'query_page',
'findGUID': guid
};
$scope.page = null;
Connection.send('query_page', query);
};
$scope.queryMessages = function() {
// Query for messages
var query = {
'type': 'query_messages'
};
console.log('querying messages');
Connection.send('query_messages', query);
console.log($scope.myself.messages);
};
// Modal Code
$scope.WelcomeModalCtrl = function($scope, $modal, $log, $rootScope) {
// Listen for changes to settings and if welcome is empty then show the welcome modal
$scope.$watch('settings', function() {
console.log('settings', $scope.settings);
if ($scope.settings.welcome == "enable") {
$scope.open('lg', 'static');
Connection.send('welcome_dismissed', {});
} else {
return;
}
/*Else process your data*/
});
$scope.open = function(size, backdrop, scope) {
backdrop = backdrop ? backdrop : true;
var modalInstance = $modal.open({
templateUrl: 'partials/welcome.html',
controller: ModalInstanceCtrl,
size: size,
backdrop: backdrop,
resolve: {
settings: function() {
return $scope.settings;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
var ModalInstanceCtrl = function($scope, $modalInstance, settings) {
$scope.settings = settings;
// $scope.selected = {
// item: $scope.items[0]
// };
//
$scope.welcome = settings.welcome;
$scope.ok = function() {
Connection.send('welcome_dismissed', {});
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.ComposeMessageCtrl = function($scope, $modal, $log) {
$scope.$on("compose_message", function(event, args) {
$scope.bm_address = args.bm_address;
$scope.size = args.size;
$scope.subject = args.subject;
$scope.myself = args.myself;
$scope.compose($scope.size, $scope.myself, $scope.bm_address, $scope.subject);
});
$scope.compose = function(size, myself, to_address, msg) {
var composeModal = $modal.open({
templateUrl: 'partials/modal/composeMessage.html',
controller: $scope.ComposeMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
to_address: function() {
return to_address;
},
msg: function() {
return msg;
},
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('messages');
};
composeModal.result.then(
afterFunc,
function() {
$scope.queryMessages();
$log.info('Modal dismissed at: ' + new Date());
}
);
};
$scope.view = function(size, myself, to_address, msg) {
var viewModal = $modal.open({
templateUrl: 'partials/modal/viewMessage.html',
controller: $scope.ViewMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
to_address: function() {
return to_address;
},
msg: function() {
return msg;
}
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('messages');
};
viewModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
};
$scope.ViewMessageInstanceCtrl = function($scope, $modalInstance, myself, to_address, msg) {
$scope.myself = myself;
$scope.my_address = myself.bitmessage;
$scope.to_address = to_address;
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.toAddress = msg.fromAddress;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
console.log('sending message with subject ' + subject);
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.ComposeMessageInstanceCtrl = function($scope, $modalInstance, myself, to_address, msg) {
$scope.myself = myself;
$scope.to_address = to_address;
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.toAddress = msg.fromAddress;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.NewMessageCtrl = function($scope, $modal, $log) {
$scope.$on("compose_inbox_message", function(event, args) {
console.log('compose_inbox_message');
$scope.guid = args.guid;
$scope.size = args.size;
$scope.subject = args.subject;
$scope.myself = args.myself;
$scope.compose($scope.size, $scope.myself, $scope.guid, $scope.subject);
});
$scope.guid_to_nickname = function(guid) {
if(guid == $scope.myself.guid) {
return $scope.myself.settings.nickname;
}
for(var peer in $scope.myself.peers) {
peer = $scope.myself.peers[peer];
if(peer.guid == guid) {
return peer.nick;
}
}
return '';
};
$scope.compose = function(size, myself, recipient, msg) {
var composeModal = $modal.open({
templateUrl: 'partials/modal/newMessage.html',
controller: $scope.NewMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
recipient: function() {
return recipient;
},
msg: function() {
return msg;
},
scope: function() {
return $scope;
}
},
size: size
});
var afterFunc = function() {
return;
};
composeModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
$scope.view = function(size, myself, msg) {
var viewModal = $modal.open({
templateUrl: 'partials/modal/viewInboxMessage.html',
controller: ViewInboxMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
msg: function() {
return msg;
},
scope: function() {
return $scope;
}
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('inbox');
};
viewModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
};
$scope.NewMessageInstanceCtrl = function($scope, $modalInstance, myself, recipient, msg, scope) {
function guid_to_peer(guid) {
for(var peer in $scope.myself.peers) {
peer = $scope.myself.peers[peer];
if(peer.guid == guid) {
return peer;
}
}
return {};
}
$scope.myself = myself;
$scope.recipient = (recipient !== '') ? guid_to_peer(recipient) : '';
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.recipient = msg.recipient;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (sendMessageForm.$invalid) {
return;
}
var query = {
'type': 'send_inbox_message',
'recipient': this.recipient.guid,
'subject': subject.value,
'body': body.value
};
Connection.send('send_inbox_message', query);
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var ViewInboxMessageInstanceCtrl = function($scope, $modalInstance, myself, msg, scope) {
$scope.myself = myself;
$scope.inbox = {};
$scope.inbox.message = msg;
$scope.inbox.message.nickname = scope.guid_to_nickname(msg.sender_guid);
console.log('test', $scope);
// Fill in form if msg is passed - reply mode
if (msg !== null) {
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
//var quote_msg = $scope.msg.body.replace(quote_re, "> $1");
//$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
console.log('sending message with subject ' + subject);
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
};
// Modal Code
$scope.AddNodeModalCtrl = function($scope, $modal, $log) {
$scope.open = function(size, backdrop, scope) {
backdrop = backdrop ? backdrop : true;
var modalInstance = $modal.open({
templateUrl: 'partials/modal/addNode.html',
controller: AddNodeModalInstance,
size: size,
backdrop: backdrop,
resolve: {}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
var AddNodeModalInstance = function($scope, $modalInstance) {
$scope.addGUID = function(newGUID) {
if (newGUID.length == 40 && newGUID.match(/^[A-Za-z0-9]+$/)) {
Connection.send('add_node', {
'type': 'add_guid',
'guid': newGUID
});
console.log('Added node by GUID');
Notifier.success('Success', 'GUID is valid');
} else {
Notifier.info('Failure', 'GUID is not valid');
}
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
}
]);
| html/controllers/market.js | /**
* Market controller.
*
* @desc This controller is the main controller for the market.
* It contains all of the single page application logic.
* @param {!angular.Scope} $scope
* @constructor
*/
angular.module('app')
.controller('Market', ['$scope', '$route', '$interval', '$routeParams', '$location', 'Connection',
function($scope, $route, $interval, $routeParams, $location, Connection) {
$scope.newuser = true; // Should show welcome screen?
$scope.page = false; // Market page has been loaded
$scope.dashboard = true; // Show dashboard
$scope.myInfoPanel = true; // Show information panel
$scope.shouts = []; // Shout messages
$scope.newShout = "";
$scope.searching = "";
$scope.currentReviews = [];
$scope.myOrders = [];
$scope.myReviews = [];
$scope.peers = [];
$scope.reviews = {};
$scope.$emit('sidebar', true);
Connection.send('get_btc_ticker', {});
/**
* Establish message handlers
* @msg - message from websocket to pass on to handler
*/
$scope.$evalAsync( function( $scope ) {
var listeners = Connection.$$listeners;
if(!listeners.hasOwnProperty('order_notify')) {
Connection.$on('order_notify', function(e, msg){ $scope.order_notify(msg); });
}
if(!listeners.hasOwnProperty('republish_notify')) {
Connection.$on('republish_notify', function(e, msg){ $scope.republish_notify(msg); });
}
if(!listeners.hasOwnProperty('inbox_notify')) {
Connection.$on('inbox_notify', function(e, msg){ $scope.inbox_notify(msg); });
}
Connection.$on('peer', function(e, msg){ $scope.add_peer(msg); });
Connection.$on('goodbye', function(e, msg){ $scope.goodbye(msg); });
Connection.$on('hello_response', function(e, msg){ $scope.hello_response(msg); });
Connection.$on('peers', function(e, msg){ $scope.update_peers(msg); });
Connection.$on('peer_remove', function(e, msg){ $scope.remove_peer(msg); });
if(!listeners.hasOwnProperty('inbox_count')) {
Connection.$on('inbox_count', function (e, msg) {
$scope.parse_inbox_count(msg);
});
}
Connection.$on('myself', function(e, msg){ $scope.parse_myself(msg); });
Connection.$on('shout', function(e, msg){ $scope.parse_shout(msg); });
Connection.$on('btc_ticker', function(e, msg){ $scope.parse_btc_ticker(msg); });
Connection.$on('log_output', function(e, msg){ $scope.parse_log_output(msg); });
Connection.$on('messages', function(e, msg){ $scope.parse_messages(msg); });
Connection.$on('notaries', function(e, msg){ $scope.parse_notaries(msg); });
Connection.$on('reputation', function(e, msg){ $scope.parse_reputation(msg); });
Connection.$on('burn_info_available', function(e, msg){ $scope.parse_burn_info(msg); });
Connection.$on('inbox_messages', function(e, msg){ $scope.parse_inbox_messages(msg); });
Connection.$on('inbox_sent_messages', function(e, msg){ $scope.parse_inbox_sent_messages(msg); });
Connection.$on('hello', function(e, msg){
console.log('Received a hello', msg);
$scope.add_peer({
'guid': msg.senderGUID,
'uri': msg.uri,
'pubkey': msg.pubkey,
'nick': msg.senderNick
});
});
});
// Listen for Sidebar mods
$scope.$on('sidebar', function(event, visible) {
$scope.sidebar = visible;
});
var refresh_peers = function() {
Connection.send('peers', {});
};
$interval(refresh_peers, 30000, 0, true);
/**
* Create a shout and send it to all connected peers
* Display it in the interface
*/
$scope.createShout = function() {
if($scope.newShout === '') {
return;
}
// launch a shout
var newShout = {
'type': 'shout',
'text': $scope.newShout,
'pubkey': $scope.myself.pubkey,
'senderGUID': $scope.myself.guid,
'avatar_url': $scope.myself.settings.avatar_url ? $scope.myself.settings.avatar_url : ''
};
Connection.send('shout', newShout);
$scope.shouts.push(newShout);
$scope.newShout = '';
};
/**
* Handles inbox count message from the server
* @msg - Message from server
*/
$scope.parse_inbox_count = function(msg) {
console.log('Inbox count', msg);
$scope.inbox_count = msg.count;
if (!$scope.$$phase) {
$scope.$apply();
}
};
// Toggle the sidebar hidden/shown
$scope.toggleSidebar = function() {
$scope.sidebar = !$scope.sidebar;
};
// Hide the sidebar
$scope.hideSidebar = function() {
$scope.sidebar = false;
};
// Show the sidebar
$scope.showSidebar = function() {
$scope.sidebar = true;
};
/**
* [LEGACY] Adds review to a page
* @pubkey -
* @review -
*/
var add_review_to_page = function(pubkey, review) {
var found = false;
console.log("Add review");
if (!$scope.reviews.hasOwnProperty(pubkey)) {
$scope.reviews[pubkey] = [];
}
$scope.reviews[pubkey].forEach(function(_review) {
if (_review.sig == review.sig && _review.subject == review.subject && _review.pubkey == review.pubkey) {
console.log("Found a review for this market");
found = true;
}
});
if (!found) {
// check if the review is about me
if ($scope.myself.pubkey == review.subject) {
console.log("Found review for myself");
$scope.myReviews.push(review);
}
$scope.reviews[pubkey].push(review);
}
};
/**
* Send log line to GUI
* @msg - Message from server
*/
$scope.parse_log_output = function(msg) {
console.log(msg);
$scope.log_output += msg.line;
};
/**
* Load notaries array into the GUI
* @msg - Message from server
*/
$scope.parse_notaries = function(msg) {
$scope.trusted_notaries = msg.notaries;
};
$scope.parse_welcome = function(msg) {
console.log(msg);
};
$scope.guid_to_avatar = function(guid) {
};
$scope.getNumber = function(num) {
return new Array(num);
};
$scope.orders_page_changed = function() {
console.log(this.orders_current_page);
var query = {
'page': this.orders_current_page - 1,
'merchant': $scope.merchant
};
Connection.send('query_orders', query);
};
$scope.parse_contracts = function(msg) {
console.log(msg);
var page = msg.page;
$scope.contracts = msg.contracts.contracts;
$scope.total_contracts = msg.contracts.total_contracts;
$scope.contracts_pages = $scope.total_contracts % 10;
console.log('contracts', $scope.total_contracts);
$scope.contracts_current_page = (page > 0) ? page - 1 : 0;
console.log($scope);
for (var key in msg.contracts.contracts) {
var obj = msg.contracts.contracts[key];
for (var prop in obj) {
if (prop == 'item_images' && jQuery.isEmptyObject(msg.contracts.contracts[key].item_images)) {
msg.contracts.contracts[key].item_images = "img/no-photo.png";
}
}
}
$scope.contract2 = {};
};
$scope.message = {};
$scope.parse_messages = function(msg) {
if (msg !== null &&
msg.messages !== null &&
msg.messages.messages !== null &&
msg.messages.messages.inboxMessages !== null) {
$scope.messages = msg.messages.messages.inboxMessages;
$scope.message = {};
}
};
$scope.inbox_messages = {};
$scope.inbox_sent_messages = {};
$scope.parse_inbox_messages = function(msg) {
console.log(msg);
$scope.inbox_messages = msg.messages;
};
$scope.parse_inbox_sent_messages = function(msg) {
console.log(msg);
$scope.inbox_sent_messages = msg.messages;
};
$scope.parse_burn_info = function(msg) {
// console.log('Burn info available!');
var SATOSHIS_IN_BITCOIN = 100000000;
var amountInSatoshis = msg.amount;
var bitcoins = msg.amount / SATOSHIS_IN_BITCOIN;
bitcoins = Math.round(bitcoins * 10000) / 10000;
// console.log(bitcoins);
console.log('Trust Pledge:', bitcoins+'BTC', msg.addr);
$scope.settings.burnAmount = bitcoins;
$scope.settings.burnAddr = msg.addr;
};
// Peer information has arrived
$scope.parse_reputation = function(msg) {
console.log('Parsing reputation', msg.reviews);
msg.reviews.forEach(function(review) {
add_review_to_page(review.subject, review);
});
};
// Check if peer is already known by comparing the public key
$scope.add_peer = function(msg) {
var alreadyExists = false;
angular.forEach($scope.peers,function(peer,index){
if(peer.pubkey === msg.pubkey){
alreadyExists = true;
}
});
if(!alreadyExists){
$scope.peers.push(msg);
}
};
$scope.goodbye = function(msg) {
console.log('Goodbye');
/* get index if peer is already known */
var index = [-1].concat($scope.myself.peers).reduce(
function(previousValue, currentValue, index, array) {
return currentValue.guid == msg.senderGUID ? index : previousValue;
});
if (index >= 0) {
/* it is a new peer */
console.log('Removing peer');
$scope.myself.peers.splice(index, 1);
$scope.peers = $scope.myself.peers;
}
};
$scope.hello_response = function(msg) {
console.log('Hello Response', msg);
refresh_peers();
};
$scope.update_peers = function(msg) {
console.log('Refresh peers: ', msg);
$scope.peers = msg.peers;
};
$scope.remove_peer = function(msg) {
console.log('Remove peer: ', msg);
$scope.peers = $scope.peers.filter(function(element) {
return element.uri != msg.uri;
});
};
$scope.review = {
rating: 5,
text: ""
};
$scope.addReview = function() {
var query = {
'type': 'review',
'pubkey': $scope.page.pubkey,
'text': $scope.review.text,
'rating': parseInt($scope.review.rating)
};
Connection.send('review', query);
// store in appropriate format (its different than push format :P)
add_review_to_page($scope.page.pubkey, {
type: 'review',
'pubkey': $scope.myself.pubkey,
'subject': $scope.page.pubkey,
'rating': query.rating,
text: query.text
});
$scope.review.rating = 5;
$scope.review.text = '';
$scope.showReviewForm = false;
};
// My information has arrived
$scope.parse_myself = function(msg) {
$scope.myself = msg;
// Settings
$scope.settings = msg.settings;
//msg.reputation.forEach(function(review) {
// add_review_to_page($scope.myself.pubkey, review)
//});
msg.peers.forEach(function(peer) {
if(peer.guid !== '') {
$scope.add_peer(peer);
}
});
};
// A shout has arrived
$scope.parse_shout = function(msg) {
$scope.shouts.push(msg);
console.log('Shout', $scope.shouts);
};
$scope.parse_btc_ticker = function(msg) {
var data = JSON.parse(msg.data);
console.log('BTC Ticker', data.USD);
$scope.last_price_usd = data.USD.last;
};
$scope.checkOrderCount = function() {
Connection.send('check_order_count', {});
};
$scope.settings = {
email: '',
PGPPubKey: '',
bitmessage: '',
pubkey: '',
secret: '',
nickname: '',
welcome: '',
trustedArbiters: {},
trustedNotaries: {}
};
$scope.order_notify = function(msg) {
console.log(msg);
Notifier.info('Order Update', msg.msg);
};
$scope.republish_notify = function(msg) {
Notifier.info('Network Update', msg.msg);
};
$scope.inbox_notify = function(msg) {
console.log(msg);
Notifier.info('"' + msg.msg.subject + '"', 'Message from ' + msg.msg.senderNick);
};
// Create a new order and send to the network
$scope.newOrder = {
message: '',
tx: '',
listingKey: '',
productTotal: ''
};
$scope.createOrder = function() {
$scope.creatingOrder = false;
var newOrder = {
'text': $scope.newOrder.message,
'state': 'New',
'buyer': $scope.myself.pubkey,
'seller': $scope.page.pubkey,
'listingKey': $scope.newOrder.pubkey
};
Connection.send('order', newOrder);
$scope.sentOrder = true;
$scope.showDashboardPanel('orders');
$('#pill-orders').addClass('active').siblings().removeClass('active').blur();
$("#orderSuccessAlert").alert();
window.setTimeout(function() {
$("#orderSuccessAlert").alert('close');
}, 5000);
};
$scope.payOrder = function(order) {
order.state = 'Paid';
order.tx = $scope.newOrder.tx;
$scope.newOrder.tx = '';
Connection.send('order', order);
};
$scope.receiveOrder = function(order) {
order.state = 'Received';
Connection.send('order', order);
};
$scope.sendOrder = function(order) {
order.state = 'Sent';
Connection.send('order', order);
$scope.queryMyOrder(0);
};
$scope.cancelOrder = function(order) {
order.state = 'cancelled';
Connection.send('order', order);
};
$scope.addArbiter = function(arbiter) {
var arbiterGUID = (arbiter !== '') ? arbiter : $('#inputArbiterGUID').val();
$('#inputArbiterGUID').val('');
// TODO: Check for valid arbiter GUID
//if(arbiterGUID.length != 38 || !arbiterGUID.match(/^[0-9a-zA-Z]+$/)) {
// alert('Incorrect format for GUID');
// return;
//}
if (!$scope.settings.trustedArbiters) {
$scope.settings.trustedArbiters = [];
}
$scope.settings.trustedArbiters.push(arbiterGUID);
// Dedupe arbiter GUIDs
var uniqueArbiters = [];
$.each($scope.settings.trustedArbiters, function(i, el) {
if ($.inArray(el, uniqueArbiters) === -1) {
uniqueArbiters.push(el);
}
});
$scope.settings.trustedArbiters = uniqueArbiters;
$scope.saveSettings(false);
Notifier.success('Success', 'Arbiter added successfully.');
};
$scope.removeArbiter = function(arbiterGUID) {
// Dedupe arbiter GUIDs
var uniqueArbiters = $scope.settings.trustedArbiters;
$.each($scope.settings.trustedArbiters, function(i, el) {
if (el == arbiterGUID) {
uniqueArbiters.splice(i, 1);
}
});
$scope.settings.trustedArbiters = uniqueArbiters;
$scope.saveSettings(false);
Notifier.success('Success', 'Arbiter removed successfully.');
};
$scope.compose_message = function(size, myself, address, subject) {
$scope.$broadcast("compose_message", {
size: size,
myself: myself,
bm_address: address,
subject: subject
});
};
$scope.clearDHTData = function() {
Connection.send('clear_dht_data', {});
Notifier.success('Success', 'DHT cache cleared');
};
$scope.clearPeers = function() {
Connection.send('clear_peers_data', {});
Notifier.success('Success', 'Peers table cleared');
};
function resetPanels() {
$scope.messagesPanel = false;
$scope.reviewsPanel = false;
$scope.productCatalogPanel = false;
$scope.settingsPanel = false;
$scope.arbitrationPanel = false;
$scope.ordersPanel = false;
$scope.myInfoPanel = false;
$scope.searchPanel = false;
}
$scope.showDashboardPanel = function(panelName, e) {
if (e) {
e.preventDefault();
}
resetPanels();
if (panelName != 'myInfo') {
$scope.hideSidebar();
$('#dashboard-container').removeClass('col-sm-8').addClass('col-sm-12');
} else {
$scope.showSidebar();
$('#dashboard-container').removeClass('col-sm-12').addClass('col-sm-8');
}
$scope.dashboard = true;
$scope.page = false;
switch (panelName) {
case 'messages':
$scope.queryMessages();
$scope.messagesPanel = true;
break;
case 'reviews':
$scope.reviewsPanel = true;
break;
case 'arbitration':
$scope.arbitrationPanel = true;
break;
case 'myInfo':
$scope.myInfoPanel = true;
break;
}
};
$scope.getNotaries = function() {
Connection.send('get_notaries', {});
};
$scope.goToStore = function(url, guid) {
$scope.awaitingStore = guid;
$scope.page = null;
$scope.go(url);
};
$scope.go = function (url) {
$location.path(url);
};
/**
* Query the network for a merchant and then
* show the page
* @guid - GUID of page to load
*/
$scope.queryShop = function(guid) {
$scope.awaitingShop = guid;
console.log('Querying for shop [market]: ', guid);
var query = {
'type': 'query_page',
'findGUID': guid
};
$scope.page = null;
Connection.send('query_page', query);
};
$scope.queryMessages = function() {
// Query for messages
var query = {
'type': 'query_messages'
};
console.log('querying messages');
Connection.send('query_messages', query);
console.log($scope.myself.messages);
};
// Modal Code
$scope.WelcomeModalCtrl = function($scope, $modal, $log, $rootScope) {
// Listen for changes to settings and if welcome is empty then show the welcome modal
$scope.$watch('settings', function() {
console.log('settings', $scope.settings);
if ($scope.settings.welcome == "enable") {
$scope.open('lg', 'static');
} else {
return;
}
/*Else process your data*/
});
$scope.open = function(size, backdrop, scope) {
backdrop = backdrop ? backdrop : true;
var modalInstance = $modal.open({
templateUrl: 'partials/welcome.html',
controller: ModalInstanceCtrl,
size: size,
backdrop: backdrop,
resolve: {
settings: function() {
return $scope.settings;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
var ModalInstanceCtrl = function($scope, $modalInstance, settings) {
$scope.settings = settings;
// $scope.selected = {
// item: $scope.items[0]
// };
//
$scope.welcome = settings.welcome;
$scope.ok = function() {
Connection.send('welcome_dismissed', {});
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.ComposeMessageCtrl = function($scope, $modal, $log) {
$scope.$on("compose_message", function(event, args) {
$scope.bm_address = args.bm_address;
$scope.size = args.size;
$scope.subject = args.subject;
$scope.myself = args.myself;
$scope.compose($scope.size, $scope.myself, $scope.bm_address, $scope.subject);
});
$scope.compose = function(size, myself, to_address, msg) {
var composeModal = $modal.open({
templateUrl: 'partials/modal/composeMessage.html',
controller: $scope.ComposeMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
to_address: function() {
return to_address;
},
msg: function() {
return msg;
},
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('messages');
};
composeModal.result.then(
afterFunc,
function() {
$scope.queryMessages();
$log.info('Modal dismissed at: ' + new Date());
}
);
};
$scope.view = function(size, myself, to_address, msg) {
var viewModal = $modal.open({
templateUrl: 'partials/modal/viewMessage.html',
controller: $scope.ViewMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
to_address: function() {
return to_address;
},
msg: function() {
return msg;
}
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('messages');
};
viewModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
};
$scope.ViewMessageInstanceCtrl = function($scope, $modalInstance, myself, to_address, msg) {
$scope.myself = myself;
$scope.my_address = myself.bitmessage;
$scope.to_address = to_address;
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.toAddress = msg.fromAddress;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
console.log('sending message with subject ' + subject);
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.ComposeMessageInstanceCtrl = function($scope, $modalInstance, myself, to_address, msg) {
$scope.myself = myself;
$scope.to_address = to_address;
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.toAddress = msg.fromAddress;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
$scope.NewMessageCtrl = function($scope, $modal, $log) {
$scope.$on("compose_inbox_message", function(event, args) {
console.log('compose_inbox_message');
$scope.guid = args.guid;
$scope.size = args.size;
$scope.subject = args.subject;
$scope.myself = args.myself;
$scope.compose($scope.size, $scope.myself, $scope.guid, $scope.subject);
});
$scope.guid_to_nickname = function(guid) {
if(guid == $scope.myself.guid) {
return $scope.myself.settings.nickname;
}
for(var peer in $scope.myself.peers) {
peer = $scope.myself.peers[peer];
if(peer.guid == guid) {
return peer.nick;
}
}
return '';
};
$scope.compose = function(size, myself, recipient, msg) {
var composeModal = $modal.open({
templateUrl: 'partials/modal/newMessage.html',
controller: $scope.NewMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
recipient: function() {
return recipient;
},
msg: function() {
return msg;
},
scope: function() {
return $scope;
}
},
size: size
});
var afterFunc = function() {
return;
};
composeModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
$scope.view = function(size, myself, msg) {
var viewModal = $modal.open({
templateUrl: 'partials/modal/viewInboxMessage.html',
controller: ViewInboxMessageInstanceCtrl,
resolve: {
myself: function() {
return myself;
},
msg: function() {
return msg;
},
scope: function() {
return $scope;
}
},
size: size
});
var afterFunc = function() {
$scope.showDashboardPanel('inbox');
};
viewModal.result.then(
afterFunc,
function() {
$log.info('Modal dismissed at: ' + new Date());
}
);
};
};
$scope.NewMessageInstanceCtrl = function($scope, $modalInstance, myself, recipient, msg, scope) {
function guid_to_peer(guid) {
for(var peer in $scope.myself.peers) {
peer = $scope.myself.peers[peer];
if(peer.guid == guid) {
return peer;
}
}
return {};
}
$scope.myself = myself;
$scope.recipient = (recipient !== '') ? guid_to_peer(recipient) : '';
$scope.msg = msg;
// Fill in form if msg is passed - reply mode
if (msg !== null) {
$scope.recipient = msg.recipient;
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
var quote_msg = msg.message.replace(quote_re, "> $1");
$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (sendMessageForm.$invalid) {
return;
}
var query = {
'type': 'send_inbox_message',
'recipient': this.recipient.guid,
'subject': subject.value,
'body': body.value
};
Connection.send('send_inbox_message', query);
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
var ViewInboxMessageInstanceCtrl = function($scope, $modalInstance, myself, msg, scope) {
$scope.myself = myself;
$scope.inbox = {};
$scope.inbox.message = msg;
$scope.inbox.message.nickname = scope.guid_to_nickname(msg.sender_guid);
console.log('test', $scope);
// Fill in form if msg is passed - reply mode
if (msg !== null) {
// Make sure subject start with RE:
var sj = msg.subject;
if (sj.match(/^RE:/) === null) {
sj = "RE: " + sj;
}
$scope.subject = sj;
// Quote message
var quote_re = /^(.*?)/mg;
//var quote_msg = $scope.msg.body.replace(quote_re, "> $1");
//$scope.body = "\n" + quote_msg;
}
$scope.send = function() {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (composeForm.$invalid) {
return;
}
var query = {
'type': 'send_message',
'to': toAddress.value,
'subject': subject.value,
'body': body.value
};
console.log('sending message with subject ' + subject);
Connection.send('send_message', query);
$modalInstance.close();
};
$scope.close = function() {
$modalInstance.dismiss('cancel');
};
};
// Modal Code
$scope.AddNodeModalCtrl = function($scope, $modal, $log) {
$scope.open = function(size, backdrop, scope) {
backdrop = backdrop ? backdrop : true;
var modalInstance = $modal.open({
templateUrl: 'partials/modal/addNode.html',
controller: AddNodeModalInstance,
size: size,
backdrop: backdrop,
resolve: {}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
var AddNodeModalInstance = function($scope, $modalInstance) {
$scope.addGUID = function(newGUID) {
if (newGUID.length == 40 && newGUID.match(/^[A-Za-z0-9]+$/)) {
Connection.send('add_node', {
'type': 'add_guid',
'guid': newGUID
});
console.log('Added node by GUID');
Notifier.success('Success', 'GUID is valid');
} else {
Notifier.info('Failure', 'GUID is not valid');
}
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
}
]);
| Only call handlers once
| html/controllers/market.js | Only call handlers once | <ide><path>tml/controllers/market.js
<ide> Connection.$on('peer', function(e, msg){ $scope.add_peer(msg); });
<ide> Connection.$on('goodbye', function(e, msg){ $scope.goodbye(msg); });
<ide> Connection.$on('hello_response', function(e, msg){ $scope.hello_response(msg); });
<add> listeners.peers = [];
<ide> Connection.$on('peers', function(e, msg){ $scope.update_peers(msg); });
<ide> Connection.$on('peer_remove', function(e, msg){ $scope.remove_peer(msg); });
<ide> if(!listeners.hasOwnProperty('inbox_count')) {
<ide> }
<ide> Connection.$on('myself', function(e, msg){ $scope.parse_myself(msg); });
<ide> Connection.$on('shout', function(e, msg){ $scope.parse_shout(msg); });
<add>
<add> listeners.btc_ticker = [];
<ide> Connection.$on('btc_ticker', function(e, msg){ $scope.parse_btc_ticker(msg); });
<ide> Connection.$on('log_output', function(e, msg){ $scope.parse_log_output(msg); });
<ide> Connection.$on('messages', function(e, msg){ $scope.parse_messages(msg); });
<ide> console.log('settings', $scope.settings);
<ide> if ($scope.settings.welcome == "enable") {
<ide> $scope.open('lg', 'static');
<add> Connection.send('welcome_dismissed', {});
<ide> } else {
<ide> return;
<ide> } |
|
Java | apache-2.0 | dce620c83fe67e787c8c4dd6428b95c9f2570d56 | 0 | IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.refset.clone;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import com.b2international.snowowl.core.ApplicationContext;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.SnomedRefSetEditingContext;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry.Fields;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.b2international.snowowl.snomed.snomedrefset.SnomedComplexMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedMappingRefSet;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSet;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRegularRefSet;
import com.b2international.snowowl.snomed.snomedrefset.SnomedSimpleMapRefSetMember;
import com.google.common.collect.Lists;
/**
* Clones the members of a given {@link SnomedRefSet reference set}.
*/
public class SnomedRefSetCloner {
private final SnomedRefSetEditingContext editingContext;
public SnomedRefSetCloner(SnomedRefSetEditingContext editingContext) {
this.editingContext = editingContext;
}
/**
* Loads the members of the original reference set from the index and clones them into new {@link SnomedRefSetMember} instances.
* @param cloneRefSet
*
* @param originalRefSetId the identifier of the reference set to clone
* @param originalRefSetType the type of the reference set to clone
* @param monitor the progress monitor
* @return
*/
public List<SnomedRefSetMember> cloneRefSetMembers(SnomedRegularRefSet cloneRefSet, String originalRefSetId, SnomedRefSetType originalRefSetType, IProgressMonitor monitor) {
SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
SubMonitor loadChildMonitor = subMonitor.newChild(1);
loadChildMonitor.setTaskName("Loading reference set members...");
loadChildMonitor.setWorkRemaining(1);
final SnomedReferenceSetMembers originalMembers = SnomedRequests.prepareSearchMember()
.all()
.filterByRefSet(originalRefSetId)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, editingContext.getBranch())
.execute(ApplicationContext.getServiceForClass(IEventBus.class))
.getSync();
loadChildMonitor.worked(1);
SubMonitor cloneChildMonitor = subMonitor.newChild(1);
cloneChildMonitor.setTaskName("Cloning reference set members...");
cloneChildMonitor.setWorkRemaining(originalMembers.getTotal());
List<SnomedRefSetMember> newMembers = Lists.newArrayList();
for (SnomedReferenceSetMember originalMember : originalMembers) {
final String referencedComponentId = originalMember.getReferencedComponent().getId();
final SnomedRefSetMember newRefSetMember;
// TODO: Add support for missing reference set types (concrete domain, extended map)
switch (originalRefSetType) {
case ATTRIBUTE_VALUE: {
final String valueId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_VALUE_ID);
newRefSetMember = editingContext.createAttributeValueRefSetMember(referencedComponentId, valueId, originalMember.getModuleId(), cloneRefSet);
break;
}
case QUERY: {
final String query = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_QUERY);
newRefSetMember = editingContext.createQueryRefSetMember(referencedComponentId, query, originalMember.getModuleId(), cloneRefSet);
break;
}
case SIMPLE: {
newRefSetMember = editingContext.createSimpleTypeRefSetMember(referencedComponentId, originalMember.getModuleId(), cloneRefSet);
break;
}
case COMPLEX_MAP: {
final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
final SnomedComplexMapRefSetMember newComplexMapRefSetMember = editingContext.createComplexMapRefSetMember(referencedComponentId,
mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
newComplexMapRefSetMember.setCorrelationId((String) originalMember.getProperties().get(Fields.CORRELATION_ID));
newComplexMapRefSetMember.setMapAdvice((String) originalMember.getProperties().get(Fields.MAP_ADVICE));
newComplexMapRefSetMember.setMapGroup((Integer) originalMember.getProperties().get(Fields.MAP_GROUP));
newComplexMapRefSetMember.setMapPriority((Integer) originalMember.getProperties().get(Fields.MAP_PRIORITY));
newComplexMapRefSetMember.setMapRule((String) originalMember.getProperties().get(Fields.MAP_RULE));
newRefSetMember = newComplexMapRefSetMember;
break;
}
case SIMPLE_MAP: {
final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
newRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId,
mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
break;
}
case SIMPLE_MAP_WITH_DESCRIPTION: {
final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
final String mapTargetDescription = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION);
final SnomedSimpleMapRefSetMember newSimpleMapRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId,
mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
newSimpleMapRefSetMember.setMapTargetComponentDescription(mapTargetDescription);
newRefSetMember = newSimpleMapRefSetMember;
break;
}
default: {
throw new RuntimeException("Unhandled reference set type: " + originalRefSetType);
}
}
newMembers.add(newRefSetMember);
cloneChildMonitor.worked(1);
}
return newMembers;
}
}
| snomed/com.b2international.snowowl.snomed.refset.core/src/com/b2international/snowowl/snomed/refset/clone/SnomedRefSetCloner.java | /*
* Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.refset.clone;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import com.b2international.snowowl.core.ApplicationContext;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.snomed.common.SnomedRf2Headers;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.SnomedRefSetEditingContext;
import com.b2international.snowowl.snomed.datastore.index.entry.SnomedRefSetMemberIndexEntry.Fields;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.b2international.snowowl.snomed.snomedrefset.SnomedComplexMapRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedMappingRefSet;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSet;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRegularRefSet;
import com.google.common.collect.Lists;
/**
* Clones the members of a given {@link SnomedRefSet reference set}.
*
*/
public class SnomedRefSetCloner {
private final SnomedRefSetEditingContext editingContext;
public SnomedRefSetCloner(SnomedRefSetEditingContext editingContext) {
this.editingContext = editingContext;
}
/**
* Loads the members of the original reference set from the index and clones them into new {@link SnomedRefSetMember} instances.
* @param cloneRefSet
*
* @param originalRefSetId the identifier of the reference set to clone
* @param originalRefSetType the type of the reference set to clone
* @param monitor the progress monitor
* @return
*/
public List<SnomedRefSetMember> cloneRefSetMembers(SnomedRegularRefSet cloneRefSet, String originalRefSetId, SnomedRefSetType originalRefSetType, IProgressMonitor monitor) {
SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
SubMonitor loadChildMonitor = subMonitor.newChild(1);
loadChildMonitor.setTaskName("Loading reference set members...");
loadChildMonitor.setWorkRemaining(1);
final SnomedReferenceSetMembers originalMembers = SnomedRequests.prepareSearchMember()
.all()
.filterByRefSet(originalRefSetId)
.build(SnomedDatastoreActivator.REPOSITORY_UUID, editingContext.getBranch())
.execute(ApplicationContext.getServiceForClass(IEventBus.class))
.getSync();
loadChildMonitor.worked(1);
SubMonitor cloneChildMonitor = subMonitor.newChild(1);
cloneChildMonitor.setTaskName("Cloning reference set members...");
cloneChildMonitor.setWorkRemaining(originalMembers.getTotal());
List<SnomedRefSetMember> newMembers = Lists.newArrayList();
for (SnomedReferenceSetMember originalMember : originalMembers) {
final String referencedComponentId = originalMember.getReferencedComponent().getId();
SnomedRefSetMember newRefSetMember;
switch (originalRefSetType) {
case ATTRIBUTE_VALUE:
final String valueId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_VALUE_ID);
newRefSetMember = editingContext.createAttributeValueRefSetMember(referencedComponentId, valueId, originalMember.getModuleId(), cloneRefSet);
break;
case QUERY:
final String query = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_QUERY);
newRefSetMember = editingContext.createQueryRefSetMember(referencedComponentId, query, originalMember.getModuleId(), cloneRefSet);
break;
case SIMPLE:
newRefSetMember = editingContext.createSimpleTypeRefSetMember(referencedComponentId, originalMember.getModuleId(), cloneRefSet);
break;
case COMPLEX_MAP:
String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
SnomedComplexMapRefSetMember newComplexMapRefSetMember = editingContext.createComplexMapRefSetMember(referencedComponentId, mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
newComplexMapRefSetMember.setCorrelationId((String) originalMember.getProperties().get(Fields.CORRELATION_ID));
newComplexMapRefSetMember.setMapAdvice((String) originalMember.getProperties().get(Fields.MAP_ADVICE));
newComplexMapRefSetMember.setMapGroup((Integer) originalMember.getProperties().get(Fields.MAP_GROUP));
newComplexMapRefSetMember.setMapPriority((Integer) originalMember.getProperties().get(Fields.MAP_PRIORITY));
newComplexMapRefSetMember.setMapRule((String) originalMember.getProperties().get(Fields.MAP_RULE));
newRefSetMember = newComplexMapRefSetMember;
break;
case SIMPLE_MAP:
mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
newRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId, mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
break;
default:
throw new RuntimeException("Unhandled reference set type: " + originalRefSetType);
}
newMembers.add(newRefSetMember);
cloneChildMonitor.worked(1);
}
return newMembers;
}
} | SO-3007: Separate cloning steps for simple map and "simple map with...
...map target description" reference set types in SnomedRefSetCloner | snomed/com.b2international.snowowl.snomed.refset.core/src/com/b2international/snowowl/snomed/refset/clone/SnomedRefSetCloner.java | SO-3007: Separate cloning steps for simple map and "simple map with... | <ide><path>nomed/com.b2international.snowowl.snomed.refset.core/src/com/b2international/snowowl/snomed/refset/clone/SnomedRefSetCloner.java
<ide> /*
<del> * Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
<add> * Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
<ide> import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType;
<ide> import com.b2international.snowowl.snomed.snomedrefset.SnomedRegularRefSet;
<add>import com.b2international.snowowl.snomed.snomedrefset.SnomedSimpleMapRefSetMember;
<ide> import com.google.common.collect.Lists;
<ide>
<ide> /**
<ide> * Clones the members of a given {@link SnomedRefSet reference set}.
<del> *
<ide> */
<ide> public class SnomedRefSetCloner {
<ide>
<ide>
<ide> for (SnomedReferenceSetMember originalMember : originalMembers) {
<ide> final String referencedComponentId = originalMember.getReferencedComponent().getId();
<del> SnomedRefSetMember newRefSetMember;
<add> final SnomedRefSetMember newRefSetMember;
<add>
<add> // TODO: Add support for missing reference set types (concrete domain, extended map)
<ide> switch (originalRefSetType) {
<del> case ATTRIBUTE_VALUE:
<del> final String valueId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_VALUE_ID);
<del> newRefSetMember = editingContext.createAttributeValueRefSetMember(referencedComponentId, valueId, originalMember.getModuleId(), cloneRefSet);
<del> break;
<del> case QUERY:
<del> final String query = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_QUERY);
<del> newRefSetMember = editingContext.createQueryRefSetMember(referencedComponentId, query, originalMember.getModuleId(), cloneRefSet);
<del> break;
<del> case SIMPLE:
<del> newRefSetMember = editingContext.createSimpleTypeRefSetMember(referencedComponentId, originalMember.getModuleId(), cloneRefSet);
<del> break;
<del> case COMPLEX_MAP:
<del> String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
<del> SnomedComplexMapRefSetMember newComplexMapRefSetMember = editingContext.createComplexMapRefSetMember(referencedComponentId, mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
<del> newComplexMapRefSetMember.setCorrelationId((String) originalMember.getProperties().get(Fields.CORRELATION_ID));
<del> newComplexMapRefSetMember.setMapAdvice((String) originalMember.getProperties().get(Fields.MAP_ADVICE));
<del> newComplexMapRefSetMember.setMapGroup((Integer) originalMember.getProperties().get(Fields.MAP_GROUP));
<del> newComplexMapRefSetMember.setMapPriority((Integer) originalMember.getProperties().get(Fields.MAP_PRIORITY));
<del> newComplexMapRefSetMember.setMapRule((String) originalMember.getProperties().get(Fields.MAP_RULE));
<del> newRefSetMember = newComplexMapRefSetMember;
<del> break;
<del> case SIMPLE_MAP:
<del> mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
<del> newRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId, mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
<del> break;
<del> default:
<del> throw new RuntimeException("Unhandled reference set type: " + originalRefSetType);
<add> case ATTRIBUTE_VALUE: {
<add> final String valueId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_VALUE_ID);
<add> newRefSetMember = editingContext.createAttributeValueRefSetMember(referencedComponentId, valueId, originalMember.getModuleId(), cloneRefSet);
<add> break;
<add> }
<add> case QUERY: {
<add> final String query = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_QUERY);
<add> newRefSetMember = editingContext.createQueryRefSetMember(referencedComponentId, query, originalMember.getModuleId(), cloneRefSet);
<add> break;
<add> }
<add> case SIMPLE: {
<add> newRefSetMember = editingContext.createSimpleTypeRefSetMember(referencedComponentId, originalMember.getModuleId(), cloneRefSet);
<add> break;
<add> }
<add> case COMPLEX_MAP: {
<add> final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
<add> final SnomedComplexMapRefSetMember newComplexMapRefSetMember = editingContext.createComplexMapRefSetMember(referencedComponentId,
<add> mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
<add>
<add> newComplexMapRefSetMember.setCorrelationId((String) originalMember.getProperties().get(Fields.CORRELATION_ID));
<add> newComplexMapRefSetMember.setMapAdvice((String) originalMember.getProperties().get(Fields.MAP_ADVICE));
<add> newComplexMapRefSetMember.setMapGroup((Integer) originalMember.getProperties().get(Fields.MAP_GROUP));
<add> newComplexMapRefSetMember.setMapPriority((Integer) originalMember.getProperties().get(Fields.MAP_PRIORITY));
<add> newComplexMapRefSetMember.setMapRule((String) originalMember.getProperties().get(Fields.MAP_RULE));
<add> newRefSetMember = newComplexMapRefSetMember;
<add> break;
<add> }
<add> case SIMPLE_MAP: {
<add> final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
<add> newRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId,
<add> mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
<add> break;
<add> }
<add> case SIMPLE_MAP_WITH_DESCRIPTION: {
<add> final String mapTargetId = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET);
<add> final String mapTargetDescription = (String) originalMember.getProperties().get(SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION);
<add> final SnomedSimpleMapRefSetMember newSimpleMapRefSetMember = editingContext.createSimpleMapRefSetMember(referencedComponentId,
<add> mapTargetId, originalMember.getModuleId(), (SnomedMappingRefSet) cloneRefSet);
<add>
<add> newSimpleMapRefSetMember.setMapTargetComponentDescription(mapTargetDescription);
<add> newRefSetMember = newSimpleMapRefSetMember;
<add> break;
<add> }
<add> default: {
<add> throw new RuntimeException("Unhandled reference set type: " + originalRefSetType);
<add> }
<ide> }
<add>
<ide> newMembers.add(newRefSetMember);
<ide> cloneChildMonitor.worked(1);
<ide> } |
|
JavaScript | mit | bb808f120065877f20085372001d2a09b8d12514 | 0 | mane115/bulid_html_test,mane115/bulid_html_test | const fs = require('fs');
const config = require('./config');
const readFile = function(dir) {
return new Promise((success, fail) => {
fs.readFile(dir, (err, data) => {
if (err) return fail(err);
success(data.toString())
})
})
}
const rewriteFile = function(dir, data) {
let option = {
flag: 'w'
};
return new Promise((success, fail) => {
fs.writeFile(dir, data, option, err => {
if (err) return fail(err);
console.log(`rewrite file ${dir} success`);
success(data);
})
})
}
const buildFile = async function(dir) {
try {
let html = await readFile(dir);
let tags = html.match(/<script [^>]*>/g);
let link = html.match(/<link [^>]*>/g);
let timeStamp = Date.now();
if (tags && tags.length > 0) {
tags.forEach(tag => {
var tempTag = tag;
if (tag.indexOf(config.dir.controller) === -1 && tag.indexOf(config.dir.util) === -1) {
return;
}
if (tag.indexOf('t=') !== -1) {
tag = tag.replace(/t=[0-9]{13}/g, '');
}
if (tag.indexOf('js?"') !== -1 || tag.indexOf("js?'") !== -1) {
tag = tag.replace('js?', 'js')
}
let replace = tag.replace('.js', `.js?t=${timeStamp}`);
html = html.replace(tempTag, replace);
});
}
if (link && link.length > 0) {
link.forEach(tag => {
var tempTag = tag;
if (tag.indexOf(config.dir.css) === -1) {
return;
}
if (tag.indexOf('t=') !== -1) {
tag = tag.replace(/t=[0-9]{13}/g, '');
}
if (tag.indexOf('css?"') !== -1 || tag.indexOf("css?'") !== -1) {
tag = tag.replace('css?', 'css')
}
let replace = tag.replace('.css', `.css?t=${timeStamp}`);
html = html.replace(tempTag, replace);
});
}
await rewriteFile(dir, html);
} catch (err) {
console.log(err);
}
}
const init = async function() {
try {
let commonDir = config.views ? config.views : '.';
config.files.forEach(dir => {
dir = `${commonDir}${dir}`
buildFile(dir)
})
} catch (err) {
console.log(err);
}
}
init()
| app.js | const fs = require('fs');
const config = require('./config');
const readFile = function(dir) {
return new Promise((success, fail) => {
fs.readFile(dir, (err, data) => {
if (err) return fail(err);
success(data.toString())
})
})
}
const rewriteFile = function(dir, data) {
let option = {
flag: 'w'
};
return new Promise((success, fail) => {
fs.writeFile(dir, data, option, err => {
if (err) return fail(err);
console.log(`rewrite file ${dir} success`);
success(data);
})
})
}
const buildFile = async function(dir) {
try {
let html = await readFile(dir);
let tags = html.match(/<script [^>]*>/g);
tags.forEach(tag => {
if (tag.indexOf(config.dir.controller) === -1 && tag.indexOf(config.dir.util) === -1) {
return false;
}
tag = tag.replace(/t=[0-9]{13}/g, '');
let replace = tag.replace('.js', `.js?t=${Date.now()}`);
html = html.replace(tag, replace);
});
await rewriteFile(dir, html);
} catch (err) {
console.log(err);
}
}
const init = async function() {
try {
let commonDir = config.views ? config.views : '.';
config.files.forEach(dir => {
dir = `${commonDir}${dir}`
buildFile(dir)
})
} catch (err) {
console.log(err);
}
}
init() | Create app.js | app.js | Create app.js | <ide><path>pp.js
<ide> try {
<ide> let html = await readFile(dir);
<ide> let tags = html.match(/<script [^>]*>/g);
<del> tags.forEach(tag => {
<del> if (tag.indexOf(config.dir.controller) === -1 && tag.indexOf(config.dir.util) === -1) {
<del> return false;
<del> }
<del> tag = tag.replace(/t=[0-9]{13}/g, '');
<del> let replace = tag.replace('.js', `.js?t=${Date.now()}`);
<del> html = html.replace(tag, replace);
<del> });
<add> let link = html.match(/<link [^>]*>/g);
<add> let timeStamp = Date.now();
<add> if (tags && tags.length > 0) {
<add> tags.forEach(tag => {
<add> var tempTag = tag;
<add> if (tag.indexOf(config.dir.controller) === -1 && tag.indexOf(config.dir.util) === -1) {
<add> return;
<add> }
<add> if (tag.indexOf('t=') !== -1) {
<add> tag = tag.replace(/t=[0-9]{13}/g, '');
<add> }
<add> if (tag.indexOf('js?"') !== -1 || tag.indexOf("js?'") !== -1) {
<add> tag = tag.replace('js?', 'js')
<add> }
<add> let replace = tag.replace('.js', `.js?t=${timeStamp}`);
<add> html = html.replace(tempTag, replace);
<add> });
<add> }
<add> if (link && link.length > 0) {
<add> link.forEach(tag => {
<add> var tempTag = tag;
<add> if (tag.indexOf(config.dir.css) === -1) {
<add> return;
<add> }
<add> if (tag.indexOf('t=') !== -1) {
<add> tag = tag.replace(/t=[0-9]{13}/g, '');
<add> }
<add> if (tag.indexOf('css?"') !== -1 || tag.indexOf("css?'") !== -1) {
<add> tag = tag.replace('css?', 'css')
<add> }
<add> let replace = tag.replace('.css', `.css?t=${timeStamp}`);
<add> html = html.replace(tempTag, replace);
<add> });
<add> }
<ide> await rewriteFile(dir, html);
<ide> } catch (err) {
<ide> console.log(err); |
|
Java | agpl-3.0 | 97df8e6ddc7654a7265101488d71c7ed6b268484 | 0 | clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile | /*
* This program is part of the OpenLMIS logistics management information
* system platform software.
*
* Copyright © 2015 ThoughtWorks, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should
* have received a copy of the GNU Affero General Public License along with
* this program. If not, see http://www.gnu.org/licenses. For additional
* information contact [email protected]
*/
package org.openlmis.core.presenter;
import com.google.inject.Inject;
import org.openlmis.core.exceptions.LMISException;
import org.openlmis.core.exceptions.ViewNotMatchException;
import org.openlmis.core.model.StockCard;
import org.openlmis.core.model.StockMovementItem;
import org.openlmis.core.model.repository.StockRepository;
import org.openlmis.core.view.View;
import org.openlmis.core.view.viewmodel.StockMovementViewModel;
import org.roboguice.shaded.goole.common.base.Function;
import java.util.ArrayList;
import java.util.List;
import static org.roboguice.shaded.goole.common.collect.FluentIterable.from;
public class StockMovementPresenter implements Presenter {
List<StockMovementViewModel> stockMovementModelList;
@Inject
StockRepository stockRepository;
long stockCardId;
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void attachView(View v) throws ViewNotMatchException {
}
public void setStockCard(long stockCardId) {
this.stockCardId = stockCardId;
}
public StockMovementPresenter() {
stockMovementModelList = new ArrayList<>();
}
public List<StockMovementViewModel> getStockMovementModels() {
try {
return from(stockRepository.listLastFive(stockCardId)).transform(new Function<StockMovementItem, StockMovementViewModel>() {
@Override
public StockMovementViewModel apply(StockMovementItem stockMovementItem) {
return new StockMovementViewModel(stockMovementItem);
}
}).toList();
} catch (LMISException e) {
e.printStackTrace();
}
return null;
}
public void saveStockMovement(StockMovementItem stockMovementItem) throws LMISException {
StockCard stockcard = getStockCard(stockCardId);
stockcard.setStockOnHand(stockMovementItem.getStockOnHand());
stockRepository.update(stockcard);
stockMovementItem.setStockCard(stockcard);
stockRepository.saveStockItem(stockMovementItem);
}
public StockCard getStockCard(long stockId) {
try {
return stockRepository.queryStockCardById(stockId);
} catch (LMISException e) {
e.printStackTrace();
}
return null;
}
}
| app/src/main/java/org/openlmis/core/presenter/StockMovementPresenter.java | /*
* This program is part of the OpenLMIS logistics management information
* system platform software.
*
* Copyright © 2015 ThoughtWorks, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should
* have received a copy of the GNU Affero General Public License along with
* this program. If not, see http://www.gnu.org/licenses. For additional
* information contact [email protected]
*/
package org.openlmis.core.presenter;
import com.google.inject.Inject;
import org.openlmis.core.exceptions.LMISException;
import org.openlmis.core.exceptions.ViewNotMatchException;
import org.openlmis.core.model.StockCard;
import org.openlmis.core.model.StockMovementItem;
import org.openlmis.core.model.repository.StockRepository;
import org.openlmis.core.view.View;
import org.openlmis.core.view.viewmodel.StockMovementViewModel;
import org.roboguice.shaded.goole.common.base.Function;
import java.util.ArrayList;
import java.util.List;
import static org.roboguice.shaded.goole.common.collect.FluentIterable.from;
public class StockMovementPresenter implements Presenter {
List<StockMovementViewModel> stockMovementModelList;
@Inject
StockRepository stockRepository;
long stockCardId;
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void attachView(View v) throws ViewNotMatchException {
}
public void setStockCard(long stockCardId) {
this.stockCardId = stockCardId;
}
public StockMovementPresenter() {
stockMovementModelList = new ArrayList<>();
}
public List<StockMovementViewModel> getStockMovementModels() {
try {
return from(stockRepository.listLastFive(stockCardId)).transform(new Function<StockMovementItem, StockMovementViewModel>() {
@Override
public StockMovementViewModel apply(StockMovementItem stockMovementItem) {
return new StockMovementViewModel(stockMovementItem);
}
}).toList();
} catch (LMISException e) {
e.printStackTrace();
}
return null;
}
public void saveStockMovement(StockMovementItem stockMovementItem) throws LMISException {
StockCard stockcard = getStockCard(stockCardId);
stockcard.setStockOnHand(stockMovementItem.getStockOnHand());
stockRepository.update(stockcard);
stockRepository.saveStockItem(stockMovementItem);
}
public StockCard getStockCard(long stockId) {
try {
return stockRepository.queryStockCardById(stockId);
} catch (LMISException e) {
e.printStackTrace();
}
return null;
}
}
| [ ZS ] -[#73] - save stockcard
| app/src/main/java/org/openlmis/core/presenter/StockMovementPresenter.java | [ ZS ] -[#73] - save stockcard | <ide><path>pp/src/main/java/org/openlmis/core/presenter/StockMovementPresenter.java
<ide> StockCard stockcard = getStockCard(stockCardId);
<ide> stockcard.setStockOnHand(stockMovementItem.getStockOnHand());
<ide> stockRepository.update(stockcard);
<add> stockMovementItem.setStockCard(stockcard);
<ide> stockRepository.saveStockItem(stockMovementItem);
<ide> }
<ide> |
|
JavaScript | mit | e7b23c108e592db086181c66c1594b7a9ef39663 | 0 | datahq/frontend,datahq/frontend | 'use strict'
const fs = require('fs')
const path = require('path')
const urllib = require('url')
const express = require('express')
const sm = require('sitemap')
const fetch = require('node-fetch')
const bytes = require('bytes')
const fm = require('front-matter')
const moment = require('moment')
const md5 = require('md5')
const timeago = require('timeago.js')
const puppeteer = require('puppeteer')
const mcache = require('memory-cache')
const slash = require('slash')
var stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const config = require('../config')
const lib = require('../lib')
const utils = require('../lib/utils')
const keywords = require('../public/seo/keywords.json')
const datapackage = require('datapackage')
module.exports = function () {
// eslint-disable-next-line new-cap
const router = express.Router()
const api = new lib.DataHubApi(config)
// Function for caching responses:
const cache = (duration) => {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 60000)
res.sendResponse(body)
}
next()
}
}
}
// Front page:
router.get('/', async (req, res) => {
res.render('home.html', {
title: 'Home'
})
})
// Sitemap:
router.get('/sitemap.xml', async (req, res) => {
// Create sitemap object with existing static paths:
const sitemap = sm.createSitemap({
host: 'https://datahub.io',
cacheTime: 600000,
urls: router.stack.reduce((urls, route) => {
const pathToIgnore = [
'/pay', '/pay/checkout', '/thanks', '/logout',
'/success', '/user/login', '/sitemap.xml', '/dashboard'
]
if (
route.route.path.constructor.name == 'String'
&& !route.route.path.includes(':')
&& !pathToIgnore.includes(route.route.path)
) {
urls.push({
url: urllib.resolve('https://datahub.io', route.route.path),
changefreq: 'monthly'
})
}
return urls
}, [])
})
// Include additional path, e.g., blog posts, awesome pages, docs:
const leftoverPages = [
'/awesome/football', '/awesome/climate-change', '/awesome/linked-open-data',
'/awesome/war-and-peace', '/awesome/world-bank', '/awesome/economic-data',
'/awesome/reference-data', '/awesome/machine-learning-data', '/awesome/inflation',
'/awesome/property-prices', '/awesome/wealth-income-and-inequality', '/awesome/logistics-data',
'/awesome/demographics', '/awesome/education', '/awesome/geojson',
'/awesome/healthcare-data', '/awesome/stock-market-data',
'/docs', '/docs/getting-started/installing-data', '/docs/getting-started/publishing-data',
'/docs/getting-started/push-excel', '/docs/getting-started/getting-data',
'/docs/getting-started/how-to-use-info-cat-and-get-commands-of-data-tool',
'/docs/getting-started/datapackage-find-prepare-share-guide', '/docs/automation',
'/docs/tutorials/js-sdk-tutorial', '/docs/tutorials/auto-publish-your-datasets-using-travis-ci',
'/docs/features/data-cli', '/docs/features/views', '/docs/features/preview-tables-for-your-data',
'/docs/features/auto-generated-csv-json-and-zip', '/docs/features/api',
'/docs/core-data', '/docs/core-data/curators', '/docs/core-data/curators-guide',
'/docs/data-packages', '/docs/data-packages/tabular', '/docs/data-packages/csv',
'/docs/data-packages/publish', '/docs/data-packages/publish-any',
'/docs/data-packages/publish-faq', '/docs/data-packages/publish-geo',
'/docs/data-packages/publish-online', '/docs/data-packages/publish-tabular',
'/docs/misc/markdown', '/docs/faq'
]
fs.readdirSync('blog/').forEach(post => {
leftoverPages.push(`blog/${post.slice(11, -3)}`)
})
leftoverPages.forEach(page => {
sitemap.add({url: urllib.resolve('https://datahub.io', page)})
})
// Add special users' publisher pages and their datasets:
const specialUsers = ['core', 'machine-learning', 'examples', 'world-bank', 'five-thirty-eight']
await Promise.all(specialUsers.map(async user => {
sitemap.add({url: urllib.resolve('https://datahub.io', user)})
let packages = await api.search(`datahub.ownerid="${user}"&size=100`)
packages.results.forEach(pkg => sitemap.add({url: urllib.resolve('https://datahub.io', pkg.id)}))
let total = packages.summary.total
total -= 100
let from = 1
while (total > 0) {
from += 100
packages = await api.search(`datahub.ownerid="${user}"&size=100&from=${from}`)
packages.results.forEach(pkg => sitemap.add({url: urllib.resolve('https://datahub.io', pkg.id)}))
total -= 100
}
}))
// Generate sitemap object into XML and respond:
sitemap.toXML((err, xml) => {
if (err) {
console.log(err)
return res.status(500).end();
}
res.header('Content-Type', 'application/xml')
res.send( xml )
})
})
// Redirects
// Old data-os page to new data-factory:
router.get('/docs/data-os', (req, res) => {
res.redirect(301, '/data-factory')
})
// ----------------------------
// Redirects from old datahub.io to new website
function redirectToDest(dest) {
return (req, res) => {
res.redirect(302, dest)
}
}
// Following paths to be redirected to new "/search" page
router.get([
'/dataset',
'/dataset?res_format=CSV',
'/es/dataset', '/it/dataset', '/fr/dataset', '/zh_CN/dataset'
], redirectToDest('/search'))
// These should be redirected to new "/core" page
router.get([
'/organization/core',
'/dataset/core'
], redirectToDest('/core'))
// Following variations of "iso-3166-1-alpha-2-country-codes" dataset should
// be redirected to new "country-list" dataset.
// There are number of variations due to language/country versions.
router.get([
'/dataset/iso-3166-1-alpha-2-country-codes',
'/dataset/iso-3166-1-alpha-2-country-codes/*',
'/*/dataset/iso-3166-1-alpha-2-country-codes',
'/*/dataset/iso-3166-1-alpha-2-country-codes/*'
], redirectToDest('/core/country-list'))
// All requests related to "us-employment-bls" redirect to new "employment-us"
router.get([
'/dataset/us-employment-bls',
'/dataset/us-employment-bls/*',
'/*/dataset/us-employment-bls',
'/*/dataset/us-employment-bls/*'
], redirectToDest('/core/employment-us'))
// All requests related to "iso-4217-currency-codes" redirect
// to new "currency-codes" dataset
router.get([
'/dataset/iso-4217-currency-codes',
'/dataset/iso-4217-currency-codes/*',
'/*/dataset/iso-4217-currency-codes',
'/*/dataset/iso-4217-currency-codes/*'
], redirectToDest('/core/currency-codes'))
// "standard-and-poors-500-shiller" => "s-and-p-500" under core
router.get([
'/dataset/standard-and-poors-500-shiller',
'/dataset/standard-and-poors-500-shiller/*',
'/*/dataset/standard-and-poors-500-shiller',
'/*/dataset/standard-and-poors-500-shiller/*'
], redirectToDest('/core/s-and-p-500'))
// "cofog" => "cofog" under core
router.get([
'/dataset/cofog',
'/dataset/cofog/*',
'/*/dataset/cofog',
'/*/dataset/cofog/*'
], redirectToDest('/core/cofog'))
// same here
router.get([
'/dataset/gold-prices',
'/dataset/gold-prices/*',
'/*/dataset/gold-prices',
'/*/dataset/gold-prices/*'
], redirectToDest('/core/gold-prices'))
// and here also
router.get([
'/dataset/imf-weo',
'/dataset/imf-weo/*',
'/*/dataset/imf-weo',
'/*/dataset/imf-weo/*'
], redirectToDest('/core/imf-weo'))
// 'global-airport' => 'airport-codes'
router.get('/dataset/global-airports', redirectToDest('/core/airport-codes'))
// 'dblp' => '/awesome/bibliographic-data'
router.get('/dataset/dblp', redirectToDest('/awesome/bibliographic-data'))
// 'yago' => `/awesome/yago`
router.get('/dataset/yago', redirectToDest('/awesome/yago'))
// 'opencorporates' => '/awesome/opencorporates'
router.get('/dataset/opencorporates', redirectToDest('/awesome/opencorporates'))
// Finally, redirections for login and dashboard pages
router.get('/user/login', redirectToDest('/login'))
router.get(['/dashboard/datasets', '/dashboard/groups'], redirectToDest('/dashboard'))
// ----------------------------
// Redirects for old.datahub.io
//
// come first to avoid any risk of conflict with /:owner or /:owner/:dataset
function redirect(path, base='https://old.datahub.io') {
return (req, res) => {
let dest = base + path;
if (req.params[0] && Object.keys(req.query).length > 0) {
let queryString = '?' + req.url.split('?')[1]
dest += '/' + req.params[0] + queryString
} else if (req.params[0]) {
dest += '/' + req.params[0]
}
res.redirect(302, dest);
}
}
const redirectPaths = [
'/organization',
'/api',
'/dataset',
'/user',
'/tag'
]
for(let offset of redirectPaths) {
router.get([offset, offset+'/*'], redirect(offset))
}
// /end redirects
// -------------
router.get('/dashboard', async (req, res, next) => {
if (req.cookies.jwt) {
const isAuthenticated = await api.authenticate(req.cookies.jwt)
if (isAuthenticated) {
const client = req.session.client || 'dashboard-check'
const events = await api.getEvents(`owner="${req.cookies.username}"&size=10`, req.cookies.jwt)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
const packages = await api.search(`datahub.ownerid="${req.cookies.id}"&size=0`, req.cookies.jwt)
const currentUser = utils.getCurrentUser(req.cookies)
let storage, storagePublic, storagePrivate
try {
storage = await api.getStorage({owner: req.cookies.username})
storagePrivate = await api.getStorage({owner: req.cookies.username, findability: 'private'})
storagePublic = storage.totalBytes - storagePrivate.totalBytes
} catch (err) {
// Log the error but continue loading the page without storage info
console.error(err)
}
res.render('dashboard.html', {
title: 'Dashboard',
currentUser,
events: events.results,
totalPackages: packages.summary.total,
publicSpaceUsage: storagePublic ? bytes(storagePublic, {decimalPlaces: 0}) : 'N/A',
privateSpaceUsage: storagePrivate ? bytes(storagePrivate.totalBytes, {decimalPlaces: 0}) : 'N/A',
client
})
} else {
req.flash('message', 'Your token has expired. Please, login to see your dashboard.')
res.redirect('/')
}
} else {
res.status(404).render('404.html', {message: 'Sorry, this page was not found'})
return
}
})
router.get('/login', async (req, res) => {
const providers = await api.authenticate()
const githubLoginUrl = providers.providers.github.url
const googleLoginUrl = providers.providers.google.url
res.render('login.html', {
title: 'Sign up | Login',
githubLoginUrl,
googleLoginUrl
})
})
router.get('/success', async (req, res) => {
const jwt = req.query.jwt
const isAuthenticated = await api.authenticate(jwt)
const client = `login-${req.query.client}`
if (isAuthenticated.authenticated) {
req.session.client = client
res.cookie('jwt', jwt)
res.cookie('email', isAuthenticated.profile.email)
res.cookie('id', isAuthenticated.profile.id)
res.cookie('username', isAuthenticated.profile.username)
res.redirect('/dashboard')
} else {
req.flash('message', 'Something went wrong. Please, try again later.')
res.redirect('/')
}
})
router.get('/logout', async (req, res) => {
res.clearCookie('jwt')
req.flash('message', 'You have been successfully logged out.')
res.redirect('/')
})
// ==============
// Docs (patterns, standards etc)
async function showDoc (req, res) {
if (req.params[0]) {
const page = req.params[0]
const BASE = 'https://raw.githubusercontent.com/datahq/datahub-content/master/'
const filePath = 'docs/' + page + '.md'
const gitpath = BASE + filePath
const editpath = 'https://github.com/datahq/datahub-content/edit/master/' + filePath
const resp = await fetch(gitpath)
const text = await resp.text()
const parsedWithFM = fm(text)
const content = utils.md.render(parsedWithFM.body)
const date = parsedWithFM.attributes.date
? moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY')
: null
const githubPath = '//github.com/okfn/data.okfn.org/blob/master/' + path
res.render('docs.html', {
title: parsedWithFM.attributes.title,
description: parsedWithFM.body.substring(0,200).replace(/\n/g, ' '),
date,
editpath: editpath,
content,
githubPath,
metaImage: parsedWithFM.attributes.image
})
} else {
res.render('docs_home.html', {
title: 'Documentation',
description: 'Learn how to use DataHub. Find out about DataHub features and read the tutorials.'
})
}
}
router.get(['/docs', '/docs/*'], showDoc)
// ===== /end docs
/** Awesome pages. http://datahub.io/awesome
* For this section we will parse, render and
* return pages from the awesome github repo:
* https://github.com/datahubio/awesome
*/
router.get('/awesome', showAwesomePage)
router.get('/awesome/dashboards/:page', showAwesomeDashboardPage)
router.get('/awesome/:page', showAwesomePage)
async function showAwesomeDashboardPage(req, res) {
const page = 'dashboards/' + req.params.page + '.html'
res.render(page, { // attributes are hard coded for now since we have only dashboard:
title: 'Climate Change Dashboard',
description: 'State of the World and Impacts of Global Climate Change.'
})
}
async function showAwesomePage(req, res) {
const BASE = 'https://raw.githubusercontent.com/datahubio/awesome-data/master/'
const path = req.params.page ? req.params.page + '.md' : 'README.md'
//request raw page from github
let gitpath = BASE + path
let editpath = 'https://github.com/datahubio/awesome-data/edit/master/' + path
const resp = await fetch(gitpath)
const text = await resp.text()
// parse the raw .md page and render it with a template.
const parsedWithFrontMatter = fm(text)
const published = parsedWithFrontMatter.attributes.date
const modified = parsedWithFrontMatter.attributes.modified
res.render('awesome.html', {
title: parsedWithFrontMatter.attributes.title,
page: req.params.page,
editpath: editpath,
description: parsedWithFrontMatter.attributes.description,
content: utils.md.render(parsedWithFrontMatter.body),
metaDescription: parsedWithFrontMatter.attributes.description + '\n' + parsedWithFrontMatter.attributes.keywords,
keywords: parsedWithFrontMatter.attributes.keywords,
metaImage: parsedWithFrontMatter.attributes.image,
published: published ? published.toISOString() : '',
modified: modified ? modified.toISOString() : ''
})
}
/* end awesome */
// ==============
// Blog
router.get('/blog', (req, res) => {
const listOfPosts = []
fs.readdirSync('blog/').forEach(post => {
const filePath = `blog/${post}`
const text = fs.readFileSync(filePath, 'utf8')
let parsedWithFM = fm(text)
parsedWithFM.body = utils.md.render(parsedWithFM.body)
parsedWithFM.attributes.date = moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY')
parsedWithFM.attributes.authors = parsedWithFM.attributes.authors.map(author => authors[author])
parsedWithFM.path = `blog/${post.slice(11, -3)}`
listOfPosts.unshift(parsedWithFM)
})
res.render('blog.html', {
title: 'Home',
description: 'DataHub blog posts.',
posts: listOfPosts
})
})
router.get('/blog/:post', showPost)
function showPost(req, res) {
const page = req.params.post
const fileName = fs.readdirSync('blog/').find(post => {
return post.slice(11, -3) === page
})
if (fileName) {
const filePath = `blog/${fileName}`
fs.readFile(filePath, 'utf8', function(err, text) {
if (err) throw err
const parsedWithFM = fm(text)
res.render('post.html', {
title: parsedWithFM.attributes.title,
description: parsedWithFM.body.substring(0,200).replace(/\n/g, ' '),
date: moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY'),
authors: parsedWithFM.attributes.authors.map(author => authors[author]),
content: utils.md.render(parsedWithFM.body),
metaImage: parsedWithFM.attributes.image
})
})
} else {
res.status(404).render('404.html', {message: 'Sorry no post was found'})
return
}
}
const authors = {
'rufuspollock': {name: 'Rufus Pollock', gravatar: md5('[email protected]'), username: 'rufuspollock'},
'anuveyatsu': {name: 'Anuar Ustayev', gravatar: md5('[email protected]'), username: 'anuveyatsu'},
'zelima': {name: 'Irakli Mchedlishvili', gravatar: md5('[email protected]'), username: 'zelima1'},
'mikanebu': {name: 'Meiran Zhiyenbayev', gravatar: md5('[email protected]'), username: 'Mikanebu'},
'akariv': {name: 'Adam Kariv', gravatar: md5('[email protected]'), username: 'akariv'},
'acckiygerman': {name: 'Dmitry German', gravatar: md5('[email protected]'), username: 'AcckiyGerman'},
'branko-dj': {name: 'Branko Djordjevic', gravatar: md5('[email protected]'), username: 'Branko-Dj'},
'svetozarstojkovic': {name: 'Svetozar Stojkovic', gravatar: md5('[email protected]'), username: 'svetozarstojkovic'}
}
// ===== /end blog
// Function for rendering showcase page:
function renderShowcase(revision) {
return async (req, res, next) => {
// Sometimes we're getting situation when owner is undefined, we want to return in such situations:
if (!req.params.owner) return
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
// Hit the resolver to get userid and packageid:
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
// If specStoreStatus API does not respond within 10 sec,
// then proceed to error handler and show 500:
const timeoutObj = setTimeout(() => {
next(`status api timed out for ${req.params.owner}/${req.params.name}`)
return
}, 10000)
// Get the latest successful revision, if does not exist show 404
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
revision ? revision : req.params.revisionId
)
clearTimeout(timeoutObj)
} catch (err) {
next(err)
return
}
// Get the "normalizedDp" depending on revision status:
let normalizedDp = null
let failedPipelines = []
// Id is in `userid/dataset/id` form so we need the latest part:
const revisionId = revisionStatus.id.split('/')[2]
if (revisionStatus.state === 'SUCCEEDED') { // Get it normally
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
} else {
if (revisionStatus.state === 'FAILED') { // Use original dp and collect failed pipelines
normalizedDp = revisionStatus.spec_contents.inputs[0].parameters.descriptor
for (let key in revisionStatus.pipelines) {
if (revisionStatus.pipelines[key].status === 'FAILED') {
failedPipelines.push(revisionStatus.pipelines[key])
} else if (revisionStatus.pipelines[key].status === 'SUCCEEDED' && key.includes('validation_report')) {
// As "validation_report" pipeline SUCCEEDED, we can get reports:
let report = await fetch(revisionStatus.pipelines[key].stats['.dpp']['out-datapackage-url'])
if (report.status === 403) {
try {
const signedUrl = await api.checkForSignedUrl(
revisionStatus.pipelines[key].stats['.dpp']['out-datapackage-url'],
userAndPkgId.userid,
token
)
let res = await fetch(signedUrl.url)
report = await res.json()
} catch (err) {
next(err)
return
}
} else if (report.status === 200) {
report = await report.json()
}
normalizedDp.report = report.resources[0]
normalizedDp = await api.handleReport(normalizedDp, {
ownerid: userAndPkgId.userid,
name: userAndPkgId.packageid,
token
})
}
}
} else if (['INPROGRESS', 'QUEUED'].includes(revisionStatus.state)) {
// We don't want to show showcase page from original dp if dataset is
// private. If so compare userid with hash of user email from cookies:
// Also compare userid with owner (in case of custom ID Eg core)
// TODO: we should probably have API for it.
const emailHash = req.cookies.email ? md5(req.cookies.email) : ''
if (userAndPkgId.userid !== emailHash && userAndPkgId.userid !== req.params.owner) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Only if above stuff is passed we use original dp:
normalizedDp = revisionStatus.spec_contents.inputs[0].parameters.descriptor
}
// When we use original dp.json, "path" for a "resource" can be relative
// but to be able to render views using that "resource" we need full URL
// of it. We can access full URLs from "resource-mapping" property in the
// source API's spec_contents and replace relative paths with it:
normalizedDp.resources.forEach(resource => {
const pathParts = urllib.parse(resource.path)
if (!pathParts.protocol) {
const remotePath = revisionStatus.spec_contents.inputs[0].parameters['resource-mapping'][resource.path]
resource.path = remotePath || resource.path
}
})
// Since "frontend-showcase-js" library renders views according to
// descriptor's "views" property, we need to include "preview" views:
// (in the SUCCEEDED revisions "preview" views are generated)
normalizedDp.views = normalizedDp.views || []
normalizedDp.resources.forEach(resource => {
const view = {
datahub: {
type: 'preview'
},
resources: [
resource.name
],
specType: 'table'
}
normalizedDp.views.push(view)
})
// When we use original dp.json, we only have "readme" property. In the
// showcase page we use "readmeSnippet" property to display short readme
// in the top of the page and "readmeHtml" property to render full readme:
if (normalizedDp.readme) {
normalizedDp.readmeSnippet = utils.makeSmallReadme(normalizedDp.readme)
const readmeCompiled = utils.dpInReadme(normalizedDp.readme, normalizedDp)
normalizedDp.readmeHtml = utils.textToMarkdown(readmeCompiled)
}
}
renderPage(revisionStatus, revision ? true : false)
async function renderPage(status, shortUrl) {
// Check if it's a private dataset and sign urls if so:
if (status.spec_contents.meta.findability === 'private') {
const authzToken = await api.authz(token)
await Promise.all(normalizedDp.resources.map(async resource => {
const pathParts = urllib.parse(resource.path)
if (!pathParts.protocol) {
resource.path = urllib.resolve(
config.get('BITSTORE_URL'),
[userAndPkgId.userid, userAndPkgId.packageid, resource.name, resource.path].join('/')
)
}
let response = await fetch(resource.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
resource.path,
userAndPkgId.userid,
null,
authzToken
)
resource.path = signedUrl.url
}
if (resource.alternates) {
const previewResource = resource.alternates.find(res => res.datahub.type === 'derived/preview')
if (previewResource) {
const pathParts = urllib.parse(previewResource.path)
if (!pathParts.protocol) {
previewResource.path = urllib.resolve(
config.get('BITSTORE_URL'),
[userAndPkgId.userid, userAndPkgId.packageid, previewResource.name, previewResource.path].join('/')
)
}
let response = await fetch(previewResource.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
previewResource.path,
userAndPkgId.userid,
null,
authzToken
)
previewResource.path = signedUrl.url
}
}
}
}))
}
// Get size of this revision:
const [owner, name, revision] = status.id.split('/')
let storage
try {
storage = await api.getStorage({owner, pkgId: name, flowId: revision})
} catch (err) {
// Log the error but continue loading the page without storage info
console.error(err)
}
// Get the seo object from the dict:
let seoDict = keywords
.find(item => item.name === req.params.name)
let metaDescription, datasetKeywords = ''
if (seoDict) {
// Get the general meta description:
const generalMetaDescription = keywords
.find(item => item.name === 'general')
.description
// Get the descriptions for popular datasets:
metaDescription = seoDict.description + ' ' + generalMetaDescription
// Get the keywords:
datasetKeywords = seoDict.keywords.join(',')
// Add keywords to README:
normalizedDp.readmeHtml += `\n<hr>Keywords and keyphrases: ${datasetKeywords.replace(/,/g, ', ')}.`
}
// Get the common keywords:
const generalKeywords = keywords
.find(item => item.name === 'general')
.keywords
.join(',')
// Check if views are available so we can set meta image tags:
let metaImage
if (normalizedDp.resources.length <= normalizedDp.views.length) {
// This means views have regular views on top of preview views:
metaImage = `https://datahub.io/${req.params.owner}/${normalizedDp.name}/view/0.png`
}
// Now render the page:
res.render('showcase.html', {
title: req.params.owner + ' | ' + req.params.name,
dataset: normalizedDp,
owner: req.params.owner,
size: storage ? bytes(storage.totalBytes, {decimalPlaces: 0}) : 'N/A',
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'"),
status: status.state,
failUrl: `/${req.params.owner}/${req.params.name}/v/${revisionId}`,
successUrl: `/${req.params.owner}/${req.params.name}`,
statusApi: `${config.get('API_URL')}/source/${userAndPkgId.userid}/${userAndPkgId.packageid}/${revisionId}`,
revisionId: shortUrl ? null : revisionId,
failedPipelines,
keywords: datasetKeywords + generalKeywords,
metaDescription,
metaImage
})
}
}
}
router.get('/tools/validate', async (req, res) => {
let dataset
let loading_error
if (req.query.q){
try {
dataset = await datapackage.Package.load(req.query.q)
} catch (err) {
loading_error = true
}
}
res.render('validate.html', {
title: 'Validate Datasets',
description: 'Data Package Validator. The online validator checks the data package descriptor (also known as datapackage.json file).',
query: req.query.q,
dataset,
loading_error,
})
})
router.get('/:owner/:name', renderShowcase('successful'))
router.get('/:owner/:name/v/:revisionId', renderShowcase())
router.get('/:owner/:name/datapackage.json', async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
let redirectUrl = `${normalizedDp.path}/datapackage.json`
let resp = await fetch(redirectUrl)
// After changes in pkgstore, we ended up with some datasets that cannot be
// accessed by its revision id unless its revision re-triggered. In such
// cases we can access datapackage.json by using 'latest' string instead of
// revision id:
if (resp.status === 404) {
redirectUrl = redirectUrl.replace(`/${revisionId}/`, '/latest/')
}
if (normalizedDp.datahub.findability === 'private') {
const authzToken = await api.authz(token)
if (resp.status === 403) {
const signedUrl = await api.checkForSignedUrl(
redirectUrl, userAndPkgId.userid, null, authzToken
)
redirectUrl = signedUrl.url
}
}
res.redirect(redirectUrl)
})
router.get('/:owner/:name/r/:fileNameOrIndex', async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
const fileParts = path.parse(req.params.fileNameOrIndex)
const extension = fileParts.ext
const name = fileParts.name
let resource
// Check if file name is a number (check if zero explicitely as 0 evaluates to false in JS)
if (parseInt(name, 10) || parseInt(name, 10) === 0) {
// If number it still can be a file name not index so check it
resource = normalizedDp.resources.find(res => res.name === name)
// Otherwise get resource by index
if (!resource) {
resource = normalizedDp.resources[parseInt(name, 10)]
}
} else {
// If name is not a number then just find resource by name
resource = normalizedDp.resources.find(res => res.name === name)
}
// Check if resource was found and give 404 if not
if (!resource) {
res.status(404).render('404.html', {
message: 'Sorry, we cannot locate that file for you'
})
return
}
// If resource is tabular or geojson + requested extension is HTML,
// then render embeddable HTML table or map:
const isTabular = resource.datahub && resource.datahub.type === 'derived/csv'
if ((isTabular || resource.format === 'geojson') && extension.substring(1) === 'html') {
// Prepare minified dp.json with the required resource:
normalizedDp.resources = [resource]
normalizedDp.views = []
if (isTabular) { // For tabular resource we need to prepare 'preview' view:
const preview = {
"datahub": {
"type": "preview"
},
"resources": [
resource.name
],
"specType": "table"
}
normalizedDp.views.push(preview)
}
// Handle private resources:
if (normalizedDp.datahub.findability === 'private') {
const authzToken = await api.authz(token)
if (resource.alternates) {
const previewResource = resource.alternates.find(res => res.datahub.type === 'derived/preview')
if (previewResource) {
previewResource.path = await getSignedUrl(previewResource.path)
} else {
resource.path = await getSignedUrl(resource.path)
}
} else {
resource.path = await getSignedUrl(resource.path)
}
}
// Render the page with stripped dp:
res.render('view.html', {
title: req.params.name,
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'")
})
return
}
// If resource was found then identify required format by given extension
if (!(resource.format === extension.substring(1))) {
if (resource.alternates) {
resource = resource.alternates.find(res => (extension.substring(1) === res.format && res.datahub.type !== 'derived/preview'))
}
// If given format was not found then show 404
if (!resource) {
res.status(404).render('404.html', {
message: 'Sorry, we cannot locate that file for you'
})
return
}
}
async function getSignedUrl(path) {
const authzToken = await api.authz(token)
let resp = await fetch(path)
if (resp.status === 403) {
const signedUrl = await api.checkForSignedUrl(
path, userAndPkgId.userid, null, authzToken
)
return signedUrl.url
}
}
// If dataset's findability is private then get a signed url for the resource
let finalPath = resource.path
if (normalizedDp.datahub.findability === 'private') {
finalPath = await getSignedUrl(finalPath)
}
res.header('Origin', req.protocol + '://' + req.get('host') + req.originalUrl)
res.redirect(finalPath)
})
// Per view URL - PNG:
router.get('/:owner/:name/view/:viewIndex.png', async (req, res, next) => {
try {
const options = {args: ['--no-sandbox', '--disable-setuid-sandbox']}
const browser = await puppeteer.launch(options)
const page = await browser.newPage()
page.on('error', (err) => {
console.log(`Puppetter error occurred on ${req.originalUrl}: ${err}`)
})
page.on('pageerror', (pageerr) => {
console.log(`Puppetter pageerror occurred on ${req.originalUrl}: ${pageerr}`)
})
let source = `https://datahub.io/${req.params.owner}/${req.params.name}/view/${req.params.viewIndex}`
if (req.query.v) {
source += `?v=${req.query.v}`
}
page.setViewport({width: 1280, height: 800})
await page.goto(source)
await page.waitForSelector('svg', {timeout: 15000})
const dims = await page.evaluate(() => {
const svg = document.querySelector('svg').getBoundingClientRect()
return {
width: svg.width,
height: svg.height
}
})
page.setViewport(dims)
const img = await page.screenshot({fullPage: true})
await browser.close()
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
return res.end(img)
} catch (err) {
if (err.message.includes('timeout')) {
console.log(`Puppetter timeout (15s) occurred on ${req.originalUrl}`)
err.status = 404
}
next(err)
return
}
})
// Per view URL - embed and share (caching response for 1 day or 1440 minutes):
router.get('/:owner/:name/view/:viewNameOrIndex', cache(1440), async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
// First try to find a view by name, e.g., if a number is given but view name is a number:
// We're using "==" here as we want string '1' to be equal to number 1:
let view = normalizedDp.views.find(item => item.name == req.params.viewNameOrIndex)
// 'view' wasn't found, now get a view by index:
view = view || normalizedDp.views[req.params.viewNameOrIndex]
if (!view) { // 'view' wasn't found - return 404
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
// Replace original 'views' property with a single required 'view':
normalizedDp.views = [view]
if (view.resources) { // 'view' has 'resources' property then find required resources:
const newResources = []
view.resources.forEach(res => {
if (res.constructor.name === 'Object') { // It's Object so use its 'name' property:
res = res.name
}
let resource = normalizedDp.resources.find(item => item.name == res)
resource = resource || normalizedDp.resources[res]
newResources.push(resource)
})
// Replace original 'resources' property with a new list that is needed for the 'view':
normalizedDp.resources = newResources
} else { // Use only the first resource as by default:
normalizedDp.resources = [normalizedDp.resources[0]]
}
// Handle private resources:
if (normalizedDp.datahub.findability === 'private') {
await Promise.all(normalizedDp.resources.map(async res => {
let response = await fetch(res.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
res.path,
userAndPkgId.userid,
token
)
res.path = signedUrl.url
}
}))
}
// Render the page with stripped dp:
res.render('view.html', {
title: req.params.name,
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'")
})
})
router.get('/:owner/:name/events', async (req, res, next) => {
// First check if dataset exists
const token = req.cookies.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
// Get the latest successful revision, if does not exist show 404
let latestSuccessfulRevision
try {
latestSuccessfulRevision = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
const revisionId = latestSuccessfulRevision.id.split('/')[2]
const response = await api.getPackageFile(userAndPkgId.userid, req.params.name, undefined, revisionId, token)
if (response.status === 200) {
const events = await api.getEvents(`owner="${req.params.owner}"&dataset="${req.params.name}"`, req.cookies.jwt)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
res.render('events.html', {
events: events.results,
username: req.params.owner,
dataset: req.params.name
})
} else if (response.status === 404) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
} else {
next(response)
}
})
router.get('/search', async (req, res) => {
const token = req.cookies.jwt
const from = req.query.from || 0
const size = req.query.size || 20
let query
if (req.query.q) {
query = `q="${req.query.q}"&size=${size}&from=${from}`
} else {
query = `size=${size}&from=${from}`
}
const packages = await api.search(`${query}`, token)
const total = packages.summary.total
const totalPages = Math.ceil(total/size)
const currentPage = parseInt(from, 10) / 20 + 1
const pages = utils.pagination(currentPage, totalPages)
res.render('search.html', {
title: 'Search Datasets',
description: 'Search for public datasets on DataHub. Quickly find data in various formats: csv, json, excel and more.',
packages,
pages,
currentPage,
query: req.query.q
})
})
router.get('/pricing', (req, res) => {
res.render('pricing.html', {
title: 'Pricing',
description: 'Membership Plans on DataHub'
})
})
router.get('/data-factory', (req, res) => {
res.render('data-factory.html', {
title: 'Data Factory',
description: 'Data Factory - Automate your data processes with our open source framework.'
})
})
router.get('/requests', (req, res) => {
res.render('requests.html', {
title: 'Data Requests',
description: 'Engage the Data Concierge. We offer a service to locate and/or prepare data for you.'
})
})
// Download page
router.get('/download', async (req, res) => {
let desktopAppUrl, binReleaseMacos, binReleaseLinux, binReleaseWindows, etagForDesktop, etagForBinary, msiX64, msiX86
if (req.app.locals.github) {
etagForDesktop = req.app.locals.github.releases.desktop
? req.app.locals.github.releases.desktop.etag : ''
etagForBinary = req.app.locals.github.releases.binary
? req.app.locals.github.releases.binary.etag : ''
} else {
req.app.locals.github = {releases: {}}
}
const desktopReleaseModified = await fetch('https://api.github.com/repos/datahq/data-desktop/releases/latest', {
method: 'GET',
headers: {'If-None-Match': etagForDesktop}
})
const binaryReleaseModified = await fetch('https://api.github.com/repos/datahq/data-cli/releases/latest', {
method: 'GET',
headers: {'If-None-Match': etagForBinary}
})
if (desktopReleaseModified.status === 304) { // No new release
desktopAppUrl = req.app.locals.github.releases.desktop.url
} else { // Go and get new release
let desktopRelease = await fetch('https://api.github.com/repos/datahq/data-desktop/releases/latest')
if (desktopRelease.status === 200) {
const etag = desktopRelease.headers.get('ETag').slice(2)
// Now get URL for downloading dekstop app:
desktopRelease = await desktopRelease.json()
desktopAppUrl = desktopRelease.assets
.find(asset => path.parse(asset.name).ext === '.dmg')
.browser_download_url
// Update desktop release in the app.locals:
const newRelease = {
desktop: {
etag,
url: desktopAppUrl
}
}
req.app.locals.github.releases = Object.assign(
req.app.locals.github.releases,
newRelease
)
} else { // If github api is unavailable then just have a link to releases page
desktopAppUrl = 'https://github.com/datahq/data-desktop/releases'
}
}
if (binaryReleaseModified.status === 304) { // No new release
binReleaseMacos = req.app.locals.github.releases.binary.macos
binReleaseLinux = req.app.locals.github.releases.binary.linux
binReleaseWindows = req.app.locals.github.releases.binary.windows
msiX64 = req.app.locals.github.releases.binary.msiX64
msiX86 = req.app.locals.github.releases.binary.msiX86
} else { // Go and get new release
let binRelease = await fetch('https://api.github.com/repos/datahq/data-cli/releases/latest')
if (binRelease.status === 200) {
const etag = binRelease.headers.get('ETag').slice(2)
// Now get URLs for downloading binaries:
binRelease = await binRelease.json()
binReleaseMacos = binRelease.assets
.find(asset => asset.name.includes('macos.gz'))
.browser_download_url
binReleaseLinux = binRelease.assets
.find(asset => asset.name.includes('linux.gz'))
.browser_download_url
binReleaseWindows = binRelease.assets
.find(asset => asset.name.includes('win.exe.gz'))
.browser_download_url
msiX64 = binRelease.assets
.find(asset => asset.name.includes('data-x64'))
.browser_download_url
msiX86 = binRelease.assets
.find(asset => asset.name.includes('data-x86'))
.browser_download_url
// If msi isn't available yet, use previous version:
msiX64 = msiX64 || req.app.locals.github.releases.binary.msiX64
msiX86 = msiX86 || req.app.locals.github.releases.binary.msiX86
// Update binary release in the app.locals:
const newRelease = {
binary: {
etag,
macos: binReleaseMacos,
linux: binReleaseLinux,
windows: binReleaseWindows,
msiX64,
msiX86
}
}
req.app.locals.github.releases = Object.assign(
req.app.locals.github.releases,
newRelease
)
} else { // If github api is unavailable then just have a link to releases page
binReleaseMacos = 'https://github.com/datahq/data-cli/releases'
binReleaseLinux = 'https://github.com/datahq/data-cli/releases'
binReleaseWindows = 'https://github.com/datahq/data-cli/releases'
msiX64 = 'https://github.com/datahq/data-cli/releases'
msiX86 = 'https://github.com/datahq/data-cli/releases'
}
}
res.render('download.html', {
title: 'Download',
description: 'Command line tool for data wrangling. Download the tool for your OS (linux, mac or windows) and start wrangling, sharing and publishing your data online.',
desktopAppUrl,
binReleaseMacos,
binReleaseLinux,
binReleaseWindows,
msiX64,
msiX86
})
})
// Consulting page
router.get('/hire-us', async (req, res) => {
res.render('consulting.html', {
title: 'Hire Us ',
description: 'We are a team with excellence and beyond. Hire us to build and improve your data-driven project. We have decades of experience building data systems for clients large and small.'
})
})
// Premium data
router.get('/premium-data', async (req, res) => {
res.render('premium-data.html', {
title: "Premium data",
submitted: !!(req.query.done)
})
})
// Thank you page
router.get('/thanks', async (req, res) => {
const dest = req.query.next ? `/${req.query.next}` : '/'
req.flash('message', 'Thank you! We\'ve recieved your request and will get back to you soon!')
res.redirect(dest)
})
//Payments Page
router.get('/pay', (req, res) => {
let paymentSucceeded, amount
if (req.query.amount) {
amount = req.query.amount
} else if (req.query.success) {
paymentSucceeded = req.query.success
} else {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
res.render('pay.html', {
getPayment: true,
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
amount,
paymentSucceeded
})
})
//Payment Charging the amount
router.post('/pay/checkout',(req,res) => {
var token = req.body.stripeToken
var chargeAmount = req.body.chargeAmount
const charge = stripe.charges.create({
amount: chargeAmount,
currency: 'usd',
description: 'Data Requests',
source: token,
}, (err, charge) => {
if(err){
req.flash('message', err.message)
res.redirect('/pay?success=0')
} else {
res.redirect('/pay?success=1')
}
})
})
// MUST come last in order to catch all the publisher pages
router.get('/:owner', async (req, res) => {
// First check if user exists using resolver
const userProfile = await api.getProfile(req.params.owner)
if (!userProfile.found) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
const token = req.cookies.jwt
// Get the latest available 10 events:
const events = await api.getEvents(`owner="${req.params.owner}"&size=10`, token)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
// Fetch information about the publisher:
const joinDate = new Date(userProfile.profile.join_date)
const joinYear = joinDate.getUTCFullYear()
const joinMonth = joinDate.toLocaleString('en-us', { month: "long" })
// Pagination - show 20 items per page:
const from = req.query.from || 0
const size = req.query.size || 20
const query = req.query.q ? `&q="${req.query.q}"` : ''
const packages = await api.search(`datahub.ownerid="${userProfile.profile.id}"${query}&size=${size}&from=${from}`, token)
const total = packages.summary.total
const totalPages = Math.ceil(total/size)
const currentPage = parseInt(from, 10) / 20 + 1
const pages = utils.pagination(currentPage, totalPages)
let title, description = ''
if (req.params.owner === 'core') {
title = 'Core Datasets'
description = 'Core datasets maintained by the DataHub team. Important, commonly-used data as high quality, easy-to-use & open data packages. Download data tables in csv (excel) and json.'
} else if (req.params.owner === 'machine-learning') {
title = 'Machine Learning Datasets'
description = 'Machine Learning / Statistical Data. Examples of machine learning datasets. Machine learning data sets on the DataHub under the @machine-learning account.'
} else {
title = req.params.owner + ' datasets'
description = userProfile.profile.name
}
const avatar = userProfile.profile.avatar_url || `https://www.gravatar.com/avatar/${userProfile.profile.gravatar}?s=300&d=https%3A%2F%2Ftesting.datahub.io%2Fstatic%2Fimg%2Flogo-cube03.png`
res.render('owner.html', {
title,
description,
packages,
pages,
currentPage,
events: events.results,
avatar,
joinDate: joinMonth + ' ' + joinYear,
owner: req.params.owner,
name: userProfile.profile.name,
queryString: req.query.q || '',
query: req.query.q ? `&q=${req.query.q}` : ''
})
})
return router
}
| routes/index.js | 'use strict'
const fs = require('fs')
const path = require('path')
const urllib = require('url')
const express = require('express')
const sm = require('sitemap')
const fetch = require('node-fetch')
const bytes = require('bytes')
const fm = require('front-matter')
const moment = require('moment')
const md5 = require('md5')
const timeago = require('timeago.js')
const puppeteer = require('puppeteer')
const mcache = require('memory-cache')
const slash = require('slash')
var stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const config = require('../config')
const lib = require('../lib')
const utils = require('../lib/utils')
const keywords = require('../public/seo/keywords.json')
const datapackage = require('datapackage')
module.exports = function () {
// eslint-disable-next-line new-cap
const router = express.Router()
const api = new lib.DataHubApi(config)
// Function for caching responses:
const cache = (duration) => {
return (req, res, next) => {
let key = '__express__' + req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 60000)
res.sendResponse(body)
}
next()
}
}
}
// Front page:
router.get('/', async (req, res) => {
res.render('home.html', {
title: 'Home'
})
})
// Sitemap:
router.get('/sitemap.xml', async (req, res) => {
// Create sitemap object with existing static paths:
const sitemap = sm.createSitemap({
host: 'https://datahub.io',
cacheTime: 600000,
urls: router.stack.reduce((urls, route) => {
const pathToIgnore = [
'/pay', '/pay/checkout', '/thanks', '/logout',
'/success', '/user/login', '/sitemap.xml', '/dashboard'
]
if (
route.route.path.constructor.name == 'String'
&& !route.route.path.includes(':')
&& !pathToIgnore.includes(route.route.path)
) {
urls.push({
url: urllib.resolve('https://datahub.io', route.route.path),
changefreq: 'monthly'
})
}
return urls
}, [])
})
// Include additional path, e.g., blog posts, awesome pages, docs:
const leftoverPages = [
'/awesome/football', '/awesome/climate-change', '/awesome/linked-open-data',
'/awesome/war-and-peace', '/awesome/world-bank', '/awesome/economic-data',
'/awesome/reference-data', '/awesome/machine-learning-data', '/awesome/inflation',
'/awesome/property-prices', '/awesome/wealth-income-and-inequality', '/awesome/logistics-data',
'/awesome/demographics', '/awesome/education', '/awesome/geojson',
'/awesome/healthcare-data', '/awesome/stock-market-data',
'/docs', '/docs/getting-started/installing-data', '/docs/getting-started/publishing-data',
'/docs/getting-started/push-excel', '/docs/getting-started/getting-data',
'/docs/getting-started/how-to-use-info-cat-and-get-commands-of-data-tool',
'/docs/getting-started/datapackage-find-prepare-share-guide', '/docs/automation',
'/docs/tutorials/js-sdk-tutorial', '/docs/tutorials/auto-publish-your-datasets-using-travis-ci',
'/docs/features/data-cli', '/docs/features/views', '/docs/features/preview-tables-for-your-data',
'/docs/features/auto-generated-csv-json-and-zip', '/docs/features/api',
'/docs/core-data', '/docs/core-data/curators', '/docs/core-data/curators-guide',
'/docs/data-packages', '/docs/data-packages/tabular', '/docs/data-packages/csv',
'/docs/data-packages/publish', '/docs/data-packages/publish-any',
'/docs/data-packages/publish-faq', '/docs/data-packages/publish-geo',
'/docs/data-packages/publish-online', '/docs/data-packages/publish-tabular',
'/docs/misc/markdown', '/docs/faq'
]
fs.readdirSync('blog/').forEach(post => {
leftoverPages.push(`blog/${post.slice(11, -3)}`)
})
leftoverPages.forEach(page => {
sitemap.add({url: urllib.resolve('https://datahub.io', page)})
})
// Add special users' publisher pages and their datasets:
const specialUsers = ['core', 'machine-learning', 'examples', 'world-bank', 'five-thirty-eight']
await Promise.all(specialUsers.map(async user => {
sitemap.add({url: urllib.resolve('https://datahub.io', user)})
let packages = await api.search(`datahub.ownerid="${user}"&size=100`)
packages.results.forEach(pkg => sitemap.add({url: urllib.resolve('https://datahub.io', pkg.id)}))
let total = packages.summary.total
total -= 100
let from = 1
while (total > 0) {
from += 100
packages = await api.search(`datahub.ownerid="${user}"&size=100&from=${from}`)
packages.results.forEach(pkg => sitemap.add({url: urllib.resolve('https://datahub.io', pkg.id)}))
total -= 100
}
}))
// Generate sitemap object into XML and respond:
sitemap.toXML((err, xml) => {
if (err) {
console.log(err)
return res.status(500).end();
}
res.header('Content-Type', 'application/xml')
res.send( xml )
})
})
// Redirects
// Old data-os page to new data-factory:
router.get('/docs/data-os', (req, res) => {
res.redirect(301, '/data-factory')
})
// ----------------------------
// Redirects from old datahub.io to new website
function redirectToDest(dest) {
return (req, res) => {
res.redirect(302, dest)
}
}
// Following paths to be redirected to new "/search" page
router.get([
'/dataset',
'/dataset?res_format=CSV',
'/es/dataset', '/it/dataset', '/fr/dataset', '/zh_CN/dataset'
], redirectToDest('/search'))
// These should be redirected to new "/core" page
router.get([
'/organization/core',
'/dataset/core'
], redirectToDest('/core'))
// Following variations of "iso-3166-1-alpha-2-country-codes" dataset should
// be redirected to new "country-list" dataset.
// There are number of variations due to language/country versions.
router.get([
'/dataset/iso-3166-1-alpha-2-country-codes',
'/dataset/iso-3166-1-alpha-2-country-codes/*',
'/*/dataset/iso-3166-1-alpha-2-country-codes',
'/*/dataset/iso-3166-1-alpha-2-country-codes/*'
], redirectToDest('/core/country-list'))
// All requests related to "us-employment-bls" redirect to new "employment-us"
router.get([
'/dataset/us-employment-bls',
'/dataset/us-employment-bls/*',
'/*/dataset/us-employment-bls',
'/*/dataset/us-employment-bls/*'
], redirectToDest('/core/employment-us'))
// All requests related to "iso-4217-currency-codes" redirect
// to new "currency-codes" dataset
router.get([
'/dataset/iso-4217-currency-codes',
'/dataset/iso-4217-currency-codes/*',
'/*/dataset/iso-4217-currency-codes',
'/*/dataset/iso-4217-currency-codes/*'
], redirectToDest('/core/currency-codes'))
// "standard-and-poors-500-shiller" => "s-and-p-500" under core
router.get([
'/dataset/standard-and-poors-500-shiller',
'/dataset/standard-and-poors-500-shiller/*',
'/*/dataset/standard-and-poors-500-shiller',
'/*/dataset/standard-and-poors-500-shiller/*'
], redirectToDest('/core/s-and-p-500'))
// "cofog" => "cofog" under core
router.get([
'/dataset/cofog',
'/dataset/cofog/*',
'/*/dataset/cofog',
'/*/dataset/cofog/*'
], redirectToDest('/core/cofog'))
// same here
router.get([
'/dataset/gold-prices',
'/dataset/gold-prices/*',
'/*/dataset/gold-prices',
'/*/dataset/gold-prices/*'
], redirectToDest('/core/gold-prices'))
// and here also
router.get([
'/dataset/imf-weo',
'/dataset/imf-weo/*',
'/*/dataset/imf-weo',
'/*/dataset/imf-weo/*'
], redirectToDest('/core/imf-weo'))
// 'global-airport' => 'airport-codes'
router.get('/dataset/global-airports', redirectToDest('/core/airport-codes'))
// Finally, redirections for login and dashboard pages
router.get('/user/login', redirectToDest('/login'))
router.get(['/dashboard/datasets', '/dashboard/groups'], redirectToDest('/dashboard'))
// ----------------------------
// Redirects for old.datahub.io
//
// come first to avoid any risk of conflict with /:owner or /:owner/:dataset
function redirect(path, base='https://old.datahub.io') {
return (req, res) => {
let dest = base + path;
if (req.params[0] && Object.keys(req.query).length > 0) {
let queryString = '?' + req.url.split('?')[1]
dest += '/' + req.params[0] + queryString
} else if (req.params[0]) {
dest += '/' + req.params[0]
}
res.redirect(302, dest);
}
}
const redirectPaths = [
'/organization',
'/api',
'/dataset',
'/user',
'/tag'
]
for(let offset of redirectPaths) {
router.get([offset, offset+'/*'], redirect(offset))
}
// /end redirects
// -------------
router.get('/dashboard', async (req, res, next) => {
if (req.cookies.jwt) {
const isAuthenticated = await api.authenticate(req.cookies.jwt)
if (isAuthenticated) {
const client = req.session.client || 'dashboard-check'
const events = await api.getEvents(`owner="${req.cookies.username}"&size=10`, req.cookies.jwt)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
const packages = await api.search(`datahub.ownerid="${req.cookies.id}"&size=0`, req.cookies.jwt)
const currentUser = utils.getCurrentUser(req.cookies)
let storage, storagePublic, storagePrivate
try {
storage = await api.getStorage({owner: req.cookies.username})
storagePrivate = await api.getStorage({owner: req.cookies.username, findability: 'private'})
storagePublic = storage.totalBytes - storagePrivate.totalBytes
} catch (err) {
// Log the error but continue loading the page without storage info
console.error(err)
}
res.render('dashboard.html', {
title: 'Dashboard',
currentUser,
events: events.results,
totalPackages: packages.summary.total,
publicSpaceUsage: storagePublic ? bytes(storagePublic, {decimalPlaces: 0}) : 'N/A',
privateSpaceUsage: storagePrivate ? bytes(storagePrivate.totalBytes, {decimalPlaces: 0}) : 'N/A',
client
})
} else {
req.flash('message', 'Your token has expired. Please, login to see your dashboard.')
res.redirect('/')
}
} else {
res.status(404).render('404.html', {message: 'Sorry, this page was not found'})
return
}
})
router.get('/login', async (req, res) => {
const providers = await api.authenticate()
const githubLoginUrl = providers.providers.github.url
const googleLoginUrl = providers.providers.google.url
res.render('login.html', {
title: 'Sign up | Login',
githubLoginUrl,
googleLoginUrl
})
})
router.get('/success', async (req, res) => {
const jwt = req.query.jwt
const isAuthenticated = await api.authenticate(jwt)
const client = `login-${req.query.client}`
if (isAuthenticated.authenticated) {
req.session.client = client
res.cookie('jwt', jwt)
res.cookie('email', isAuthenticated.profile.email)
res.cookie('id', isAuthenticated.profile.id)
res.cookie('username', isAuthenticated.profile.username)
res.redirect('/dashboard')
} else {
req.flash('message', 'Something went wrong. Please, try again later.')
res.redirect('/')
}
})
router.get('/logout', async (req, res) => {
res.clearCookie('jwt')
req.flash('message', 'You have been successfully logged out.')
res.redirect('/')
})
// ==============
// Docs (patterns, standards etc)
async function showDoc (req, res) {
if (req.params[0]) {
const page = req.params[0]
const BASE = 'https://raw.githubusercontent.com/datahq/datahub-content/master/'
const filePath = 'docs/' + page + '.md'
const gitpath = BASE + filePath
const editpath = 'https://github.com/datahq/datahub-content/edit/master/' + filePath
const resp = await fetch(gitpath)
const text = await resp.text()
const parsedWithFM = fm(text)
const content = utils.md.render(parsedWithFM.body)
const date = parsedWithFM.attributes.date
? moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY')
: null
const githubPath = '//github.com/okfn/data.okfn.org/blob/master/' + path
res.render('docs.html', {
title: parsedWithFM.attributes.title,
description: parsedWithFM.body.substring(0,200).replace(/\n/g, ' '),
date,
editpath: editpath,
content,
githubPath,
metaImage: parsedWithFM.attributes.image
})
} else {
res.render('docs_home.html', {
title: 'Documentation',
description: 'Learn how to use DataHub. Find out about DataHub features and read the tutorials.'
})
}
}
router.get(['/docs', '/docs/*'], showDoc)
// ===== /end docs
/** Awesome pages. http://datahub.io/awesome
* For this section we will parse, render and
* return pages from the awesome github repo:
* https://github.com/datahubio/awesome
*/
router.get('/awesome', showAwesomePage)
router.get('/awesome/dashboards/:page', showAwesomeDashboardPage)
router.get('/awesome/:page', showAwesomePage)
async function showAwesomeDashboardPage(req, res) {
const page = 'dashboards/' + req.params.page + '.html'
res.render(page, { // attributes are hard coded for now since we have only dashboard:
title: 'Climate Change Dashboard',
description: 'State of the World and Impacts of Global Climate Change.'
})
}
async function showAwesomePage(req, res) {
const BASE = 'https://raw.githubusercontent.com/datahubio/awesome-data/master/'
const path = req.params.page ? req.params.page + '.md' : 'README.md'
//request raw page from github
let gitpath = BASE + path
let editpath = 'https://github.com/datahubio/awesome-data/edit/master/' + path
const resp = await fetch(gitpath)
const text = await resp.text()
// parse the raw .md page and render it with a template.
const parsedWithFrontMatter = fm(text)
const published = parsedWithFrontMatter.attributes.date
const modified = parsedWithFrontMatter.attributes.modified
res.render('awesome.html', {
title: parsedWithFrontMatter.attributes.title,
page: req.params.page,
editpath: editpath,
description: parsedWithFrontMatter.attributes.description,
content: utils.md.render(parsedWithFrontMatter.body),
metaDescription: parsedWithFrontMatter.attributes.description + '\n' + parsedWithFrontMatter.attributes.keywords,
keywords: parsedWithFrontMatter.attributes.keywords,
metaImage: parsedWithFrontMatter.attributes.image,
published: published ? published.toISOString() : '',
modified: modified ? modified.toISOString() : ''
})
}
/* end awesome */
// ==============
// Blog
router.get('/blog', (req, res) => {
const listOfPosts = []
fs.readdirSync('blog/').forEach(post => {
const filePath = `blog/${post}`
const text = fs.readFileSync(filePath, 'utf8')
let parsedWithFM = fm(text)
parsedWithFM.body = utils.md.render(parsedWithFM.body)
parsedWithFM.attributes.date = moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY')
parsedWithFM.attributes.authors = parsedWithFM.attributes.authors.map(author => authors[author])
parsedWithFM.path = `blog/${post.slice(11, -3)}`
listOfPosts.unshift(parsedWithFM)
})
res.render('blog.html', {
title: 'Home',
description: 'DataHub blog posts.',
posts: listOfPosts
})
})
router.get('/blog/:post', showPost)
function showPost(req, res) {
const page = req.params.post
const fileName = fs.readdirSync('blog/').find(post => {
return post.slice(11, -3) === page
})
if (fileName) {
const filePath = `blog/${fileName}`
fs.readFile(filePath, 'utf8', function(err, text) {
if (err) throw err
const parsedWithFM = fm(text)
res.render('post.html', {
title: parsedWithFM.attributes.title,
description: parsedWithFM.body.substring(0,200).replace(/\n/g, ' '),
date: moment(parsedWithFM.attributes.date).format('MMMM Do, YYYY'),
authors: parsedWithFM.attributes.authors.map(author => authors[author]),
content: utils.md.render(parsedWithFM.body),
metaImage: parsedWithFM.attributes.image
})
})
} else {
res.status(404).render('404.html', {message: 'Sorry no post was found'})
return
}
}
const authors = {
'rufuspollock': {name: 'Rufus Pollock', gravatar: md5('[email protected]'), username: 'rufuspollock'},
'anuveyatsu': {name: 'Anuar Ustayev', gravatar: md5('[email protected]'), username: 'anuveyatsu'},
'zelima': {name: 'Irakli Mchedlishvili', gravatar: md5('[email protected]'), username: 'zelima1'},
'mikanebu': {name: 'Meiran Zhiyenbayev', gravatar: md5('[email protected]'), username: 'Mikanebu'},
'akariv': {name: 'Adam Kariv', gravatar: md5('[email protected]'), username: 'akariv'},
'acckiygerman': {name: 'Dmitry German', gravatar: md5('[email protected]'), username: 'AcckiyGerman'},
'branko-dj': {name: 'Branko Djordjevic', gravatar: md5('[email protected]'), username: 'Branko-Dj'},
'svetozarstojkovic': {name: 'Svetozar Stojkovic', gravatar: md5('[email protected]'), username: 'svetozarstojkovic'}
}
// ===== /end blog
// Function for rendering showcase page:
function renderShowcase(revision) {
return async (req, res, next) => {
// Sometimes we're getting situation when owner is undefined, we want to return in such situations:
if (!req.params.owner) return
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
// Hit the resolver to get userid and packageid:
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
// If specStoreStatus API does not respond within 10 sec,
// then proceed to error handler and show 500:
const timeoutObj = setTimeout(() => {
next(`status api timed out for ${req.params.owner}/${req.params.name}`)
return
}, 10000)
// Get the latest successful revision, if does not exist show 404
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
revision ? revision : req.params.revisionId
)
clearTimeout(timeoutObj)
} catch (err) {
next(err)
return
}
// Get the "normalizedDp" depending on revision status:
let normalizedDp = null
let failedPipelines = []
// Id is in `userid/dataset/id` form so we need the latest part:
const revisionId = revisionStatus.id.split('/')[2]
if (revisionStatus.state === 'SUCCEEDED') { // Get it normally
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
} else {
if (revisionStatus.state === 'FAILED') { // Use original dp and collect failed pipelines
normalizedDp = revisionStatus.spec_contents.inputs[0].parameters.descriptor
for (let key in revisionStatus.pipelines) {
if (revisionStatus.pipelines[key].status === 'FAILED') {
failedPipelines.push(revisionStatus.pipelines[key])
} else if (revisionStatus.pipelines[key].status === 'SUCCEEDED' && key.includes('validation_report')) {
// As "validation_report" pipeline SUCCEEDED, we can get reports:
let report = await fetch(revisionStatus.pipelines[key].stats['.dpp']['out-datapackage-url'])
if (report.status === 403) {
try {
const signedUrl = await api.checkForSignedUrl(
revisionStatus.pipelines[key].stats['.dpp']['out-datapackage-url'],
userAndPkgId.userid,
token
)
let res = await fetch(signedUrl.url)
report = await res.json()
} catch (err) {
next(err)
return
}
} else if (report.status === 200) {
report = await report.json()
}
normalizedDp.report = report.resources[0]
normalizedDp = await api.handleReport(normalizedDp, {
ownerid: userAndPkgId.userid,
name: userAndPkgId.packageid,
token
})
}
}
} else if (['INPROGRESS', 'QUEUED'].includes(revisionStatus.state)) {
// We don't want to show showcase page from original dp if dataset is
// private. If so compare userid with hash of user email from cookies:
// Also compare userid with owner (in case of custom ID Eg core)
// TODO: we should probably have API for it.
const emailHash = req.cookies.email ? md5(req.cookies.email) : ''
if (userAndPkgId.userid !== emailHash && userAndPkgId.userid !== req.params.owner) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Only if above stuff is passed we use original dp:
normalizedDp = revisionStatus.spec_contents.inputs[0].parameters.descriptor
}
// When we use original dp.json, "path" for a "resource" can be relative
// but to be able to render views using that "resource" we need full URL
// of it. We can access full URLs from "resource-mapping" property in the
// source API's spec_contents and replace relative paths with it:
normalizedDp.resources.forEach(resource => {
const pathParts = urllib.parse(resource.path)
if (!pathParts.protocol) {
const remotePath = revisionStatus.spec_contents.inputs[0].parameters['resource-mapping'][resource.path]
resource.path = remotePath || resource.path
}
})
// Since "frontend-showcase-js" library renders views according to
// descriptor's "views" property, we need to include "preview" views:
// (in the SUCCEEDED revisions "preview" views are generated)
normalizedDp.views = normalizedDp.views || []
normalizedDp.resources.forEach(resource => {
const view = {
datahub: {
type: 'preview'
},
resources: [
resource.name
],
specType: 'table'
}
normalizedDp.views.push(view)
})
// When we use original dp.json, we only have "readme" property. In the
// showcase page we use "readmeSnippet" property to display short readme
// in the top of the page and "readmeHtml" property to render full readme:
if (normalizedDp.readme) {
normalizedDp.readmeSnippet = utils.makeSmallReadme(normalizedDp.readme)
const readmeCompiled = utils.dpInReadme(normalizedDp.readme, normalizedDp)
normalizedDp.readmeHtml = utils.textToMarkdown(readmeCompiled)
}
}
renderPage(revisionStatus, revision ? true : false)
async function renderPage(status, shortUrl) {
// Check if it's a private dataset and sign urls if so:
if (status.spec_contents.meta.findability === 'private') {
const authzToken = await api.authz(token)
await Promise.all(normalizedDp.resources.map(async resource => {
const pathParts = urllib.parse(resource.path)
if (!pathParts.protocol) {
resource.path = urllib.resolve(
config.get('BITSTORE_URL'),
[userAndPkgId.userid, userAndPkgId.packageid, resource.name, resource.path].join('/')
)
}
let response = await fetch(resource.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
resource.path,
userAndPkgId.userid,
null,
authzToken
)
resource.path = signedUrl.url
}
if (resource.alternates) {
const previewResource = resource.alternates.find(res => res.datahub.type === 'derived/preview')
if (previewResource) {
const pathParts = urllib.parse(previewResource.path)
if (!pathParts.protocol) {
previewResource.path = urllib.resolve(
config.get('BITSTORE_URL'),
[userAndPkgId.userid, userAndPkgId.packageid, previewResource.name, previewResource.path].join('/')
)
}
let response = await fetch(previewResource.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
previewResource.path,
userAndPkgId.userid,
null,
authzToken
)
previewResource.path = signedUrl.url
}
}
}
}))
}
// Get size of this revision:
const [owner, name, revision] = status.id.split('/')
let storage
try {
storage = await api.getStorage({owner, pkgId: name, flowId: revision})
} catch (err) {
// Log the error but continue loading the page without storage info
console.error(err)
}
// Get the seo object from the dict:
let seoDict = keywords
.find(item => item.name === req.params.name)
let metaDescription, datasetKeywords = ''
if (seoDict) {
// Get the general meta description:
const generalMetaDescription = keywords
.find(item => item.name === 'general')
.description
// Get the descriptions for popular datasets:
metaDescription = seoDict.description + ' ' + generalMetaDescription
// Get the keywords:
datasetKeywords = seoDict.keywords.join(',')
// Add keywords to README:
normalizedDp.readmeHtml += `\n<hr>Keywords and keyphrases: ${datasetKeywords.replace(/,/g, ', ')}.`
}
// Get the common keywords:
const generalKeywords = keywords
.find(item => item.name === 'general')
.keywords
.join(',')
// Check if views are available so we can set meta image tags:
let metaImage
if (normalizedDp.resources.length <= normalizedDp.views.length) {
// This means views have regular views on top of preview views:
metaImage = `https://datahub.io/${req.params.owner}/${normalizedDp.name}/view/0.png`
}
// Now render the page:
res.render('showcase.html', {
title: req.params.owner + ' | ' + req.params.name,
dataset: normalizedDp,
owner: req.params.owner,
size: storage ? bytes(storage.totalBytes, {decimalPlaces: 0}) : 'N/A',
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'"),
status: status.state,
failUrl: `/${req.params.owner}/${req.params.name}/v/${revisionId}`,
successUrl: `/${req.params.owner}/${req.params.name}`,
statusApi: `${config.get('API_URL')}/source/${userAndPkgId.userid}/${userAndPkgId.packageid}/${revisionId}`,
revisionId: shortUrl ? null : revisionId,
failedPipelines,
keywords: datasetKeywords + generalKeywords,
metaDescription,
metaImage
})
}
}
}
router.get('/tools/validate', async (req, res) => {
let dataset
let loading_error
if (req.query.q){
try {
dataset = await datapackage.Package.load(req.query.q)
} catch (err) {
loading_error = true
}
}
res.render('validate.html', {
title: 'Validate Datasets',
description: 'Data Package Validator. The online validator checks the data package descriptor (also known as datapackage.json file).',
query: req.query.q,
dataset,
loading_error,
})
})
router.get('/:owner/:name', renderShowcase('successful'))
router.get('/:owner/:name/v/:revisionId', renderShowcase())
router.get('/:owner/:name/datapackage.json', async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
let redirectUrl = `${normalizedDp.path}/datapackage.json`
let resp = await fetch(redirectUrl)
// After changes in pkgstore, we ended up with some datasets that cannot be
// accessed by its revision id unless its revision re-triggered. In such
// cases we can access datapackage.json by using 'latest' string instead of
// revision id:
if (resp.status === 404) {
redirectUrl = redirectUrl.replace(`/${revisionId}/`, '/latest/')
}
if (normalizedDp.datahub.findability === 'private') {
const authzToken = await api.authz(token)
if (resp.status === 403) {
const signedUrl = await api.checkForSignedUrl(
redirectUrl, userAndPkgId.userid, null, authzToken
)
redirectUrl = signedUrl.url
}
}
res.redirect(redirectUrl)
})
router.get('/:owner/:name/r/:fileNameOrIndex', async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
const fileParts = path.parse(req.params.fileNameOrIndex)
const extension = fileParts.ext
const name = fileParts.name
let resource
// Check if file name is a number (check if zero explicitely as 0 evaluates to false in JS)
if (parseInt(name, 10) || parseInt(name, 10) === 0) {
// If number it still can be a file name not index so check it
resource = normalizedDp.resources.find(res => res.name === name)
// Otherwise get resource by index
if (!resource) {
resource = normalizedDp.resources[parseInt(name, 10)]
}
} else {
// If name is not a number then just find resource by name
resource = normalizedDp.resources.find(res => res.name === name)
}
// Check if resource was found and give 404 if not
if (!resource) {
res.status(404).render('404.html', {
message: 'Sorry, we cannot locate that file for you'
})
return
}
// If resource is tabular or geojson + requested extension is HTML,
// then render embeddable HTML table or map:
const isTabular = resource.datahub && resource.datahub.type === 'derived/csv'
if ((isTabular || resource.format === 'geojson') && extension.substring(1) === 'html') {
// Prepare minified dp.json with the required resource:
normalizedDp.resources = [resource]
normalizedDp.views = []
if (isTabular) { // For tabular resource we need to prepare 'preview' view:
const preview = {
"datahub": {
"type": "preview"
},
"resources": [
resource.name
],
"specType": "table"
}
normalizedDp.views.push(preview)
}
// Handle private resources:
if (normalizedDp.datahub.findability === 'private') {
const authzToken = await api.authz(token)
if (resource.alternates) {
const previewResource = resource.alternates.find(res => res.datahub.type === 'derived/preview')
if (previewResource) {
previewResource.path = await getSignedUrl(previewResource.path)
} else {
resource.path = await getSignedUrl(resource.path)
}
} else {
resource.path = await getSignedUrl(resource.path)
}
}
// Render the page with stripped dp:
res.render('view.html', {
title: req.params.name,
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'")
})
return
}
// If resource was found then identify required format by given extension
if (!(resource.format === extension.substring(1))) {
if (resource.alternates) {
resource = resource.alternates.find(res => (extension.substring(1) === res.format && res.datahub.type !== 'derived/preview'))
}
// If given format was not found then show 404
if (!resource) {
res.status(404).render('404.html', {
message: 'Sorry, we cannot locate that file for you'
})
return
}
}
async function getSignedUrl(path) {
const authzToken = await api.authz(token)
let resp = await fetch(path)
if (resp.status === 403) {
const signedUrl = await api.checkForSignedUrl(
path, userAndPkgId.userid, null, authzToken
)
return signedUrl.url
}
}
// If dataset's findability is private then get a signed url for the resource
let finalPath = resource.path
if (normalizedDp.datahub.findability === 'private') {
finalPath = await getSignedUrl(finalPath)
}
res.header('Origin', req.protocol + '://' + req.get('host') + req.originalUrl)
res.redirect(finalPath)
})
// Per view URL - PNG:
router.get('/:owner/:name/view/:viewIndex.png', async (req, res, next) => {
try {
const options = {args: ['--no-sandbox', '--disable-setuid-sandbox']}
const browser = await puppeteer.launch(options)
const page = await browser.newPage()
page.on('error', (err) => {
console.log(`Puppetter error occurred on ${req.originalUrl}: ${err}`)
})
page.on('pageerror', (pageerr) => {
console.log(`Puppetter pageerror occurred on ${req.originalUrl}: ${pageerr}`)
})
let source = `https://datahub.io/${req.params.owner}/${req.params.name}/view/${req.params.viewIndex}`
if (req.query.v) {
source += `?v=${req.query.v}`
}
page.setViewport({width: 1280, height: 800})
await page.goto(source)
await page.waitForSelector('svg', {timeout: 15000})
const dims = await page.evaluate(() => {
const svg = document.querySelector('svg').getBoundingClientRect()
return {
width: svg.width,
height: svg.height
}
})
page.setViewport(dims)
const img = await page.screenshot({fullPage: true})
await browser.close()
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
return res.end(img)
} catch (err) {
if (err.message.includes('timeout')) {
console.log(`Puppetter timeout (15s) occurred on ${req.originalUrl}`)
err.status = 404
}
next(err)
return
}
})
// Per view URL - embed and share (caching response for 1 day or 1440 minutes):
router.get('/:owner/:name/view/:viewNameOrIndex', cache(1440), async (req, res, next) => {
let normalizedDp = null
let token = req.cookies.jwt ? req.cookies.jwt : req.query.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
if (!userAndPkgId.userid) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found',
comment: 'You might need to Login to access more datasets'
})
return
}
// Get the specific revision if id is given,
// if not get the latest successful revision, if does not exist show 404
let revisionId = req.query.v
if (!revisionId) {
let revisionStatus
try {
revisionStatus = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
revisionId = revisionStatus.id.split('/')[2]
}
try {
normalizedDp = await api.getPackage(userAndPkgId.userid, userAndPkgId.packageid, revisionId, token)
} catch (err) {
next(err)
return
}
// First try to find a view by name, e.g., if a number is given but view name is a number:
// We're using "==" here as we want string '1' to be equal to number 1:
let view = normalizedDp.views.find(item => item.name == req.params.viewNameOrIndex)
// 'view' wasn't found, now get a view by index:
view = view || normalizedDp.views[req.params.viewNameOrIndex]
if (!view) { // 'view' wasn't found - return 404
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
// Replace original 'views' property with a single required 'view':
normalizedDp.views = [view]
if (view.resources) { // 'view' has 'resources' property then find required resources:
const newResources = []
view.resources.forEach(res => {
if (res.constructor.name === 'Object') { // It's Object so use its 'name' property:
res = res.name
}
let resource = normalizedDp.resources.find(item => item.name == res)
resource = resource || normalizedDp.resources[res]
newResources.push(resource)
})
// Replace original 'resources' property with a new list that is needed for the 'view':
normalizedDp.resources = newResources
} else { // Use only the first resource as by default:
normalizedDp.resources = [normalizedDp.resources[0]]
}
// Handle private resources:
if (normalizedDp.datahub.findability === 'private') {
await Promise.all(normalizedDp.resources.map(async res => {
let response = await fetch(res.path)
if (response.status === 403) {
const signedUrl = await api.checkForSignedUrl(
res.path,
userAndPkgId.userid,
token
)
res.path = signedUrl.url
}
}))
}
// Render the page with stripped dp:
res.render('view.html', {
title: req.params.name,
// eslint-disable-next-line no-useless-escape, quotes
dpId: JSON.stringify(normalizedDp).replace(/\\/g, '\\\\').replace(/\'/g, "\\'")
})
})
router.get('/:owner/:name/events', async (req, res, next) => {
// First check if dataset exists
const token = req.cookies.jwt
const userAndPkgId = await api.resolve(
slash(path.join(req.params.owner, req.params.name))
)
// Get the latest successful revision, if does not exist show 404
let latestSuccessfulRevision
try {
latestSuccessfulRevision = await api.specStoreStatus(
userAndPkgId.userid,
userAndPkgId.packageid,
'successful'
)
} catch (err) {
next(err)
return
}
const revisionId = latestSuccessfulRevision.id.split('/')[2]
const response = await api.getPackageFile(userAndPkgId.userid, req.params.name, undefined, revisionId, token)
if (response.status === 200) {
const events = await api.getEvents(`owner="${req.params.owner}"&dataset="${req.params.name}"`, req.cookies.jwt)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
res.render('events.html', {
events: events.results,
username: req.params.owner,
dataset: req.params.name
})
} else if (response.status === 404) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
} else {
next(response)
}
})
router.get('/search', async (req, res) => {
const token = req.cookies.jwt
const from = req.query.from || 0
const size = req.query.size || 20
let query
if (req.query.q) {
query = `q="${req.query.q}"&size=${size}&from=${from}`
} else {
query = `size=${size}&from=${from}`
}
const packages = await api.search(`${query}`, token)
const total = packages.summary.total
const totalPages = Math.ceil(total/size)
const currentPage = parseInt(from, 10) / 20 + 1
const pages = utils.pagination(currentPage, totalPages)
res.render('search.html', {
title: 'Search Datasets',
description: 'Search for public datasets on DataHub. Quickly find data in various formats: csv, json, excel and more.',
packages,
pages,
currentPage,
query: req.query.q
})
})
router.get('/pricing', (req, res) => {
res.render('pricing.html', {
title: 'Pricing',
description: 'Membership Plans on DataHub'
})
})
router.get('/data-factory', (req, res) => {
res.render('data-factory.html', {
title: 'Data Factory',
description: 'Data Factory - Automate your data processes with our open source framework.'
})
})
router.get('/requests', (req, res) => {
res.render('requests.html', {
title: 'Data Requests',
description: 'Engage the Data Concierge. We offer a service to locate and/or prepare data for you.'
})
})
// Download page
router.get('/download', async (req, res) => {
let desktopAppUrl, binReleaseMacos, binReleaseLinux, binReleaseWindows, etagForDesktop, etagForBinary, msiX64, msiX86
if (req.app.locals.github) {
etagForDesktop = req.app.locals.github.releases.desktop
? req.app.locals.github.releases.desktop.etag : ''
etagForBinary = req.app.locals.github.releases.binary
? req.app.locals.github.releases.binary.etag : ''
} else {
req.app.locals.github = {releases: {}}
}
const desktopReleaseModified = await fetch('https://api.github.com/repos/datahq/data-desktop/releases/latest', {
method: 'GET',
headers: {'If-None-Match': etagForDesktop}
})
const binaryReleaseModified = await fetch('https://api.github.com/repos/datahq/data-cli/releases/latest', {
method: 'GET',
headers: {'If-None-Match': etagForBinary}
})
if (desktopReleaseModified.status === 304) { // No new release
desktopAppUrl = req.app.locals.github.releases.desktop.url
} else { // Go and get new release
let desktopRelease = await fetch('https://api.github.com/repos/datahq/data-desktop/releases/latest')
if (desktopRelease.status === 200) {
const etag = desktopRelease.headers.get('ETag').slice(2)
// Now get URL for downloading dekstop app:
desktopRelease = await desktopRelease.json()
desktopAppUrl = desktopRelease.assets
.find(asset => path.parse(asset.name).ext === '.dmg')
.browser_download_url
// Update desktop release in the app.locals:
const newRelease = {
desktop: {
etag,
url: desktopAppUrl
}
}
req.app.locals.github.releases = Object.assign(
req.app.locals.github.releases,
newRelease
)
} else { // If github api is unavailable then just have a link to releases page
desktopAppUrl = 'https://github.com/datahq/data-desktop/releases'
}
}
if (binaryReleaseModified.status === 304) { // No new release
binReleaseMacos = req.app.locals.github.releases.binary.macos
binReleaseLinux = req.app.locals.github.releases.binary.linux
binReleaseWindows = req.app.locals.github.releases.binary.windows
msiX64 = req.app.locals.github.releases.binary.msiX64
msiX86 = req.app.locals.github.releases.binary.msiX86
} else { // Go and get new release
let binRelease = await fetch('https://api.github.com/repos/datahq/data-cli/releases/latest')
if (binRelease.status === 200) {
const etag = binRelease.headers.get('ETag').slice(2)
// Now get URLs for downloading binaries:
binRelease = await binRelease.json()
binReleaseMacos = binRelease.assets
.find(asset => asset.name.includes('macos.gz'))
.browser_download_url
binReleaseLinux = binRelease.assets
.find(asset => asset.name.includes('linux.gz'))
.browser_download_url
binReleaseWindows = binRelease.assets
.find(asset => asset.name.includes('win.exe.gz'))
.browser_download_url
msiX64 = binRelease.assets
.find(asset => asset.name.includes('data-x64'))
.browser_download_url
msiX86 = binRelease.assets
.find(asset => asset.name.includes('data-x86'))
.browser_download_url
// If msi isn't available yet, use previous version:
msiX64 = msiX64 || req.app.locals.github.releases.binary.msiX64
msiX86 = msiX86 || req.app.locals.github.releases.binary.msiX86
// Update binary release in the app.locals:
const newRelease = {
binary: {
etag,
macos: binReleaseMacos,
linux: binReleaseLinux,
windows: binReleaseWindows,
msiX64,
msiX86
}
}
req.app.locals.github.releases = Object.assign(
req.app.locals.github.releases,
newRelease
)
} else { // If github api is unavailable then just have a link to releases page
binReleaseMacos = 'https://github.com/datahq/data-cli/releases'
binReleaseLinux = 'https://github.com/datahq/data-cli/releases'
binReleaseWindows = 'https://github.com/datahq/data-cli/releases'
msiX64 = 'https://github.com/datahq/data-cli/releases'
msiX86 = 'https://github.com/datahq/data-cli/releases'
}
}
res.render('download.html', {
title: 'Download',
description: 'Command line tool for data wrangling. Download the tool for your OS (linux, mac or windows) and start wrangling, sharing and publishing your data online.',
desktopAppUrl,
binReleaseMacos,
binReleaseLinux,
binReleaseWindows,
msiX64,
msiX86
})
})
// Consulting page
router.get('/hire-us', async (req, res) => {
res.render('consulting.html', {
title: 'Hire Us ',
description: 'We are a team with excellence and beyond. Hire us to build and improve your data-driven project. We have decades of experience building data systems for clients large and small.'
})
})
// Premium data
router.get('/premium-data', async (req, res) => {
res.render('premium-data.html', {
title: "Premium data",
submitted: !!(req.query.done)
})
})
// Thank you page
router.get('/thanks', async (req, res) => {
const dest = req.query.next ? `/${req.query.next}` : '/'
req.flash('message', 'Thank you! We\'ve recieved your request and will get back to you soon!')
res.redirect(dest)
})
//Payments Page
router.get('/pay', (req, res) => {
let paymentSucceeded, amount
if (req.query.amount) {
amount = req.query.amount
} else if (req.query.success) {
paymentSucceeded = req.query.success
} else {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
res.render('pay.html', {
getPayment: true,
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
amount,
paymentSucceeded
})
})
//Payment Charging the amount
router.post('/pay/checkout',(req,res) => {
var token = req.body.stripeToken
var chargeAmount = req.body.chargeAmount
const charge = stripe.charges.create({
amount: chargeAmount,
currency: 'usd',
description: 'Data Requests',
source: token,
}, (err, charge) => {
if(err){
req.flash('message', err.message)
res.redirect('/pay?success=0')
} else {
res.redirect('/pay?success=1')
}
})
})
// MUST come last in order to catch all the publisher pages
router.get('/:owner', async (req, res) => {
// First check if user exists using resolver
const userProfile = await api.getProfile(req.params.owner)
if (!userProfile.found) {
res.status(404).render('404.html', {
message: 'Sorry, this page was not found'
})
return
}
const token = req.cookies.jwt
// Get the latest available 10 events:
const events = await api.getEvents(`owner="${req.params.owner}"&size=10`, token)
events.results = events.results.map(item => {
item.timeago = timeago().format(item.timestamp)
return item
})
// Fetch information about the publisher:
const joinDate = new Date(userProfile.profile.join_date)
const joinYear = joinDate.getUTCFullYear()
const joinMonth = joinDate.toLocaleString('en-us', { month: "long" })
// Pagination - show 20 items per page:
const from = req.query.from || 0
const size = req.query.size || 20
const query = req.query.q ? `&q="${req.query.q}"` : ''
const packages = await api.search(`datahub.ownerid="${userProfile.profile.id}"${query}&size=${size}&from=${from}`, token)
const total = packages.summary.total
const totalPages = Math.ceil(total/size)
const currentPage = parseInt(from, 10) / 20 + 1
const pages = utils.pagination(currentPage, totalPages)
let title, description = ''
if (req.params.owner === 'core') {
title = 'Core Datasets'
description = 'Core datasets maintained by the DataHub team. Important, commonly-used data as high quality, easy-to-use & open data packages. Download data tables in csv (excel) and json.'
} else if (req.params.owner === 'machine-learning') {
title = 'Machine Learning Datasets'
description = 'Machine Learning / Statistical Data. Examples of machine learning datasets. Machine learning data sets on the DataHub under the @machine-learning account.'
} else {
title = req.params.owner + ' datasets'
description = userProfile.profile.name
}
const avatar = userProfile.profile.avatar_url || `https://www.gravatar.com/avatar/${userProfile.profile.gravatar}?s=300&d=https%3A%2F%2Ftesting.datahub.io%2Fstatic%2Fimg%2Flogo-cube03.png`
res.render('owner.html', {
title,
description,
packages,
pages,
currentPage,
events: events.results,
avatar,
joinDate: joinMonth + ' ' + joinYear,
owner: req.params.owner,
name: userProfile.profile.name,
queryString: req.query.q || '',
query: req.query.q ? `&q=${req.query.q}` : ''
})
})
return router
}
| [old datahub][xs]: redirects for popular datasets from old datahub - refs https://github.com/datahq/pm/issues/214
| routes/index.js | [old datahub][xs]: redirects for popular datasets from old datahub - refs https://github.com/datahq/pm/issues/214 | <ide><path>outes/index.js
<ide>
<ide> // 'global-airport' => 'airport-codes'
<ide> router.get('/dataset/global-airports', redirectToDest('/core/airport-codes'))
<add>
<add> // 'dblp' => '/awesome/bibliographic-data'
<add> router.get('/dataset/dblp', redirectToDest('/awesome/bibliographic-data'))
<add>
<add> // 'yago' => `/awesome/yago`
<add> router.get('/dataset/yago', redirectToDest('/awesome/yago'))
<add>
<add> // 'opencorporates' => '/awesome/opencorporates'
<add> router.get('/dataset/opencorporates', redirectToDest('/awesome/opencorporates'))
<ide>
<ide> // Finally, redirections for login and dashboard pages
<ide> router.get('/user/login', redirectToDest('/login')) |
|
Java | apache-2.0 | a11ab1fbf0a9b8aebfed4404415725cb51327fa7 | 0 | mdogan/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,tombujok/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,dsukhoroslov/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,lmjacksoniii/hazelcast,tkountis/hazelcast,tombujok/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,lmjacksoniii/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl.operationservice.impl;
import com.hazelcast.cluster.ClusterState;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.instance.NodeState;
import com.hazelcast.internal.cluster.ClusterService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.ConnectionManager;
import com.hazelcast.partition.IPartition;
import com.hazelcast.partition.NoDataMemberInClusterException;
import com.hazelcast.spi.BlockingOperation;
import com.hazelcast.spi.ExceptionAction;
import com.hazelcast.spi.ExecutionService;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.OperationResponseHandler;
import com.hazelcast.spi.exception.ResponseAlreadySentException;
import com.hazelcast.spi.exception.RetryableException;
import com.hazelcast.spi.exception.RetryableIOException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.spi.exception.WrongTargetException;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationexecutor.OperationExecutor;
import com.hazelcast.spi.impl.operationservice.impl.responses.CallTimeoutResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.ErrorResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.NormalResponse;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;
import static com.hazelcast.cluster.memberselector.MemberSelectors.DATA_MEMBER_SELECTOR;
import static com.hazelcast.spi.ExecutionService.ASYNC_EXECUTOR;
import static com.hazelcast.spi.OperationAccessor.setCallTimeout;
import static com.hazelcast.spi.OperationAccessor.setCallerAddress;
import static com.hazelcast.spi.OperationAccessor.setInvocationTime;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.INTERRUPTED_RESPONSE;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.NULL_RESPONSE;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.WAIT_RESPONSE;
import static com.hazelcast.spi.impl.operationutil.Operations.isJoinOperation;
import static com.hazelcast.spi.impl.operationutil.Operations.isMigrationOperation;
import static com.hazelcast.spi.impl.operationutil.Operations.isWanReplicationOperation;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.WARNING;
/**
* The Invocation evaluates a Operation invocation.
* <p/>
* Using the InvocationFuture, one can wait for the completion of a Invocation.
*/
public abstract class Invocation implements OperationResponseHandler, Runnable {
private static final AtomicReferenceFieldUpdater<Invocation, Boolean> RESPONSE_RECEIVED =
AtomicReferenceFieldUpdater.newUpdater(Invocation.class, Boolean.class, "responseReceived");
private static final AtomicIntegerFieldUpdater<Invocation> BACKUPS_COMPLETED =
AtomicIntegerFieldUpdater.newUpdater(Invocation.class, "backupsCompleted");
private static final long MIN_TIMEOUT = 10000;
private static final int MAX_FAST_INVOCATION_COUNT = 5;
//some constants for logging purposes
private static final int LOG_MAX_INVOCATION_COUNT = 99;
private static final int LOG_INVOCATION_COUNT_MOD = 10;
@SuppressWarnings("checkstyle:visibilitymodifier")
public final Operation op;
// The time in millis when the response of the primary has been received.
volatile long pendingResponseReceivedMillis = -1;
// contains the pending response from the primary. It is pending because it could be that backups need to complete.
volatile Object pendingResponse;
// number of expected backups. Is set correctly as soon as the pending response is set. See {@link NormalResponse}
volatile int backupsExpected;
// number of backups that have completed. See {@link BackupResponse}.
volatile int backupsCompleted;
// A flag to prevent multiple responses to be send tot he Invocation. Only needed for local operations.
volatile Boolean responseReceived = FALSE;
final long callTimeout;
final NodeEngineImpl nodeEngine;
final String serviceName;
final int partitionId;
final int replicaIndex;
final int tryCount;
final long tryPauseMillis;
final ILogger logger;
final boolean resultDeserialized;
boolean remote;
Address invTarget;
MemberImpl targetMember;
final InvocationFuture invocationFuture;
final OperationServiceImpl operationService;
// writes to that are normally handled through the INVOKE_COUNT to ensure atomic increments / decrements
volatile int invokeCount;
Invocation(NodeEngineImpl nodeEngine, String serviceName, Operation op, int partitionId,
int replicaIndex, int tryCount, long tryPauseMillis, long callTimeout, ExecutionCallback callback,
boolean resultDeserialized) {
this.operationService = (OperationServiceImpl) nodeEngine.getOperationService();
this.logger = operationService.invocationLogger;
this.nodeEngine = nodeEngine;
this.serviceName = serviceName;
this.op = op;
this.partitionId = partitionId;
this.replicaIndex = replicaIndex;
this.tryCount = tryCount;
this.tryPauseMillis = tryPauseMillis;
this.callTimeout = getCallTimeout(callTimeout);
this.invocationFuture = new InvocationFuture(operationService, this, callback);
this.resultDeserialized = resultDeserialized;
}
abstract ExceptionAction onException(Throwable t);
protected abstract Address getTarget();
IPartition getPartition() {
return nodeEngine.getPartitionService().getPartition(partitionId);
}
private long getCallTimeout(long callTimeout) {
if (callTimeout > 0) {
return callTimeout;
}
long defaultCallTimeout = operationService.defaultCallTimeoutMillis;
if (!(op instanceof BlockingOperation)) {
return defaultCallTimeout;
}
long waitTimeoutMillis = op.getWaitTimeout();
if (waitTimeoutMillis > 0 && waitTimeoutMillis < Long.MAX_VALUE) {
/*
* final long minTimeout = Math.min(defaultCallTimeout, MIN_TIMEOUT);
* long callTimeout = Math.min(waitTimeoutMillis, defaultCallTimeout);
* callTimeout = Math.max(a, minTimeout);
* return callTimeout;
*
* Below two lines are shortened version of above*
* using min(max(x,y),z)=max(min(x,z),min(y,z))
*/
long max = Math.max(waitTimeoutMillis, MIN_TIMEOUT);
return Math.min(max, defaultCallTimeout);
}
return defaultCallTimeout;
}
public final InvocationFuture invoke() {
invokeInternal(false);
return invocationFuture;
}
public final void invokeAsync() {
invokeInternal(true);
}
private void invokeInternal(boolean isAsync) {
if (invokeCount > 0) {
// no need to be pessimistic.
throw new IllegalStateException("An invocation can not be invoked more than once!");
}
if (op.getCallId() != 0) {
throw new IllegalStateException("An operation[" + op + "] can not be used for multiple invocations!");
}
try {
setCallTimeout(op, callTimeout);
setCallerAddress(op, nodeEngine.getThisAddress());
op.setNodeEngine(nodeEngine)
.setServiceName(serviceName)
.setPartitionId(partitionId)
.setReplicaIndex(replicaIndex);
boolean isAllowed = operationService.operationExecutor.isInvocationAllowedFromCurrentThread(op, isAsync);
if (!isAllowed && !isMigrationOperation(op)) {
throw new IllegalThreadStateException(Thread.currentThread() + " cannot make remote call: " + op);
}
doInvoke(isAsync);
} catch (Exception e) {
handleInvocationException(e);
}
}
private void handleInvocationException(Exception e) {
if (e instanceof RetryableException) {
notifyError(e);
} else {
throw ExceptionUtil.rethrow(e);
}
}
@SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
private void doInvoke(boolean isAsync) {
if (!engineActive()) {
return;
}
invokeCount++;
// register method assumes this method has run before it is being called so that remote is set correctly.
if (!initInvocationTarget()) {
return;
}
setInvocationTime(op, nodeEngine.getClusterService().getClusterClock().getClusterTime());
operationService.invocationsRegistry.register(this);
if (remote) {
doInvokeRemote();
} else {
doInvokeLocal(isAsync);
}
}
private void doInvokeLocal(boolean isAsync) {
if (op.getCallerUuid() == null) {
op.setCallerUuid(nodeEngine.getLocalMember().getUuid());
}
responseReceived = FALSE;
op.setOperationResponseHandler(this);
OperationExecutor executor = operationService.operationExecutor;
if (isAsync) {
executor.execute(op);
} else {
executor.runOnCallingThreadIfPossible(op);
}
}
private void doInvokeRemote() {
boolean sent = operationService.send(op, invTarget);
if (!sent) {
operationService.invocationsRegistry.deregister(this);
notifyError(new RetryableIOException("Packet not send to -> " + invTarget));
}
}
@Override
public void run() {
doInvoke(false);
}
private boolean engineActive() {
if (nodeEngine.isRunning()) {
return true;
}
final NodeState state = nodeEngine.getNode().getState();
boolean allowed = state == NodeState.PASSIVE && (op instanceof AllowedDuringPassiveState);
if (!allowed) {
notifyError(new HazelcastInstanceNotActiveException("State: " + state + " Operation: " + op.getClass()));
remote = false;
}
return allowed;
}
/**
* Initializes the invocation target.
*
* @return true if the initialization was a success.
*/
boolean initInvocationTarget() {
Address thisAddress = nodeEngine.getThisAddress();
invTarget = getTarget();
final ClusterService clusterService = nodeEngine.getClusterService();
if (invTarget == null) {
remote = false;
notifyWithExceptionWhenTargetIsNull();
return false;
}
targetMember = clusterService.getMember(invTarget);
if (targetMember == null && !(isJoinOperation(op) || isWanReplicationOperation(op))) {
notifyError(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName));
return false;
}
if (op.getPartitionId() != partitionId) {
notifyError(new IllegalStateException("Partition id of operation: " + op.getPartitionId()
+ " is not equal to the partition id of invocation: " + partitionId));
return false;
}
if (op.getReplicaIndex() != replicaIndex) {
notifyError(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex()
+ " is not equal to the replica index of invocation: " + replicaIndex));
return false;
}
remote = !thisAddress.equals(invTarget);
return true;
}
private void notifyWithExceptionWhenTargetIsNull() {
Address thisAddress = nodeEngine.getThisAddress();
ClusterService clusterService = nodeEngine.getClusterService();
if (!nodeEngine.isRunning()) {
notifyError(new HazelcastInstanceNotActiveException());
return;
}
ClusterState clusterState = clusterService.getClusterState();
if (clusterState == ClusterState.FROZEN || clusterState == ClusterState.PASSIVE) {
notifyError(new IllegalStateException("Partitions can't be assigned since cluster-state: "
+ clusterState));
return;
}
if (clusterService.getSize(DATA_MEMBER_SELECTOR) == 0) {
notifyError(new NoDataMemberInClusterException(
"Partitions can't be assigned since all nodes in the cluster are lite members"));
return;
}
notifyError(new WrongTargetException(thisAddress, null, partitionId,
replicaIndex, op.getClass().getName(), serviceName));
}
@Override
public void sendResponse(Operation op, Object response) {
if (!RESPONSE_RECEIVED.compareAndSet(this, FALSE, TRUE)) {
throw new ResponseAlreadySentException("NormalResponse already responseReceived for callback: " + this
+ ", current-response: : " + response);
}
if (response == null) {
response = NULL_RESPONSE;
}
if (response instanceof CallTimeoutResponse) {
notifyCallTimeout();
return;
}
if (response instanceof ErrorResponse || response instanceof Throwable) {
notifyError(response);
return;
}
if (response instanceof NormalResponse) {
NormalResponse normalResponse = (NormalResponse) response;
notifyNormalResponse(normalResponse.getValue(), normalResponse.getBackupCount());
return;
}
// there are no backups or the number of expected backups has returned; so signal the future that the result is ready.
invocationFuture.set(response);
}
@Override
public boolean isLocal() {
return true;
}
void notifyError(Object error) {
assert error != null;
Throwable cause;
if (error instanceof Throwable) {
cause = (Throwable) error;
} else {
cause = ((ErrorResponse) error).getCause();
}
switch (onException(cause)) {
case CONTINUE_WAIT:
handleContinueWait();
break;
case THROW_EXCEPTION:
notifyNormalResponse(cause, 0);
break;
case RETRY_INVOCATION:
if (invokeCount < tryCount) {
// we are below the tryCount, so lets retry
handleRetry(cause);
} else {
// we can't retry anymore, so lets send the cause to the future.
notifyNormalResponse(cause, 0);
}
break;
default:
throw new IllegalStateException("Unhandled ExceptionAction");
}
}
void notifyNormalResponse(Object value, int expectedBackups) {
if (value == null) {
value = NULL_RESPONSE;
}
//if a regular response came and there are backups, we need to wait for the backs.
//when the backups complete, the response will be send by the last backup or backup-timeout-handle mechanism kicks on
if (expectedBackups > backupsCompleted) {
// So the invocation has backups and since not all backups have completed, we need to wait.
// It could be that backups arrive earlier than the response.
this.pendingResponseReceivedMillis = Clock.currentTimeMillis();
this.backupsExpected = expectedBackups;
// It is very important that the response is set after the backupsExpected is set. Else the system
// can assume the invocation is complete because there is a response and no backups need to respond.
this.pendingResponse = value;
if (backupsCompleted != expectedBackups) {
// We are done since not all backups have completed. Therefor we should not notify the future.
return;
}
}
// We are going to notify the future that a response is available. This can happen when:
// - we had a regular operation (so no backups we need to wait for) that completed.
// - we had a backup-aware operation that has completed, but also all its backups have completed.
invocationFuture.set(value);
}
@SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
void notifyCallTimeout() {
operationService.callTimeoutCount.inc();
if (logger.isFinestEnabled()) {
logger.finest("Call timed-out either in operation queue or during wait-notify phase, retrying call: "
+ toString());
}
if (op instanceof BlockingOperation) {
// decrement wait-timeout by call-timeout
long waitTimeout = op.getWaitTimeout();
waitTimeout -= callTimeout;
op.setWaitTimeout(waitTimeout);
}
invokeCount--;
handleRetry("invocation timeout");
}
void notifySingleBackupComplete() {
int newBackupsCompleted = BACKUPS_COMPLETED.incrementAndGet(this);
Object pendingResponse = this.pendingResponse;
if (pendingResponse == null) {
// No pendingResponse has been set, so we are done since the invocation on the primary needs to complete first.
return;
}
// If a pendingResponse is set, then the backupsExpected has been set. So we can now safely read backupsExpected.
int backupsExpected = this.backupsExpected;
if (backupsExpected < newBackupsCompleted) {
// the backups have not yet completed. So we are done.
return;
}
if (backupsExpected != newBackupsCompleted) {
// We managed to complete one backup, but we were not the one completing the last backup. So we are done.
return;
}
// We are the lucky ones since we just managed to complete the last backup for this invocation and since the
// pendingResponse is set, we can set it on the future.
invocationFuture.set(pendingResponse);
}
boolean checkInvocationTimeout() {
long maxCallTimeout = invocationFuture.getMaxCallTimeout();
long expirationTime = op.getInvocationTime() + maxCallTimeout;
boolean done = invocationFuture.isDone();
boolean hasResponse = pendingResponse != null;
boolean hasWaitingThreads = invocationFuture.getWaitingThreadsCount() > 0;
boolean notExpired = maxCallTimeout == Long.MAX_VALUE
|| expirationTime < 0
|| expirationTime >= Clock.currentTimeMillis();
if (hasResponse || hasWaitingThreads || notExpired || done) {
return false;
}
operationService.getIsStillRunningService().timeoutInvocationIfNotExecuting(this);
return true;
}
Object newOperationTimeoutException(long totalTimeoutMs) {
operationService.operationTimeoutCount.inc();
boolean hasResponse = this.pendingResponse != null;
int backupsExpected = this.backupsExpected;
int backupsCompleted = this.backupsCompleted;
if (hasResponse) {
return new OperationTimeoutException("No response for " + totalTimeoutMs + " ms."
+ " Aborting invocation! " + toString()
+ " Not all backups have completed! "
+ " backups-expected:" + backupsExpected
+ " backups-completed: " + backupsCompleted);
} else {
return new OperationTimeoutException("No response for " + totalTimeoutMs + " ms."
+ " Aborting invocation! " + toString()
+ " No response has been received! "
+ " backups-expected:" + backupsExpected
+ " backups-completed: " + backupsCompleted);
}
}
private void handleContinueWait() {
invocationFuture.set(WAIT_RESPONSE);
}
private void handleRetry(Object cause) {
operationService.retryCount.inc();
if (invokeCount % LOG_INVOCATION_COUNT_MOD == 0) {
Level level = invokeCount > LOG_MAX_INVOCATION_COUNT ? WARNING : FINEST;
if (logger.isLoggable(level)) {
logger.log(level, "Retrying invocation: " + toString() + ", Reason: " + cause);
}
}
operationService.invocationsRegistry.deregister(this);
if (invocationFuture.interrupted) {
invocationFuture.set(INTERRUPTED_RESPONSE);
return;
}
if (!invocationFuture.set(WAIT_RESPONSE)) {
logger.finest("Cannot retry " + toString() + ", because a different response is already set: "
+ invocationFuture.response);
return;
}
ExecutionService ex = nodeEngine.getExecutionService();
// fast retry for the first few invocations
if (invokeCount < MAX_FAST_INVOCATION_COUNT) {
operationService.asyncExecutor.execute(this);
} else {
ex.schedule(ASYNC_EXECUTOR, this, tryPauseMillis, TimeUnit.MILLISECONDS);
}
}
boolean checkBackupTimeout(long timeoutMillis) {
// If the backups have completed, we are done.
// This check also filters out all non backup-aware operations since they backupsExpected will always be equal to the
// backupsCompleted.
boolean allBackupsComplete = backupsExpected == backupsCompleted;
long responseReceivedMillis = pendingResponseReceivedMillis;
// If this has not yet expired (so has not been in the system for a too long period) we ignore it.
long expirationTime = responseReceivedMillis + timeoutMillis;
boolean timeout = expirationTime > 0 && expirationTime < Clock.currentTimeMillis();
// If no response has yet been received, we we are done. We are only going to re-invoke an operation
// if the response of the primary has been received, but the backups have not replied.
boolean responseReceived = pendingResponse != null;
if (allBackupsComplete || !responseReceived || !timeout) {
return false;
}
boolean targetDead = nodeEngine.getClusterService().getMember(invTarget) == null;
if (targetDead) {
// The target doesn't exist, we are going to re-invoke this invocation. The reason why this operation is being invoked
// is that otherwise it would be possible to loose data. In this particular case it could have happened that e.g.
// a map.put was done, the primary has returned the response but has not yet completed the backups and then the
// primary fails. The consequence is that the backups never will be made and the effects of the map.put, even though
// it returned a value, will never be visible. So if we would complete the future, a response is send even though
// its changes never made it into the system.
resetAndReInvoke();
return false;
}
// The backups have not yet completed, but we are going to release the future anyway if a pendingResponse has been set.
invocationFuture.set(pendingResponse);
return true;
}
private void resetAndReInvoke() {
operationService.invocationsRegistry.deregister(this);
invokeCount = 0;
pendingResponse = null;
pendingResponseReceivedMillis = -1;
backupsExpected = 0;
backupsCompleted = 0;
doInvoke(false);
}
@Override
public String toString() {
String connectionStr = null;
Address invTarget = this.invTarget;
if (invTarget != null) {
ConnectionManager connectionManager = operationService.nodeEngine.getNode().getConnectionManager();
Connection connection = connectionManager.getConnection(invTarget);
connectionStr = connection == null ? null : connection.toString();
}
return "Invocation{"
+ "serviceName='" + serviceName + '\''
+ ", op=" + op
+ ", partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex
+ ", tryCount=" + tryCount
+ ", tryPauseMillis=" + tryPauseMillis
+ ", invokeCount=" + invokeCount
+ ", callTimeout=" + callTimeout
+ ", target=" + invTarget
+ ", backupsExpected=" + backupsExpected
+ ", backupsCompleted=" + backupsCompleted
+ ", connection=" + connectionStr
+ '}';
}
}
| hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/Invocation.java | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl.operationservice.impl;
import com.hazelcast.cluster.ClusterState;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.instance.NodeState;
import com.hazelcast.internal.cluster.ClusterService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.ConnectionManager;
import com.hazelcast.partition.IPartition;
import com.hazelcast.partition.NoDataMemberInClusterException;
import com.hazelcast.spi.BlockingOperation;
import com.hazelcast.spi.ExceptionAction;
import com.hazelcast.spi.ExecutionService;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.OperationResponseHandler;
import com.hazelcast.spi.exception.ResponseAlreadySentException;
import com.hazelcast.spi.exception.RetryableException;
import com.hazelcast.spi.exception.RetryableIOException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.spi.exception.WrongTargetException;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationexecutor.OperationExecutor;
import com.hazelcast.spi.impl.operationservice.impl.responses.CallTimeoutResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.ErrorResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.NormalResponse;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;
import static com.hazelcast.cluster.memberselector.MemberSelectors.DATA_MEMBER_SELECTOR;
import static com.hazelcast.spi.ExecutionService.ASYNC_EXECUTOR;
import static com.hazelcast.spi.OperationAccessor.setCallTimeout;
import static com.hazelcast.spi.OperationAccessor.setCallerAddress;
import static com.hazelcast.spi.OperationAccessor.setInvocationTime;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.INTERRUPTED_RESPONSE;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.NULL_RESPONSE;
import static com.hazelcast.spi.impl.operationservice.impl.InternalResponse.WAIT_RESPONSE;
import static com.hazelcast.spi.impl.operationutil.Operations.isJoinOperation;
import static com.hazelcast.spi.impl.operationutil.Operations.isMigrationOperation;
import static com.hazelcast.spi.impl.operationutil.Operations.isWanReplicationOperation;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.WARNING;
/**
* The Invocation evaluates a Operation invocation.
* <p/>
* Using the InvocationFuture, one can wait for the completion of a Invocation.
*/
public abstract class Invocation implements OperationResponseHandler, Runnable {
private static final AtomicReferenceFieldUpdater<Invocation, Boolean> RESPONSE_RECEIVED =
AtomicReferenceFieldUpdater.newUpdater(Invocation.class, Boolean.class, "responseReceived");
private static final AtomicIntegerFieldUpdater<Invocation> BACKUPS_COMPLETED =
AtomicIntegerFieldUpdater.newUpdater(Invocation.class, "backupsCompleted");
private static final long MIN_TIMEOUT = 10000;
private static final int MAX_FAST_INVOCATION_COUNT = 5;
//some constants for logging purposes
private static final int LOG_MAX_INVOCATION_COUNT = 99;
private static final int LOG_INVOCATION_COUNT_MOD = 10;
@SuppressWarnings("checkstyle:visibilitymodifier")
public final Operation op;
// The time in millis when the response of the primary has been received.
volatile long pendingResponseReceivedMillis = -1;
// contains the pending response from the primary. It is pending because it could be that backups need to complete.
volatile Object pendingResponse;
// number of expected backups. Is set correctly as soon as the pending response is set. See {@link NormalResponse}
volatile int backupsExpected;
// number of backups that have completed. See {@link BackupResponse}.
volatile int backupsCompleted;
// A flag to prevent multiple responses to be send tot he Invocation. Only needed for local operations.
volatile Boolean responseReceived = FALSE;
final long callTimeout;
final NodeEngineImpl nodeEngine;
final String serviceName;
final int partitionId;
final int replicaIndex;
final int tryCount;
final long tryPauseMillis;
final ILogger logger;
final boolean resultDeserialized;
boolean remote;
Address invTarget;
MemberImpl targetMember;
final InvocationFuture invocationFuture;
final OperationServiceImpl operationService;
// writes to that are normally handled through the INVOKE_COUNT to ensure atomic increments / decrements
volatile int invokeCount;
Invocation(NodeEngineImpl nodeEngine, String serviceName, Operation op, int partitionId,
int replicaIndex, int tryCount, long tryPauseMillis, long callTimeout, ExecutionCallback callback,
boolean resultDeserialized) {
this.operationService = (OperationServiceImpl) nodeEngine.getOperationService();
this.logger = operationService.invocationLogger;
this.nodeEngine = nodeEngine;
this.serviceName = serviceName;
this.op = op;
this.partitionId = partitionId;
this.replicaIndex = replicaIndex;
this.tryCount = tryCount;
this.tryPauseMillis = tryPauseMillis;
this.callTimeout = getCallTimeout(callTimeout);
this.invocationFuture = new InvocationFuture(operationService, this, callback);
this.resultDeserialized = resultDeserialized;
}
abstract ExceptionAction onException(Throwable t);
protected abstract Address getTarget();
IPartition getPartition() {
return nodeEngine.getPartitionService().getPartition(partitionId);
}
@Override
public boolean isLocal() {
return true;
}
private long getCallTimeout(long callTimeout) {
if (callTimeout > 0) {
return callTimeout;
}
long defaultCallTimeout = operationService.defaultCallTimeoutMillis;
if (!(op instanceof BlockingOperation)) {
return defaultCallTimeout;
}
long waitTimeoutMillis = op.getWaitTimeout();
if (waitTimeoutMillis > 0 && waitTimeoutMillis < Long.MAX_VALUE) {
/*
* final long minTimeout = Math.min(defaultCallTimeout, MIN_TIMEOUT);
* long callTimeout = Math.min(waitTimeoutMillis, defaultCallTimeout);
* callTimeout = Math.max(a, minTimeout);
* return callTimeout;
*
* Below two lines are shortened version of above*
* using min(max(x,y),z)=max(min(x,z),min(y,z))
*/
long max = Math.max(waitTimeoutMillis, MIN_TIMEOUT);
return Math.min(max, defaultCallTimeout);
}
return defaultCallTimeout;
}
public final InvocationFuture invoke() {
invokeInternal(false);
return invocationFuture;
}
public final void invokeAsync() {
invokeInternal(true);
}
private void invokeInternal(boolean isAsync) {
if (invokeCount > 0) {
// no need to be pessimistic.
throw new IllegalStateException("An invocation can not be invoked more than once!");
}
if (op.getCallId() != 0) {
throw new IllegalStateException("An operation[" + op + "] can not be used for multiple invocations!");
}
try {
setCallTimeout(op, callTimeout);
setCallerAddress(op, nodeEngine.getThisAddress());
op.setNodeEngine(nodeEngine)
.setServiceName(serviceName)
.setPartitionId(partitionId)
.setReplicaIndex(replicaIndex);
boolean isAllowed = operationService.operationExecutor.isInvocationAllowedFromCurrentThread(op, isAsync);
if (!isAllowed && !isMigrationOperation(op)) {
throw new IllegalThreadStateException(Thread.currentThread() + " cannot make remote call: " + op);
}
doInvoke(isAsync);
} catch (Exception e) {
handleInvocationException(e);
}
}
private void handleInvocationException(Exception e) {
if (e instanceof RetryableException) {
notifyError(e);
} else {
throw ExceptionUtil.rethrow(e);
}
}
@SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
private void doInvoke(boolean isAsync) {
if (!engineActive()) {
return;
}
invokeCount++;
// register method assumes this method has run before it is being called so that remote is set correctly.
if (!initInvocationTarget()) {
return;
}
setInvocationTime(op, nodeEngine.getClusterService().getClusterClock().getClusterTime());
operationService.invocationsRegistry.register(this);
if (remote) {
doInvokeRemote();
} else {
doInvokeLocal(isAsync);
}
}
private void doInvokeLocal(boolean isAsync) {
if (op.getCallerUuid() == null) {
op.setCallerUuid(nodeEngine.getLocalMember().getUuid());
}
responseReceived = FALSE;
op.setOperationResponseHandler(this);
OperationExecutor executor = operationService.operationExecutor;
if (isAsync) {
executor.execute(op);
} else {
executor.runOnCallingThreadIfPossible(op);
}
}
private void doInvokeRemote() {
boolean sent = operationService.send(op, invTarget);
if (!sent) {
operationService.invocationsRegistry.deregister(this);
notifyError(new RetryableIOException("Packet not send to -> " + invTarget));
}
}
@Override
public void run() {
doInvoke(false);
}
private boolean engineActive() {
if (nodeEngine.isRunning()) {
return true;
}
final NodeState state = nodeEngine.getNode().getState();
boolean allowed = state == NodeState.PASSIVE && (op instanceof AllowedDuringPassiveState);
if (!allowed) {
notifyError(new HazelcastInstanceNotActiveException("State: " + state + " Operation: " + op.getClass()));
remote = false;
}
return allowed;
}
/**
* Initializes the invocation target.
*
* @return true if the initialization was a success.
*/
boolean initInvocationTarget() {
Address thisAddress = nodeEngine.getThisAddress();
invTarget = getTarget();
final ClusterService clusterService = nodeEngine.getClusterService();
if (invTarget == null) {
remote = false;
notifyWithExceptionWhenTargetIsNull();
return false;
}
targetMember = clusterService.getMember(invTarget);
if (targetMember == null && !(isJoinOperation(op) || isWanReplicationOperation(op))) {
notifyError(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName));
return false;
}
if (op.getPartitionId() != partitionId) {
notifyError(new IllegalStateException("Partition id of operation: " + op.getPartitionId()
+ " is not equal to the partition id of invocation: " + partitionId));
return false;
}
if (op.getReplicaIndex() != replicaIndex) {
notifyError(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex()
+ " is not equal to the replica index of invocation: " + replicaIndex));
return false;
}
remote = !thisAddress.equals(invTarget);
return true;
}
private void notifyWithExceptionWhenTargetIsNull() {
Address thisAddress = nodeEngine.getThisAddress();
ClusterService clusterService = nodeEngine.getClusterService();
if (!nodeEngine.isRunning()) {
notifyError(new HazelcastInstanceNotActiveException());
return;
}
ClusterState clusterState = clusterService.getClusterState();
if (clusterState == ClusterState.FROZEN || clusterState == ClusterState.PASSIVE) {
notifyError(new IllegalStateException("Partitions can't be assigned since cluster-state: "
+ clusterState));
return;
}
if (clusterService.getSize(DATA_MEMBER_SELECTOR) == 0) {
notifyError(new NoDataMemberInClusterException(
"Partitions can't be assigned since all nodes in the cluster are lite members"));
return;
}
notifyError(new WrongTargetException(thisAddress, null, partitionId,
replicaIndex, op.getClass().getName(), serviceName));
}
@Override
public void sendResponse(Operation op, Object response) {
if (!RESPONSE_RECEIVED.compareAndSet(this, FALSE, TRUE)) {
throw new ResponseAlreadySentException("NormalResponse already responseReceived for callback: " + this
+ ", current-response: : " + response);
}
if (response == null) {
response = NULL_RESPONSE;
}
if (response instanceof CallTimeoutResponse) {
notifyCallTimeout();
return;
}
if (response instanceof ErrorResponse || response instanceof Throwable) {
notifyError(response);
return;
}
if (response instanceof NormalResponse) {
NormalResponse normalResponse = (NormalResponse) response;
notifyNormalResponse(normalResponse.getValue(), normalResponse.getBackupCount());
return;
}
// there are no backups or the number of expected backups has returned; so signal the future that the result is ready.
invocationFuture.set(response);
}
void notifyError(Object error) {
assert error != null;
Throwable cause;
if (error instanceof Throwable) {
cause = (Throwable) error;
} else {
cause = ((ErrorResponse) error).getCause();
}
switch (onException(cause)) {
case CONTINUE_WAIT:
handleContinueWait();
break;
case THROW_EXCEPTION:
notifyNormalResponse(cause, 0);
break;
case RETRY_INVOCATION:
if (invokeCount < tryCount) {
// we are below the tryCount, so lets retry
handleRetry(cause);
} else {
// we can't retry anymore, so lets send the cause to the future.
notifyNormalResponse(cause, 0);
}
break;
default:
throw new IllegalStateException("Unhandled ExceptionAction");
}
}
void notifyNormalResponse(Object value, int expectedBackups) {
if (value == null) {
value = NULL_RESPONSE;
}
//if a regular response came and there are backups, we need to wait for the backs.
//when the backups complete, the response will be send by the last backup or backup-timeout-handle mechanism kicks on
if (expectedBackups > backupsCompleted) {
// So the invocation has backups and since not all backups have completed, we need to wait.
// It could be that backups arrive earlier than the response.
this.pendingResponseReceivedMillis = Clock.currentTimeMillis();
this.backupsExpected = expectedBackups;
// It is very important that the response is set after the backupsExpected is set. Else the system
// can assume the invocation is complete because there is a response and no backups need to respond.
this.pendingResponse = value;
if (backupsCompleted != expectedBackups) {
// We are done since not all backups have completed. Therefor we should not notify the future.
return;
}
}
// We are going to notify the future that a response is available. This can happen when:
// - we had a regular operation (so no backups we need to wait for) that completed.
// - we had a backup-aware operation that has completed, but also all its backups have completed.
invocationFuture.set(value);
}
@SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
void notifyCallTimeout() {
operationService.callTimeoutCount.inc();
if (logger.isFinestEnabled()) {
logger.finest("Call timed-out either in operation queue or during wait-notify phase, retrying call: "
+ toString());
}
if (op instanceof BlockingOperation) {
// decrement wait-timeout by call-timeout
long waitTimeout = op.getWaitTimeout();
waitTimeout -= callTimeout;
op.setWaitTimeout(waitTimeout);
}
invokeCount--;
handleRetry("invocation timeout");
}
void notifySingleBackupComplete() {
int newBackupsCompleted = BACKUPS_COMPLETED.incrementAndGet(this);
Object pendingResponse = this.pendingResponse;
if (pendingResponse == null) {
// No pendingResponse has been set, so we are done since the invocation on the primary needs to complete first.
return;
}
// If a pendingResponse is set, then the backupsExpected has been set. So we can now safely read backupsExpected.
int backupsExpected = this.backupsExpected;
if (backupsExpected < newBackupsCompleted) {
// the backups have not yet completed. So we are done.
return;
}
if (backupsExpected != newBackupsCompleted) {
// We managed to complete one backup, but we were not the one completing the last backup. So we are done.
return;
}
// We are the lucky ones since we just managed to complete the last backup for this invocation and since the
// pendingResponse is set, we can set it on the future.
invocationFuture.set(pendingResponse);
}
boolean checkInvocationTimeout() {
long maxCallTimeout = invocationFuture.getMaxCallTimeout();
long expirationTime = op.getInvocationTime() + maxCallTimeout;
boolean done = invocationFuture.isDone();
boolean hasResponse = pendingResponse != null;
boolean hasWaitingThreads = invocationFuture.getWaitingThreadsCount() > 0;
boolean notExpired = maxCallTimeout == Long.MAX_VALUE
|| expirationTime < 0
|| expirationTime >= Clock.currentTimeMillis();
if (hasResponse || hasWaitingThreads || notExpired || done) {
return false;
}
operationService.getIsStillRunningService().timeoutInvocationIfNotExecuting(this);
return true;
}
Object newOperationTimeoutException(long totalTimeoutMs) {
operationService.operationTimeoutCount.inc();
boolean hasResponse = this.pendingResponse != null;
int backupsExpected = this.backupsExpected;
int backupsCompleted = this.backupsCompleted;
if (hasResponse) {
return new OperationTimeoutException("No response for " + totalTimeoutMs + " ms."
+ " Aborting invocation! " + toString()
+ " Not all backups have completed! "
+ " backups-expected:" + backupsExpected
+ " backups-completed: " + backupsCompleted);
} else {
return new OperationTimeoutException("No response for " + totalTimeoutMs + " ms."
+ " Aborting invocation! " + toString()
+ " No response has been received! "
+ " backups-expected:" + backupsExpected
+ " backups-completed: " + backupsCompleted);
}
}
private void handleContinueWait() {
invocationFuture.set(WAIT_RESPONSE);
}
private void handleRetry(Object cause) {
operationService.retryCount.inc();
if (invokeCount % LOG_INVOCATION_COUNT_MOD == 0) {
Level level = invokeCount > LOG_MAX_INVOCATION_COUNT ? WARNING : FINEST;
if (logger.isLoggable(level)) {
logger.log(level, "Retrying invocation: " + toString() + ", Reason: " + cause);
}
}
operationService.invocationsRegistry.deregister(this);
if (invocationFuture.interrupted) {
invocationFuture.set(INTERRUPTED_RESPONSE);
return;
}
if (!invocationFuture.set(WAIT_RESPONSE)) {
logger.finest("Cannot retry " + toString() + ", because a different response is already set: "
+ invocationFuture.response);
return;
}
ExecutionService ex = nodeEngine.getExecutionService();
// fast retry for the first few invocations
if (invokeCount < MAX_FAST_INVOCATION_COUNT) {
operationService.asyncExecutor.execute(this);
} else {
ex.schedule(ASYNC_EXECUTOR, this, tryPauseMillis, TimeUnit.MILLISECONDS);
}
}
boolean checkBackupTimeout(long timeoutMillis) {
// If the backups have completed, we are done.
// This check also filters out all non backup-aware operations since they backupsExpected will always be equal to the
// backupsCompleted.
boolean allBackupsComplete = backupsExpected == backupsCompleted;
long responseReceivedMillis = pendingResponseReceivedMillis;
// If this has not yet expired (so has not been in the system for a too long period) we ignore it.
long expirationTime = responseReceivedMillis + timeoutMillis;
boolean timeout = expirationTime > 0 && expirationTime < Clock.currentTimeMillis();
// If no response has yet been received, we we are done. We are only going to re-invoke an operation
// if the response of the primary has been received, but the backups have not replied.
boolean responseReceived = pendingResponse != null;
if (allBackupsComplete || !responseReceived || !timeout) {
return false;
}
boolean targetDead = nodeEngine.getClusterService().getMember(invTarget) == null;
if (targetDead) {
// The target doesn't exist, we are going to re-invoke this invocation. The reason why this operation is being invoked
// is that otherwise it would be possible to loose data. In this particular case it could have happened that e.g.
// a map.put was done, the primary has returned the response but has not yet completed the backups and then the
// primary fails. The consequence is that the backups never will be made and the effects of the map.put, even though
// it returned a value, will never be visible. So if we would complete the future, a response is send even though
// its changes never made it into the system.
resetAndReInvoke();
return false;
}
// The backups have not yet completed, but we are going to release the future anyway if a pendingResponse has been set.
invocationFuture.set(pendingResponse);
return true;
}
private void resetAndReInvoke() {
operationService.invocationsRegistry.deregister(this);
invokeCount = 0;
pendingResponse = null;
pendingResponseReceivedMillis = -1;
backupsExpected = 0;
backupsCompleted = 0;
doInvoke(false);
}
@Override
public String toString() {
String connectionStr = null;
Address invTarget = this.invTarget;
if (invTarget != null) {
ConnectionManager connectionManager = operationService.nodeEngine.getNode().getConnectionManager();
Connection connection = connectionManager.getConnection(invTarget);
connectionStr = connection == null ? null : connection.toString();
}
return "Invocation{"
+ "serviceName='" + serviceName + '\''
+ ", op=" + op
+ ", partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex
+ ", tryCount=" + tryCount
+ ", tryPauseMillis=" + tryPauseMillis
+ ", invokeCount=" + invokeCount
+ ", callTimeout=" + callTimeout
+ ", target=" + invTarget
+ ", backupsExpected=" + backupsExpected
+ ", backupsCompleted=" + backupsCompleted
+ ", connection=" + connectionStr
+ '}';
}
}
| Moved Invocation.isLocal method underneath sendResponse since they are part of the same implementing interface
| hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/Invocation.java | Moved Invocation.isLocal method underneath sendResponse since they are part of the same implementing interface | <ide><path>azelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/Invocation.java
<ide> return nodeEngine.getPartitionService().getPartition(partitionId);
<ide> }
<ide>
<del> @Override
<del> public boolean isLocal() {
<del> return true;
<del> }
<del>
<ide> private long getCallTimeout(long callTimeout) {
<ide> if (callTimeout > 0) {
<ide> return callTimeout;
<ide>
<ide> // there are no backups or the number of expected backups has returned; so signal the future that the result is ready.
<ide> invocationFuture.set(response);
<add> }
<add>
<add> @Override
<add> public boolean isLocal() {
<add> return true;
<ide> }
<ide>
<ide> void notifyError(Object error) { |
|
JavaScript | apache-2.0 | 27f261a50ade673e5dc8d2c9476883d37b323441 | 0 | ManageIQ/manageiq-ui-service,AllenBW/manageiq-ui-service,ManageIQ/manageiq-ui-service,ManageIQ/manageiq-ui-self_service,ManageIQ/manageiq-ui-self_service,AllenBW/manageiq-ui-service,ManageIQ/manageiq-ui-self_service,AllenBW/manageiq-ui-service,ManageIQ/manageiq-ui-service,AllenBW/manageiq-ui-service | /* eslint-disable angular/window-service */
// The webpack entrypoint
function requireAll(context) {
context.keys().forEach(context);
}
// Globals that are expected in application code and some libraries
window.$ = window.jQuery = require('jquery');
window._ = require('lodash');
window.moment = require('moment');
window.sprintf = require('sprintf-js').sprintf;
// Vendor libraries, order matters
require('jquery-ui-bundle');
require('moment-timezone');
require('es6-shim');
require('angular');
require('angular-animate');
require('angular-cookies');
require('angular-resource');
require('angular-messages');
require('angular-sanitize');
require('angular-base64');
require('angular-bootstrap-switch');
require('angular-ui-bootstrap');
require('angular-ui-sortable');
require('angular-gettext');
require('bootstrap');
require('angular-dragdrop');
require('bootstrap-combobox');
require('bootstrap-datepicker');
require('bootstrap-select');
require('bootstrap-switch');
require('bootstrap-touchspin');
require('angular-svg-base-fix');
require('angular-ui-router');
require('patternfly/dist/js/patternfly.js');
require('manageiq-ui-components/dist/js/ui-components.js');
require('ngprogress/build/ngprogress.min.js');
require('ngstorage');
// Needs imports loader because it expects `this` to be `window`
require('imports-loader?this=>window!actioncable');
// Must be required last because of its dependencies
require('angular-patternfly/dist/angular-patternfly');
// Application scripts, order matters
require('./app/app.module.js');
// Vendor styles, order matters
require('patternfly/dist/css/patternfly-additions.css');
require('angular-patternfly/dist/styles/angular-patternfly.css');
require('manageiq-ui-components/dist/css/ui-components.css');
require('ngprogress/ngProgress.css');
// Application styles
require('./assets/sass/styles.sass');
// Angular templates
requireAll(require.context('./app', true, /\.html$/));
// Skin overrides, require all js and css files within `client/skin`
requireAll(require.context('./', true, /skin\/.*\.(js|css)$/));
| client/app.js | /* eslint-disable angular/window-service */
// The webpack entrypoint
function requireAll(context) {
context.keys().forEach(context);
}
// Globals that are expected in application code and some libraries
window.$ = window.jQuery = require('jquery');
window._ = require('lodash');
window.moment = require('moment');
window.sprintf = require('sprintf-js').sprintf;
// Vendor libraries, order matters
require('jquery-ui-bundle');
require('moment-timezone');
require('es6-shim');
require('angular');
require('angular-animate');
require('angular-cookies');
require('angular-resource');
require('angular-messages');
require('angular-sanitize');
require('angular-base64');
require('angular-bootstrap-switch');
require('angular-ui-bootstrap');
require('angular-ui-sortable');
require('angular-gettext');
require('bootstrap');
require('angular-dragdrop');
require('bootstrap-combobox');
require('bootstrap-datepicker');
require('bootstrap-select');
require('bootstrap-switch');
require('bootstrap-touchspin');
require('angular-svg-base-fix');
require('angular-ui-router');
require('patternfly/dist/js/patternfly.js');
require('manageiq-ui-components/dist/js/ui-components.js');
require('ngprogress/build/ngprogress.min.js');
require('ngstorage');
// Needs imports loader because it expects `this` to be `window`
require('imports-loader?this=>window!actioncable');
// Must be required last because of its dependencies
require('angular-patternfly/dist/angular-patternfly');
// Application scripts, order matters
require('./app/app.module.js');
// Vendor styles, order matters
require('patternfly/dist/css/patternfly-additions.css');
// require('angular-patternfly/dist/styles/angular-patternfly.css');
require('manageiq-ui-components/dist/css/ui-components.css');
require('ngprogress/ngProgress.css');
// Application styles
require('./assets/sass/styles.sass');
// Angular templates
requireAll(require.context('./app', true, /\.html$/));
// Skin overrides, require all js and css files within `client/skin`
requireAll(require.context('./', true, /skin\/.*\.(js|css)$/));
| Added
| client/app.js | Added | <ide><path>lient/app.js
<ide>
<ide> // Vendor styles, order matters
<ide> require('patternfly/dist/css/patternfly-additions.css');
<del>// require('angular-patternfly/dist/styles/angular-patternfly.css');
<add>require('angular-patternfly/dist/styles/angular-patternfly.css');
<ide> require('manageiq-ui-components/dist/css/ui-components.css');
<ide> require('ngprogress/ngProgress.css');
<ide> |
|
Java | agpl-3.0 | a838000bb77fdd90b32149d104bd77fd04d39829 | 0 | opencadc/vos,opencadc/vos,opencadc/vos | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2009. (c) 2009.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.vos.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import org.apache.log4j.Logger;
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.auth.SSOCookieCredential;
import ca.nrc.cadc.auth.X509CertificateChain;
import ca.nrc.cadc.net.HttpDelete;
import ca.nrc.cadc.net.HttpDownload;
import ca.nrc.cadc.net.HttpPost;
import ca.nrc.cadc.net.HttpUpload;
import ca.nrc.cadc.net.NetUtil;
import ca.nrc.cadc.net.OutputStreamWrapper;
import ca.nrc.cadc.reg.Standards;
import ca.nrc.cadc.reg.client.RegistryClient;
import ca.nrc.cadc.vos.ContainerNode;
import ca.nrc.cadc.vos.Direction;
import ca.nrc.cadc.vos.Node;
import ca.nrc.cadc.vos.NodeNotFoundException;
import ca.nrc.cadc.vos.NodeParsingException;
import ca.nrc.cadc.vos.NodeProperty;
import ca.nrc.cadc.vos.NodeReader;
import ca.nrc.cadc.vos.NodeWriter;
import ca.nrc.cadc.vos.Protocol;
import ca.nrc.cadc.vos.Transfer;
import ca.nrc.cadc.vos.TransferParsingException;
import ca.nrc.cadc.vos.TransferReader;
import ca.nrc.cadc.vos.TransferWriter;
import ca.nrc.cadc.vos.VOSURI;
import ca.nrc.cadc.vos.View;
/**
* VOSpace client library. This implementation
*
* @author zhangsa
*/
public class VOSpaceClient
{
private static Logger log = Logger.getLogger(VOSpaceClient.class);
public static final String CR = System.getProperty("line.separator"); // OS independant new line
private URI serviceID;
boolean schemaValidation;
/**
* Constructor. XML Schema validation is enabled by default.
*
* @param serviceID
*/
public VOSpaceClient(URI serviceID)
{
this(serviceID, true);
}
/**
* Constructor. XML schema validation may be disabled, in which case the client
* is likely to fail in horrible ways (e.g. NullPointerException) if it receives
* invalid VOSpace (node or transfer) or UWS (job) documents. However, performance
* may be improved.
*
* @param serviceID
* @param enableSchemaValidation
*/
public VOSpaceClient(URI serviceID, boolean enableSchemaValidation)
{
this.schemaValidation = enableSchemaValidation;
this.serviceID = serviceID;
}
/**
* Create the specified node. If the parent (container) nodes do not exist, they
* will also be created.
*
* @param node
* @return the created node
*/
public Node createNode(Node node)
{
return this.createNode(node, true);
}
/**
* Create the specified node. If the parent (container) nodes do not exist, they
* will also be created.
*
* @param node
* @param checkForDuplicate If true, throw duplicate node exception if node
* already exists.
* @return the created node
*/
public Node createNode(Node node, boolean checkForDuplicate)
{
Node rtnNode = null;
log.debug("createNode(), node=" + node + ", checkForDuplicate=" + checkForDuplicate);
try
{
VOSURI parentURI = node.getUri().getParentURI();
ContainerNode parent = null;
if (parentURI == null)
throw new RuntimeException("parent (root node) not found and cannot create: " + node.getUri());
try
{
// check for existence--get the node with minimal content. get the target child
// if we need to check for duplicates.
Node p = null;
if (checkForDuplicate)
p = this.getNode(parentURI.getPath(), "detail=min&limit=1&uri=" + NetUtil.encode(node.getUri().toString()));
else
p = this.getNode(parentURI.getPath(), "detail=min&limit=0");
log.debug("found parent: " + parentURI);
if (p instanceof ContainerNode)
parent = (ContainerNode) p;
else
throw new IllegalArgumentException("cannot create a child, parent is a " + p.getClass().getSimpleName());
}
catch(NodeNotFoundException ex)
{
// if parent does not exist, just create it!!
log.info("creating parent: " + parentURI);
ContainerNode cn = new ContainerNode(parentURI);
parent = (ContainerNode) createNode(cn, false);
}
// check if target already exists: also could fail like this below due to race condition
if (checkForDuplicate)
for (Node n : parent.getNodes())
if (n.getName().equals(node.getName()))
throw new IllegalArgumentException("DuplicateNode: " + node.getUri().getURI().toASCIIString());
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + node.getUri().getPath());
log.debug("createNode(), URL=" + url);
NodeOutputStream out = new NodeOutputStream(node);
HttpUpload put = new HttpUpload(out, url);
put.setContentType("text/xml");
put.run();
VOSClientUtil.checkFailure(put.getThrowable());
NodeReader nodeReader = new NodeReader(schemaValidation);
rtnNode = nodeReader.read(put.getResponseBody());
log.debug("createNode, created node: " + rtnNode);
}
catch (IOException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("failed to create node", e);
}
catch (NodeParsingException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("failed to create node", e);
}
catch (NodeNotFoundException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("Node not found", e);
}
return rtnNode;
}
/**
* Get Node.
*
* @param path The path to the Node.
* @return The Node instance.
* @throws NodeNotFoundException when the requested node does not exist on the server
*/
public Node getNode(String path)
throws NodeNotFoundException
{
return getNode(path, null);
}
/**
* Get Node.
*
* @param path The path to the Node.
* @param query Optional query string
* @return The Node instance.
* @throws NodeNotFoundException when the requested node does not exist on the server
*/
public Node getNode(String path, String query)
throws NodeNotFoundException
{
if ( path.length() > 0 && !path.startsWith("/")) // length 0 is root: no /
path = "/" + path; // must be absolute
if (query != null)
path += "?" + query;
Node rtnNode = null;
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + path);
log.debug("getNode(), URL=" + url);
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpDownload get = new HttpDownload(url, out);
get.run();
VOSClientUtil.checkFailure(get.getThrowable());
String xml = new String(out.toByteArray(), "UTF-8");
log.debug("node xml:\n" + xml);
NodeReader nodeReader = new NodeReader(schemaValidation);
rtnNode = nodeReader.read(xml);
log.debug("getNode, returned node: " + rtnNode);
}
catch (IOException ex)
{
log.debug("failed to get node", ex);
throw new IllegalStateException("failed to get node", ex);
}
catch (NodeParsingException e)
{
log.debug("failed to get node", e);
throw new IllegalStateException("failed to get node", e);
}
return rtnNode;
}
/**
* Add --recursiveMode option to command line, used by set only, and if set
* setNode uses a different recursiveMode endpoint.
*/
/**
* @param node
* @return
*/
public Node setNode(Node node)
{
Node rtnNode = null;
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + node.getUri().getPath());
log.debug("setNode: " + VOSClientUtil.xmlString(node));
log.debug("setNode: " + url);
NodeWriter nodeWriter = new NodeWriter();
StringBuilder nodeXML = new StringBuilder();
nodeWriter.write(node, nodeXML);
HttpPost httpPost = new HttpPost(url, nodeXML.toString(), null, false);
httpPost.run();
VOSClientUtil.checkFailure(httpPost.getThrowable());
String responseBody = httpPost.getResponseBody();
NodeReader nodeReader = new NodeReader();
rtnNode = nodeReader.read(responseBody);
}
catch (IOException e)
{
throw new IllegalStateException("failed to set node", e);
}
catch (NodeParsingException e)
{
throw new IllegalStateException("failed to set node", e);
}
catch (NodeNotFoundException e)
{
throw new IllegalStateException("Node not found", e);
}
return rtnNode;
}
// create an async transfer job
public ClientRecursiveSetNode setNodeRecursive(Node node)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODEPROPS_20);
// String asyncNodePropsUrl = this.baseUrl + VOSPACE_ASYNC_NODEPROPS_ENDPONT;
NodeWriter nodeWriter = new NodeWriter();
Writer stringWriter = new StringWriter();
nodeWriter.write(node, stringWriter);
// URL postUrl = new URL(asyncNodePropsUrl);
HttpPost httpPost = new HttpPost(vospaceURL, stringWriter.toString(), "text/xml", false);
httpPost.run();
VOSClientUtil.checkFailure(httpPost.getThrowable());
URL jobUrl = httpPost.getRedirectURL();
log.debug("Job URL is: " + jobUrl.toString());
// we have only created the job, not run it
return new ClientRecursiveSetNode(jobUrl, node, schemaValidation);
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (NodeNotFoundException e)
{
log.debug("Node not found", e);
throw new RuntimeException(e);
}
}
/**
* Negotiate a transfer. The argument transfer specifies the target URI, the
* direction, the proposed protocols, and an optional view.
*
* @param trans
* @return a negotiated transfer
*/
public ClientTransfer createTransfer(Transfer trans)
{
if (Direction.pushToVoSpace.equals(trans.getDirection()))
return createTransferSync(trans);
if (Direction.pullFromVoSpace.equals(trans.getDirection()))
return createTransferSync(trans);
return createTransferASync(trans);
}
public List<NodeProperty> getProperties()
{
throw new UnsupportedOperationException("Feature under construction.");
}
public List<Protocol> getProtocols()
{
throw new UnsupportedOperationException("Feature under construction.");
}
public List<View> getViews()
{
throw new UnsupportedOperationException("Feature under construction.");
}
/**
* Remove the Node associated with the given Path.
* @param path The path of the Node to delete.
*/
public void deleteNode(final String path)
{
// length 0 is root: no
// Path must be absolute
final String nodePath = (path.length() > 0 && !path.startsWith("/"))
? ("/" + path) : path;
try
{
final URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
final URL url = new URL(vospaceURL.toExternalForm() + nodePath);
final HttpDelete httpDelete = new HttpDelete(url, false);
httpDelete.run();
VOSClientUtil.checkFailure(httpDelete.getThrowable());
}
catch (MalformedURLException e)
{
log.debug(String.format("Error creating URL from %s", nodePath));
throw new RuntimeException(e);
}
catch (NodeNotFoundException e)
{
log.debug("Node not found", e);
throw new RuntimeException(e);
}
}
protected RegistryClient getRegistryClient()
{
return new RegistryClient();
}
protected URL getServiceURL(URI serviceID, URI standard, AuthMethod authMethod)
{
RegistryClient registryClient = new RegistryClient();
return registryClient.getServiceURL(serviceID, standard, authMethod);
}
// create an async transfer job
private ClientTransfer createTransferASync(Transfer transfer)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_TRANSFERS_20);
// String asyncTransUrl = this.baseUrl + VOSPACE_ASYNC_TRANSFER_ENDPOINT;
TransferWriter transferWriter = new TransferWriter();
Writer stringWriter = new StringWriter();
transferWriter.write(transfer, stringWriter);
// URL postUrl = new URL(asyncTransUrl);
HttpPost httpPost = new HttpPost(vospaceURL, stringWriter.toString(), "text/xml", false);
httpPost.run();
if (httpPost.getThrowable() != null)
{
log.debug("Unable to post transfer because ", httpPost.getThrowable());
throw new RuntimeException("Unable to post transfer because " + httpPost.getThrowable().getMessage());
}
URL jobUrl = httpPost.getRedirectURL();
log.debug("Job URL is: " + jobUrl.toString());
// we have only created the job, not run it
return new ClientTransfer(jobUrl, transfer, schemaValidation);
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
}
// create a transfer using the sync transfers job resource
private ClientTransfer createTransferSync(Transfer transfer)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_SYNC_21);
log.debug("vospaceURL: " + vospaceURL);
HttpPost httpPost = null;
if (transfer.isQuickTransfer())
{
Map<String, Object> form = new HashMap<String, Object>();
form.put("TARGET", transfer.getTarget());
form.put("DIRECTION", transfer.getDirection().getValue());
form.put("PROTOCOL", transfer.getProtocols().iterator().
next().getUri()); // try first protocol?
httpPost = new HttpPost(vospaceURL, form, false);
}
else
{
// POST the Job and get the redirect location.
TransferWriter writer = new TransferWriter();
StringWriter sw = new StringWriter();
writer.write(transfer, sw);
httpPost = new HttpPost(vospaceURL, sw.toString(), "text/xml", false);
}
httpPost.run();
if (httpPost.getThrowable() != null)
{
log.debug("Unable to post transfer because ", httpPost.getThrowable());
throw new RuntimeException("Unable to post transfer because " + httpPost.getThrowable().getMessage());
}
URL redirectURL = httpPost.getRedirectURL();
if (redirectURL == null)
{
throw new RuntimeException("Redirect not received from UWS.");
}
if( transfer.isQuickTransfer())
{
log.debug("Quick transfer URL: " + redirectURL);
// create a new transfer with a protocol with an end point
List<Protocol> prots = new ArrayList<Protocol>();
prots.add(new Protocol(transfer.getProtocols().iterator().next().getUri(), redirectURL.toString(), null));
Transfer trf = new Transfer(transfer.getTarget(), transfer.getDirection(), prots);
return new ClientTransfer(null, trf, false);
}
else
{
log.debug("POST: transfer jobURL: " + redirectURL);
// follow the redirect to run the job
log.debug("GET - opening connection: " + redirectURL.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpDownload get = new HttpDownload(redirectURL, out);
get.run();
if (get.getThrowable() != null)
{
log.debug("Unable to run the job", get.getThrowable());
throw new RuntimeException("Unable to run the job because " + get.getThrowable().getMessage());
}
String transDoc = new String(out.toByteArray(), "UTF-8");
log.debug("transfer response: " + transDoc);
TransferReader txfReader = new TransferReader(schemaValidation);
log.debug("GET - reading content: " + redirectURL);
Transfer trans = txfReader.read(transDoc, VOSURI.SCHEME);
log.debug("GET - done: " + redirectURL);
log.debug("negotiated transfer: " + trans);
//URL jobURL = extractJobURL(vospaceURL.toString(), redirectURL);
// temporary hack:
URL jobURL = new URL(redirectURL.toString().substring(0, redirectURL.toString().length() - "/results/transferDetails".length()));
log.debug("extracted job url: " + jobURL);
return new ClientTransfer(jobURL, trans, schemaValidation);
}
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
/*
catch (JDOMException e) // from JobReader
{
log.debug("got bad job XML from service", e);
throw new RuntimeException(e);
}
catch (ParseException e) // from JobReader
{
log.debug("got bad job XML from service", e);
throw new RuntimeException(e);
}
*/
catch (TransferParsingException e)
{
log.debug("got invalid XML from service", e);
throw new RuntimeException(e);
}
}
// determine the jobURL from the service base URL and the URL to
// transfer details... makes assumptions about paths structure that
// can be simplified once we comply to spec
private URL extractJobURL(String baseURL, URL transferDetailsURL)
throws MalformedURLException
{
//log.warn("baseURL: " + baseURL);
URL u = new URL(baseURL);
String bp = u.getPath();
//log.warn("bp: " + bp);
String tu = transferDetailsURL.toExternalForm();
//log.warn("tu: " + tu);
int i = tu.indexOf(bp);
String jp = tu.substring(i + bp.length() + 1); // strip /
//log.warn("jp: " + jp);
String[] parts = jp.split("/");
// part[0] is the joblist
// part[1] is the jobID
// part[2-] is either run (current impl) or results/transferDetails (spec)
String jobList = parts[0];
String jobID = parts[1];
//log.warn("jobList: " + jobList);
//log.warn("jobID: " + jobID);
return new URL(baseURL + "/" + jobList + "/" + jobID);
}
private class NodeOutputStream implements OutputStreamWrapper
{
private Node node;
public NodeOutputStream(Node node)
{
this.node = node;
}
public void write(OutputStream out) throws IOException
{
NodeWriter writer = new NodeWriter();
writer.write(node, out);
}
}
// temporary fix -- the code below needs to be moved out to a library
private URL lookupServiceURL(final URI standard)
throws AccessControlException
{
Subject subject = AuthenticationUtil.getCurrentSubject();
AuthMethod am = AuthenticationUtil.getAuthMethodFromCredentials(subject);
URL serviceURL = getRegistryClient().getServiceURL(this.serviceID, standard, am);
if (serviceURL == null)
{
throw new RuntimeException(
String.format("Unable to get Service URL for '%s', '%s', '%s'",
serviceID.toString(), standard, am));
}
return serviceURL;
}
}
| cadc-vos/src/main/java/ca/nrc/cadc/vos/client/VOSpaceClient.java | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2009. (c) 2009.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 4 $
*
************************************************************************
*/
package ca.nrc.cadc.vos.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import org.apache.log4j.Logger;
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.auth.SSOCookieCredential;
import ca.nrc.cadc.auth.X509CertificateChain;
import ca.nrc.cadc.net.HttpDelete;
import ca.nrc.cadc.net.HttpDownload;
import ca.nrc.cadc.net.HttpPost;
import ca.nrc.cadc.net.HttpUpload;
import ca.nrc.cadc.net.NetUtil;
import ca.nrc.cadc.net.OutputStreamWrapper;
import ca.nrc.cadc.reg.Standards;
import ca.nrc.cadc.reg.client.RegistryClient;
import ca.nrc.cadc.vos.ContainerNode;
import ca.nrc.cadc.vos.Direction;
import ca.nrc.cadc.vos.Node;
import ca.nrc.cadc.vos.NodeNotFoundException;
import ca.nrc.cadc.vos.NodeParsingException;
import ca.nrc.cadc.vos.NodeProperty;
import ca.nrc.cadc.vos.NodeReader;
import ca.nrc.cadc.vos.NodeWriter;
import ca.nrc.cadc.vos.Protocol;
import ca.nrc.cadc.vos.Transfer;
import ca.nrc.cadc.vos.TransferParsingException;
import ca.nrc.cadc.vos.TransferReader;
import ca.nrc.cadc.vos.TransferWriter;
import ca.nrc.cadc.vos.VOSURI;
import ca.nrc.cadc.vos.View;
/**
* VOSpace client library. This implementation
*
* @author zhangsa
*/
public class VOSpaceClient
{
private static Logger log = Logger.getLogger(VOSpaceClient.class);
public static final String CR = System.getProperty("line.separator"); // OS independant new line
private URI serviceID;
boolean schemaValidation;
/**
* Constructor. XML Schema validation is enabled by default.
*
* @param serviceID
*/
public VOSpaceClient(URI serviceID)
{
this(serviceID, true);
}
/**
* Constructor. XML schema validation may be disabled, in which case the client
* is likely to fail in horrible ways (e.g. NullPointerException) if it receives
* invalid VOSpace (node or transfer) or UWS (job) documents. However, performance
* may be improved.
*
* @param serviceID
* @param enableSchemaValidation
*/
public VOSpaceClient(URI serviceID, boolean enableSchemaValidation)
{
this.schemaValidation = enableSchemaValidation;
this.serviceID = serviceID;
}
/**
* Create the specified node. If the parent (container) nodes do not exist, they
* will also be created.
*
* @param node
* @return the created node
*/
public Node createNode(Node node)
{
return this.createNode(node, true);
}
/**
* Create the specified node. If the parent (container) nodes do not exist, they
* will also be created.
*
* @param node
* @param checkForDuplicate If true, throw duplicate node exception if node
* already exists.
* @return the created node
*/
public Node createNode(Node node, boolean checkForDuplicate)
{
Node rtnNode = null;
log.debug("createNode(), node=" + node + ", checkForDuplicate=" + checkForDuplicate);
try
{
VOSURI parentURI = node.getUri().getParentURI();
ContainerNode parent = null;
if (parentURI == null)
throw new RuntimeException("parent (root node) not found and cannot create: " + node.getUri());
try
{
// check for existence--get the node with minimal content. get the target child
// if we need to check for duplicates.
Node p = null;
if (checkForDuplicate)
p = this.getNode(parentURI.getPath(), "detail=min&limit=1&uri=" + NetUtil.encode(node.getUri().toString()));
else
p = this.getNode(parentURI.getPath(), "detail=min&limit=0");
log.debug("found parent: " + parentURI);
if (p instanceof ContainerNode)
parent = (ContainerNode) p;
else
throw new IllegalArgumentException("cannot create a child, parent is a " + p.getClass().getSimpleName());
}
catch(NodeNotFoundException ex)
{
// if parent does not exist, just create it!!
log.info("creating parent: " + parentURI);
ContainerNode cn = new ContainerNode(parentURI);
parent = (ContainerNode) createNode(cn, false);
}
// check if target already exists: also could fail like this below due to race condition
if (checkForDuplicate)
for (Node n : parent.getNodes())
if (n.getName().equals(node.getName()))
throw new IllegalArgumentException("DuplicateNode: " + node.getUri().getURI().toASCIIString());
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + node.getUri().getPath());
log.debug("createNode(), URL=" + url);
NodeOutputStream out = new NodeOutputStream(node);
HttpUpload put = new HttpUpload(out, url);
put.setContentType("text/xml");
put.run();
VOSClientUtil.checkFailure(put.getThrowable());
NodeReader nodeReader = new NodeReader(schemaValidation);
rtnNode = nodeReader.read(put.getResponseBody());
log.debug("createNode, created node: " + rtnNode);
}
catch (IOException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("failed to create node", e);
}
catch (NodeParsingException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("failed to create node", e);
}
catch (NodeNotFoundException e)
{
log.debug("failed to create node", e);
throw new IllegalStateException("Node not found", e);
}
return rtnNode;
}
/**
* Get Node.
*
* @param path The path to the Node.
* @return The Node instance.
* @throws NodeNotFoundException when the requested node does not exist on the server
*/
public Node getNode(String path)
throws NodeNotFoundException
{
return getNode(path, null);
}
/**
* Get Node.
*
* @param path The path to the Node.
* @param query Optional query string
* @return The Node instance.
* @throws NodeNotFoundException when the requested node does not exist on the server
*/
public Node getNode(String path, String query)
throws NodeNotFoundException
{
if ( path.length() > 0 && !path.startsWith("/")) // length 0 is root: no /
path = "/" + path; // must be absolute
if (query != null)
path += "?" + query;
Node rtnNode = null;
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + path);
log.debug("getNode(), URL=" + url);
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpDownload get = new HttpDownload(url, out);
get.run();
VOSClientUtil.checkFailure(get.getThrowable());
String xml = new String(out.toByteArray(), "UTF-8");
log.debug("node xml:\n" + xml);
NodeReader nodeReader = new NodeReader(schemaValidation);
rtnNode = nodeReader.read(xml);
log.debug("getNode, returned node: " + rtnNode);
}
catch (IOException ex)
{
log.debug("failed to get node", ex);
throw new IllegalStateException("failed to get node", ex);
}
catch (NodeParsingException e)
{
log.debug("failed to get node", e);
throw new IllegalStateException("failed to get node", e);
}
return rtnNode;
}
/**
* Add --recursiveMode option to command line, used by set only, and if set
* setNode uses a different recursiveMode endpoint.
*/
/**
* @param node
* @return
*/
public Node setNode(Node node)
{
Node rtnNode = null;
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
URL url = new URL(vospaceURL.toExternalForm() + node.getUri().getPath());
log.debug("setNode: " + VOSClientUtil.xmlString(node));
log.debug("setNode: " + url);
NodeWriter nodeWriter = new NodeWriter();
StringBuilder nodeXML = new StringBuilder();
nodeWriter.write(node, nodeXML);
HttpPost httpPost = new HttpPost(url, nodeXML.toString(), null, false);
httpPost.run();
VOSClientUtil.checkFailure(httpPost.getThrowable());
String responseBody = httpPost.getResponseBody();
NodeReader nodeReader = new NodeReader();
rtnNode = nodeReader.read(responseBody);
}
catch (IOException e)
{
throw new IllegalStateException("failed to set node", e);
}
catch (NodeParsingException e)
{
throw new IllegalStateException("failed to set node", e);
}
catch (NodeNotFoundException e)
{
throw new IllegalStateException("Node not found", e);
}
return rtnNode;
}
// create an async transfer job
public ClientRecursiveSetNode setNodeRecursive(Node node)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODEPROPS_20);
// String asyncNodePropsUrl = this.baseUrl + VOSPACE_ASYNC_NODEPROPS_ENDPONT;
NodeWriter nodeWriter = new NodeWriter();
Writer stringWriter = new StringWriter();
nodeWriter.write(node, stringWriter);
// URL postUrl = new URL(asyncNodePropsUrl);
HttpPost httpPost = new HttpPost(vospaceURL, stringWriter.toString(), "text/xml", false);
httpPost.run();
VOSClientUtil.checkFailure(httpPost.getThrowable());
URL jobUrl = httpPost.getRedirectURL();
log.debug("Job URL is: " + jobUrl.toString());
// we have only created the job, not run it
return new ClientRecursiveSetNode(jobUrl, node, schemaValidation);
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (NodeNotFoundException e)
{
log.debug("Node not found", e);
throw new RuntimeException(e);
}
}
/**
* Negotiate a transfer. The argument transfer specifies the target URI, the
* direction, the proposed protocols, and an optional view.
*
* @param trans
* @return a negotiated transfer
*/
public ClientTransfer createTransfer(Transfer trans)
{
if (Direction.pushToVoSpace.equals(trans.getDirection()))
return createTransferSync(trans);
if (Direction.pullFromVoSpace.equals(trans.getDirection()))
return createTransferSync(trans);
return createTransferASync(trans);
}
public List<NodeProperty> getProperties()
{
throw new UnsupportedOperationException("Feature under construction.");
}
public List<Protocol> getProtocols()
{
throw new UnsupportedOperationException("Feature under construction.");
}
public List<View> getViews()
{
throw new UnsupportedOperationException("Feature under construction.");
}
/**
* Remove the Node associated with the given Path.
* @param path The path of the Node to delete.
*/
public void deleteNode(final String path)
{
// length 0 is root: no
// Path must be absolute
final String nodePath = (path.length() > 0 && !path.startsWith("/"))
? ("/" + path) : path;
try
{
final URL vospaceURL = lookupServiceURL(Standards.VOSPACE_NODES_20);
final URL url = new URL(vospaceURL.toExternalForm() + nodePath);
final HttpDelete httpDelete = new HttpDelete(url, false);
httpDelete.run();
VOSClientUtil.checkFailure(httpDelete.getThrowable());
}
catch (MalformedURLException e)
{
log.debug(String.format("Error creating URL from %s", nodePath));
throw new RuntimeException(e);
}
catch (NodeNotFoundException e)
{
log.debug("Node not found", e);
throw new RuntimeException(e);
}
}
protected RegistryClient getRegistryClient()
{
return new RegistryClient();
}
protected URL getServiceURL(URI serviceID, URI standard, AuthMethod authMethod)
{
RegistryClient registryClient = new RegistryClient();
return registryClient.getServiceURL(serviceID, standard, authMethod);
}
// create an async transfer job
private ClientTransfer createTransferASync(Transfer transfer)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_TRANSFERS_20);
// String asyncTransUrl = this.baseUrl + VOSPACE_ASYNC_TRANSFER_ENDPOINT;
TransferWriter transferWriter = new TransferWriter();
Writer stringWriter = new StringWriter();
transferWriter.write(transfer, stringWriter);
// URL postUrl = new URL(asyncTransUrl);
HttpPost httpPost = new HttpPost(vospaceURL, stringWriter.toString(), "text/xml", false);
httpPost.run();
if (httpPost.getThrowable() != null)
{
log.debug("Unable to post transfer because ", httpPost.getThrowable());
throw new RuntimeException("Unable to post transfer because " + httpPost.getThrowable().getMessage());
}
URL jobUrl = httpPost.getRedirectURL();
log.debug("Job URL is: " + jobUrl.toString());
// we have only created the job, not run it
return new ClientTransfer(jobUrl, transfer, schemaValidation);
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
}
// create a transfer using the sync transfers job resource
private ClientTransfer createTransferSync(Transfer transfer)
{
try
{
URL vospaceURL = lookupServiceURL(Standards.VOSPACE_SYNC_21);
log.debug("vospaceURL: " + vospaceURL);
HttpPost httpPost = null;
if (transfer.isQuickTransfer())
{
Map<String, Object> form = new HashMap<String, Object>();
form.put("TARGET", transfer.getTarget());
form.put("DIRECTION", transfer.getDirection().getValue());
form.put("PROTOCOL", transfer.getProtocols().iterator().
next().getUri()); // try first protocol?
httpPost = new HttpPost(vospaceURL, form, false);
}
else
{
// POST the Job and get the redirect location.
TransferWriter writer = new TransferWriter();
StringWriter sw = new StringWriter();
writer.write(transfer, sw);
httpPost = new HttpPost(vospaceURL, sw.toString(), "text/xml", false);
}
httpPost.run();
if (httpPost.getThrowable() != null)
{
log.debug("Unable to post transfer because ", httpPost.getThrowable());
throw new RuntimeException("Unable to post transfer because " + httpPost.getThrowable().getMessage());
}
URL redirectURL = httpPost.getRedirectURL();
if (redirectURL == null)
{
throw new RuntimeException("Redirect not received from UWS.");
}
if( transfer.isQuickTransfer())
{
log.debug("Quick transfer URL: " + redirectURL);
// create a new transfer with a protocol with an end point
List<Protocol> prots = new ArrayList<Protocol>();
prots.add(new Protocol(transfer.getProtocols().iterator().next().getUri(), redirectURL.toString(), null));
Transfer trf = new Transfer(transfer.getTarget(), transfer.getDirection(), prots);
return new ClientTransfer(null, trf, false);
}
else
{
log.debug("POST: transfer jobURL: " + redirectURL);
// follow the redirect to run the job
log.debug("GET - opening connection: " + redirectURL.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpDownload get = new HttpDownload(redirectURL, out);
get.run();
if (get.getThrowable() != null)
{
log.debug("Unable to run the job", get.getThrowable());
throw new RuntimeException("Unable to run the job because " + get.getThrowable().getMessage());
}
String transDoc = new String(out.toByteArray(), "UTF-8");
log.debug("transfer response: " + transDoc);
TransferReader txfReader = new TransferReader(schemaValidation);
log.debug("GET - reading content: " + redirectURL);
Transfer trans = txfReader.read(transDoc, VOSURI.SCHEME);
log.debug("GET - done: " + redirectURL);
log.debug("negotiated transfer: " + trans);
//URL jobURL = extractJobURL(vospaceURL.toString(), redirectURL);
// temporary hack:
URL jobURL = new URL(redirectURL.toString().substring(0, redirectURL.toString().length() - "/results/transferDetails".length()));
log.debug("extracted job url: " + jobURL);
return new ClientTransfer(jobURL, trans, schemaValidation);
}
}
catch (MalformedURLException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
catch (IOException e)
{
log.debug("failed to create transfer", e);
throw new RuntimeException(e);
}
/*
catch (JDOMException e) // from JobReader
{
log.debug("got bad job XML from service", e);
throw new RuntimeException(e);
}
catch (ParseException e) // from JobReader
{
log.debug("got bad job XML from service", e);
throw new RuntimeException(e);
}
*/
catch (TransferParsingException e)
{
log.debug("got invalid XML from service", e);
throw new RuntimeException(e);
}
}
// determine the jobURL from the service base URL and the URL to
// transfer details... makes assumptions about paths structure that
// can be simplified once we comply to spec
private URL extractJobURL(String baseURL, URL transferDetailsURL)
throws MalformedURLException
{
//log.warn("baseURL: " + baseURL);
URL u = new URL(baseURL);
String bp = u.getPath();
//log.warn("bp: " + bp);
String tu = transferDetailsURL.toExternalForm();
//log.warn("tu: " + tu);
int i = tu.indexOf(bp);
String jp = tu.substring(i + bp.length() + 1); // strip /
//log.warn("jp: " + jp);
String[] parts = jp.split("/");
// part[0] is the joblist
// part[1] is the jobID
// part[2-] is either run (current impl) or results/transferDetails (spec)
String jobList = parts[0];
String jobID = parts[1];
//log.warn("jobList: " + jobList);
//log.warn("jobID: " + jobID);
return new URL(baseURL + "/" + jobList + "/" + jobID);
}
private class NodeOutputStream implements OutputStreamWrapper
{
private Node node;
public NodeOutputStream(Node node)
{
this.node = node;
}
public void write(OutputStream out) throws IOException
{
NodeWriter writer = new NodeWriter();
writer.write(node, out);
}
}
// temporary fix -- the code below needs to be moved out to a library
private URL lookupServiceURL(final URI standard)
throws AccessControlException
{
Subject subject = AuthenticationUtil.getCurrentSubject();
AuthMethod am = AuthenticationUtil.getAuthMethodFromCredentials(subject);
URL serviceURL = getRegistryClient().getServiceURL(this.serviceID, standard, am);
// now that we have a URL we can check if the cookie will actually be sent to it
if (AuthMethod.COOKIE.equals(am))
{
try
{
boolean domainMatch = false;
String domain = NetUtil.getDomainName(serviceURL);
for (SSOCookieCredential cc : subject.getPublicCredentials(SSOCookieCredential.class))
{
if (cc.getDomain().equals(domain))
domainMatch = true;
}
if (!domainMatch)
{
throw new AccessControlException("no SSOCookieCredential for domain " + domain);
}
}
catch(IOException ex)
{
throw new RuntimeException("failure checking domain for cookie use", ex);
}
}
if (serviceURL == null)
{
throw new RuntimeException(
String.format("Unable to get Service URL for '%s', '%s', '%s'",
serviceID.toString(), standard, am));
}
return serviceURL;
}
}
| no cookie domain check in client
| cadc-vos/src/main/java/ca/nrc/cadc/vos/client/VOSpaceClient.java | no cookie domain check in client | <ide><path>adc-vos/src/main/java/ca/nrc/cadc/vos/client/VOSpaceClient.java
<ide>
<ide> URL serviceURL = getRegistryClient().getServiceURL(this.serviceID, standard, am);
<ide>
<del> // now that we have a URL we can check if the cookie will actually be sent to it
<del> if (AuthMethod.COOKIE.equals(am))
<del> {
<del> try
<del> {
<del> boolean domainMatch = false;
<del> String domain = NetUtil.getDomainName(serviceURL);
<del> for (SSOCookieCredential cc : subject.getPublicCredentials(SSOCookieCredential.class))
<del> {
<del> if (cc.getDomain().equals(domain))
<del> domainMatch = true;
<del> }
<del> if (!domainMatch)
<del> {
<del> throw new AccessControlException("no SSOCookieCredential for domain " + domain);
<del> }
<del> }
<del> catch(IOException ex)
<del> {
<del> throw new RuntimeException("failure checking domain for cookie use", ex);
<del> }
<del> }
<del>
<ide> if (serviceURL == null)
<ide> {
<ide> throw new RuntimeException( |
|
Java | apache-2.0 | 8a34ffb4ae83372d2481b74196cc14124948d834 | 0 | heuer/cassa | /*
* Copyright 2011 Lars Heuer (heuer[at]semagia.com). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.semagia.cassa.jaxrs;
import static com.semagia.cassa.jaxrs.ResponseUtils.accepted;
import static com.semagia.cassa.jaxrs.ResponseUtils.buildStreamingEntity;
import static com.semagia.cassa.jaxrs.ResponseUtils.created;
import static com.semagia.cassa.jaxrs.ResponseUtils.noContent;
import java.io.InputStream;
import java.net.URI;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.semagia.cassa.common.MediaType;
import com.semagia.cassa.common.dm.IGraphInfo;
import com.semagia.cassa.server.store.IStore;
import com.semagia.cassa.server.store.RemovalStatus;
import com.semagia.cassa.server.store.StoreException;
/**
* Common graph resource which implements all operations above graphs.
*
* @author Lars Heuer (heuer[at]semagia.com) <a href="http://www.semagia.com/">Semagia</a>
*/
public abstract class AbstractGraphResource extends AbstractResource {
@Context
protected UriInfo _uriInfo;
/**
* Returns the graph IRI.
*
* @return The graph IRI to operate on. {@code null} indicates the default graph.
*/
protected abstract URI getGraphURI();
/**
*
*
* @return A graph serialization.
* @throws StorageException In case of an error.
*/
@GET
public Response getGraph() throws StoreException {
final URI graphURI = getGraphURI();
final IStore store = getStore();
final IGraphInfo graph = store.getGraphInfo(graphURI);
final MediaType mt = getMediaType(graph.getSupportedMediaTypes());
return buildStreamingEntity(
makeResponseBuilder(graph.getLastModification()), store.getGraph(graphURI, mt));
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@PUT
public Response createGraph(InputStream in, @Context HttpHeaders header) throws StoreException {
final URI graphURI = getGraphURI();
final IStore store = getStore();
final MediaType mt = MediaTypeUtils.toMediaType(header.getMediaType());
final boolean wasKnown = store.containsGraph(graphURI);
final IGraphInfo info = store.createOrReplaceGraph(graphURI, in, getBaseURI(graphURI), mt);
//TODO: Is it a good idea to return the IRI here? It may refer to an external server...
return wasKnown ? noContent() : created(info.getURI());
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@POST
public Response mergeGraph(InputStream in, @Context HttpHeaders header) throws StoreException {
//TODO: Ensure that the location points to this server.
final URI graphURI = getGraphURI();
final IStore store = getStore();
final MediaType mt = MediaTypeUtils.toMediaType(header.getMediaType());
final boolean wasKnown = store.containsGraph(graphURI);
final IGraphInfo info = store.createOrUpdateGraph(graphURI, in, getBaseURI(graphURI), mt);
return wasKnown ? noContent() : created(info.getURI());
}
/**
* Returns the base URI.
*
* @param graphURI The graph URI.
* @return The {@code graphURI} if it does not represent the default graph,
* otherwise a URI which represents the path to this resource.
*/
private URI getBaseURI(URI graphURI) {
return graphURI == IStore.DEFAULT_GRAPH ? _uriInfo.getAbsolutePath() : graphURI;
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@DELETE
public Response deleteGraph() throws StoreException {
return getStore().deleteGraph(getGraphURI()) == RemovalStatus.DELAYED ? accepted() : noContent();
}
}
| cassa-server-jaxrs/src/main/java/com/semagia/cassa/jaxrs/AbstractGraphResource.java | /*
* Copyright 2011 Lars Heuer (heuer[at]semagia.com). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.semagia.cassa.jaxrs;
import static com.semagia.cassa.jaxrs.ResponseUtils.accepted;
import static com.semagia.cassa.jaxrs.ResponseUtils.buildStreamingEntity;
import static com.semagia.cassa.jaxrs.ResponseUtils.created;
import static com.semagia.cassa.jaxrs.ResponseUtils.noContent;
import java.io.InputStream;
import java.net.URI;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.semagia.cassa.common.MediaType;
import com.semagia.cassa.common.dm.IGraphInfo;
import com.semagia.cassa.server.store.IStore;
import com.semagia.cassa.server.store.RemovalStatus;
import com.semagia.cassa.server.store.StoreException;
/**
* Common graph resource which implements all operations above graphs.
*
* @author Lars Heuer (heuer[at]semagia.com) <a href="http://www.semagia.com/">Semagia</a>
*/
public abstract class AbstractGraphResource extends AbstractResource {
@Context
protected UriInfo _uriInfo;
/**
* Returns the graph IRI.
*
* @return The graph IRI to operate on. {@code null} indicates the default graph.
*/
protected abstract URI getGraphURI();
/**
*
*
* @return A graph serialization.
* @throws StorageException In case of an error.
*/
@GET
public Response getGraph() throws StoreException {
final URI graphURI = getGraphURI();
final IStore store = getStore();
final IGraphInfo graph = store.getGraphInfo(graphURI);
final MediaType mt = getMediaType(graph.getSupportedMediaTypes());
return buildStreamingEntity(
makeResponseBuilder(graph.getLastModification()), store.getGraph(graphURI, mt));
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@PUT
public Response createGraph(InputStream in, @Context HttpHeaders header) throws StoreException {
final URI graphURI = getGraphURI();
final IStore store = getStore();
final MediaType mt = MediaTypeUtils.toMediaType(header.getMediaType());
final boolean wasKnown = store.containsGraph(graphURI);
final IGraphInfo info = store.createOrReplaceGraph(graphURI, in, getBaseURI(graphURI) mt);
//TODO: Is it a good idea to return the IRI here? It may refer to an external server...
return wasKnown ? noContent() : created(info.getURI());
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@POST
public Response mergeGraph(InputStream in, @Context HttpHeaders header) throws StoreException {
//TODO: Ensure that the location points to this server.
final URI graphURI = getGraphURI();
final IStore store = getStore();
final MediaType mt = MediaTypeUtils.toMediaType(header.getMediaType());
final boolean wasKnown = store.containsGraph(graphURI);
final IGraphInfo info = store.createOrUpdateGraph(graphURI, in, getBaseURI(graphURI), mt);
return wasKnown ? noContent() : created(info.getURI());
}
/**
* Returns the base URI.
*
* @param graphURI The graph URI.
* @return The {@code graphURI} if it does not represent the default graph,
* otherwise a URI which represents the path to this resource.
*/
private URI getBaseURI(URI graphURI) {
return graphURI == IStore.DEFAULT_GRAPH ? _uriInfo.getAbsolutePath() : graphURI;
}
/**
*
*
* @return
* @throws StorageException In case of an error.
*/
@DELETE
public Response deleteGraph() throws StoreException {
return getStore().deleteGraph(getGraphURI()) == RemovalStatus.DELAYED ? accepted() : noContent();
}
}
| Committed wrong version. Fixed.
| cassa-server-jaxrs/src/main/java/com/semagia/cassa/jaxrs/AbstractGraphResource.java | Committed wrong version. Fixed. | <ide><path>assa-server-jaxrs/src/main/java/com/semagia/cassa/jaxrs/AbstractGraphResource.java
<ide> final IStore store = getStore();
<ide> final MediaType mt = MediaTypeUtils.toMediaType(header.getMediaType());
<ide> final boolean wasKnown = store.containsGraph(graphURI);
<del> final IGraphInfo info = store.createOrReplaceGraph(graphURI, in, getBaseURI(graphURI) mt);
<add> final IGraphInfo info = store.createOrReplaceGraph(graphURI, in, getBaseURI(graphURI), mt);
<ide> //TODO: Is it a good idea to return the IRI here? It may refer to an external server...
<ide> return wasKnown ? noContent() : created(info.getURI());
<ide> } |
|
JavaScript | mit | 1a11bb8b86f295aba475fc64f1754f84a5a56731 | 0 | wikimedia/oojs-ui,wikimedia/oojs-ui,wikimedia/oojs-ui,wikimedia/oojs-ui | /**
* Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
* that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
* connected to them and can't be interacted with.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
* to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
* @cfg {string} [id] The HTML id attribute used in the rendered tag.
* @cfg {string} [text] Text to insert
* @cfg {Array} [content] An array of content elements to append (after #text).
* Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
* Instances of OO.ui.Element will have their $element appended.
* @cfg {jQuery} [$content] Content elements to append (after #text).
* @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
* @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
* Data can also be specified with the #setData method.
*/
OO.ui.Element = function OoUiElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$ = $;
this.visible = true;
this.data = config.data;
this.$element = config.$element ||
$( document.createElement( this.getTagName() ) );
this.elementGroup = null;
// Initialization
if ( Array.isArray( config.classes ) ) {
this.$element.addClass( config.classes.join( ' ' ) );
}
if ( config.id ) {
this.$element.attr( 'id', config.id );
}
if ( config.text ) {
this.$element.text( config.text );
}
if ( config.content ) {
// The `content` property treats plain strings as text; use an
// HtmlSnippet to append HTML content. `OO.ui.Element`s get their
// appropriate $element appended.
this.$element.append( config.content.map( function ( v ) {
if ( typeof v === 'string' ) {
// Escape string so it is properly represented in HTML.
return document.createTextNode( v );
} else if ( v instanceof OO.ui.HtmlSnippet ) {
// Bypass escaping.
return v.toString();
} else if ( v instanceof OO.ui.Element ) {
return v.$element;
}
return v;
} ) );
}
if ( config.$content ) {
// The `$content` property treats plain strings as HTML.
this.$element.append( config.$content );
}
};
/* Setup */
OO.initClass( OO.ui.Element );
/* Static Properties */
/**
* The name of the HTML tag used by the element.
*
* The static value may be ignored if the #getTagName method is overridden.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Element.static.tagName = 'div';
/* Static Methods */
/**
* Reconstitute a JavaScript object corresponding to a widget created
* by the PHP implementation.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
* For `Tag` objects emitted on the HTML side (used occasionally for content)
* the value returned is a newly-created Element wrapping around the existing
* DOM node.
*/
OO.ui.Element.static.infuse = function ( idOrNode ) {
var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
// Verify that the type matches up.
// FIXME: uncomment after T89721 is fixed (see T90929)
/*
if ( !( obj instanceof this['class'] ) ) {
throw new Error( 'Infusion type mismatch!' );
}
*/
return obj;
};
/**
* Implementation helper for `infuse`; skips the type check and has an
* extra property so that only the top-level invocation touches the DOM.
*
* @private
* @param {string|HTMLElement|jQuery} idOrNode
* @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
* when the top-level widget of this infusion is inserted into DOM,
* replacing the original node; or false for top-level invocation.
* @return {OO.ui.Element}
*/
OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
// look for a cached result of a previous infusion.
var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren;
if ( typeof idOrNode === 'string' ) {
id = idOrNode;
$elem = $( document.getElementById( id ) );
} else {
$elem = $( idOrNode );
id = $elem.attr( 'id' );
}
if ( !$elem.length ) {
throw new Error( 'Widget not found: ' + id );
}
if ( $elem[ 0 ].oouiInfused ) {
$elem = $elem[ 0 ].oouiInfused;
}
data = $elem.data( 'ooui-infused' );
if ( data ) {
// cached!
if ( data === true ) {
throw new Error( 'Circular dependency! ' + id );
}
if ( domPromise ) {
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = data.constructor.static.gatherPreInfuseState( $elem, data );
// restore dynamic state after the new element is re-inserted into DOM under infused parent
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
infusedChildren = $elem.data( 'ooui-infused-children' );
if ( infusedChildren && infusedChildren.length ) {
infusedChildren.forEach( function ( data ) {
var state = data.constructor.static.gatherPreInfuseState( $elem, data );
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
} );
}
}
return data;
}
data = $elem.attr( 'data-ooui' );
if ( !data ) {
throw new Error( 'No infusion data found: ' + id );
}
try {
data = $.parseJSON( data );
} catch ( _ ) {
data = null;
}
if ( !( data && data._ ) ) {
throw new Error( 'No valid infusion data found: ' + id );
}
if ( data._ === 'Tag' ) {
// Special case: this is a raw Tag; wrap existing node, don't rebuild.
return new OO.ui.Element( { $element: $elem } );
}
parts = data._.split( '.' );
cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
if ( cls === undefined ) {
// The PHP output might be old and not including the "OO.ui" prefix
// TODO: Remove this back-compat after next major release
cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
if ( cls === undefined ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
}
// Verify that we're creating an OO.ui.Element instance
parent = cls.parent;
while ( parent !== undefined ) {
if ( parent === OO.ui.Element ) {
// Safe
break;
}
parent = parent.parent;
}
if ( parent !== OO.ui.Element ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
if ( domPromise === false ) {
top = $.Deferred();
domPromise = top.promise();
}
$elem.data( 'ooui-infused', true ); // prevent loops
data.id = id; // implicit
infusedChildren = [];
data = OO.copy( data, null, function deserialize( value ) {
var infused;
if ( OO.isPlainObject( value ) ) {
if ( value.tag ) {
infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
infusedChildren.push( infused );
// Flatten the structure
infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
infused.$element.removeData( 'ooui-infused-children' );
return infused;
}
if ( value.html !== undefined ) {
return new OO.ui.HtmlSnippet( value.html );
}
}
} );
// allow widgets to reuse parts of the DOM
data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
// rebuild widget
// eslint-disable-next-line new-cap
obj = new cls( data );
// now replace old DOM with this new DOM.
if ( top ) {
// An efficient constructor might be able to reuse the entire DOM tree of the original element,
// so only mutate the DOM if we need to.
if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
$elem.replaceWith( obj.$element );
// This element is now gone from the DOM, but if anyone is holding a reference to it,
// let's allow them to OO.ui.infuse() it and do what they expect (T105828).
// Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
$elem[ 0 ].oouiInfused = obj.$element;
}
top.resolve();
}
obj.$element.data( 'ooui-infused', obj );
obj.$element.data( 'ooui-infused-children', infusedChildren );
// set the 'data-ooui' attribute so we can identify infused widgets
obj.$element.attr( 'data-ooui', '' );
// restore dynamic state after the new element is inserted into DOM
domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
return obj;
};
/**
* Pick out parts of `node`'s DOM to be reused when infusing a widget.
*
* This method **must not** make any changes to the DOM, only find interesting pieces and add them
* to `config` (which should then be returned). Actual DOM juggling should then be done by the
* constructor, which will be given the enhanced config.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
return config;
};
/**
* Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
* (and its children) that represent an Element of the same class and the given configuration,
* generated by the PHP implementation.
*
* This method is called just before `node` is detached from the DOM. The return value of this
* function will be passed to #restorePreInfuseState after the newly created widget's #$element
* is inserted into DOM to replace `node`.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.gatherPreInfuseState = function () {
return {};
};
/**
* Get a jQuery function within a specific document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
* @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
* not in an iframe
* @return {Function} Bound jQuery function
*/
OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
function wrapper( selector ) {
return $( selector, wrapper.context );
}
wrapper.context = this.getDocument( context );
if ( $iframe ) {
wrapper.$iframe = $iframe;
}
return wrapper;
};
/**
* Get the document of an element.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
* @return {HTMLDocument|null} Document object
*/
OO.ui.Element.static.getDocument = function ( obj ) {
// jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
// Empty jQuery selections might have a context
obj.context ||
// HTMLElement
obj.ownerDocument ||
// Window
obj.document ||
// HTMLDocument
( obj.nodeType === 9 && obj ) ||
null;
};
/**
* Get the window of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
* @return {Window} Window object
*/
OO.ui.Element.static.getWindow = function ( obj ) {
var doc = this.getDocument( obj );
return doc.defaultView;
};
/**
* Get the direction of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
* @return {string} Text direction, either 'ltr' or 'rtl'
*/
OO.ui.Element.static.getDir = function ( obj ) {
var isDoc, isWin;
if ( obj instanceof jQuery ) {
obj = obj[ 0 ];
}
isDoc = obj.nodeType === 9;
isWin = obj.document !== undefined;
if ( isDoc || isWin ) {
if ( isWin ) {
obj = obj.document;
}
obj = obj.body;
}
return $( obj ).css( 'direction' );
};
/**
* Get the offset between two frames.
*
* TODO: Make this function not use recursion.
*
* @static
* @param {Window} from Window of the child frame
* @param {Window} [to=window] Window of the parent frame
* @param {Object} [offset] Offset to start with, used internally
* @return {Object} Offset object, containing left and top properties
*/
OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
var i, len, frames, frame, rect;
if ( !to ) {
to = window;
}
if ( !offset ) {
offset = { top: 0, left: 0 };
}
if ( from.parent === from ) {
return offset;
}
// Get iframe element
frames = from.parent.document.getElementsByTagName( 'iframe' );
for ( i = 0, len = frames.length; i < len; i++ ) {
if ( frames[ i ].contentWindow === from ) {
frame = frames[ i ];
break;
}
}
// Recursively accumulate offset values
if ( frame ) {
rect = frame.getBoundingClientRect();
offset.left += rect.left;
offset.top += rect.top;
if ( from !== to ) {
this.getFrameOffset( from.parent, offset );
}
}
return offset;
};
/**
* Get the offset between two elements.
*
* The two elements may be in a different frame, but in that case the frame $element is in must
* be contained in the frame $anchor is in.
*
* @static
* @param {jQuery} $element Element whose position to get
* @param {jQuery} $anchor Element to get $element's position relative to
* @return {Object} Translated position coordinates, containing top and left properties
*/
OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
var iframe, iframePos,
pos = $element.offset(),
anchorPos = $anchor.offset(),
elementDocument = this.getDocument( $element ),
anchorDocument = this.getDocument( $anchor );
// If $element isn't in the same document as $anchor, traverse up
while ( elementDocument !== anchorDocument ) {
iframe = elementDocument.defaultView.frameElement;
if ( !iframe ) {
throw new Error( '$element frame is not contained in $anchor frame' );
}
iframePos = $( iframe ).offset();
pos.left += iframePos.left;
pos.top += iframePos.top;
elementDocument = iframe.ownerDocument;
}
pos.left -= anchorPos.left;
pos.top -= anchorPos.top;
return pos;
};
/**
* Get element border sizes.
*
* @static
* @param {HTMLElement} el Element to measure
* @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
*/
OO.ui.Element.static.getBorders = function ( el ) {
var doc = el.ownerDocument,
win = doc.defaultView,
style = win.getComputedStyle( el, null ),
$el = $( el ),
top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
};
/**
* Get dimensions of an element or window.
*
* @static
* @param {HTMLElement|Window} el Element to measure
* @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
*/
OO.ui.Element.static.getDimensions = function ( el ) {
var $el, $win,
doc = el.ownerDocument || el.document,
win = doc.defaultView;
if ( win === el || el === doc.documentElement ) {
$win = $( win );
return {
borders: { top: 0, left: 0, bottom: 0, right: 0 },
scroll: {
top: $win.scrollTop(),
left: $win.scrollLeft()
},
scrollbar: { right: 0, bottom: 0 },
rect: {
top: 0,
left: 0,
bottom: $win.innerHeight(),
right: $win.innerWidth()
}
};
} else {
$el = $( el );
return {
borders: this.getBorders( el ),
scroll: {
top: $el.scrollTop(),
left: $el.scrollLeft()
},
scrollbar: {
right: $el.innerWidth() - el.clientWidth,
bottom: $el.innerHeight() - el.clientHeight
},
rect: el.getBoundingClientRect()
};
}
};
/**
* Get scrollable object parent
*
* documentElement can't be used to get or set the scrollTop
* property on Blink. Changing and testing its value lets us
* use 'body' or 'documentElement' based on what is working.
*
* https://code.google.com/p/chromium/issues/detail?id=303131
*
* @static
* @param {HTMLElement} el Element to find scrollable parent for
* @return {HTMLElement} Scrollable parent
*/
OO.ui.Element.static.getRootScrollableElement = function ( el ) {
var scrollTop, body;
if ( OO.ui.scrollableElement === undefined ) {
body = el.ownerDocument.body;
scrollTop = body.scrollTop;
body.scrollTop = 1;
if ( body.scrollTop === 1 ) {
body.scrollTop = scrollTop;
OO.ui.scrollableElement = 'body';
} else {
OO.ui.scrollableElement = 'documentElement';
}
}
return el.ownerDocument[ OO.ui.scrollableElement ];
};
/**
* Get closest scrollable container.
*
* Traverses up until either a scrollable element or the root is reached, in which case the window
* will be returned.
*
* @static
* @param {HTMLElement} el Element to find scrollable container for
* @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
var i, val,
// props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
props = [ 'overflow-x', 'overflow-y' ],
$parent = $( el ).parent();
if ( dimension === 'x' || dimension === 'y' ) {
props = [ 'overflow-' + dimension ];
}
while ( $parent.length ) {
if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
return $parent[ 0 ];
}
i = props.length;
while ( i-- ) {
val = $parent.css( props[ i ] );
if ( val === 'auto' || val === 'scroll' ) {
return $parent[ 0 ];
}
}
$parent = $parent.parent();
}
return this.getDocument( el ).body;
};
/**
* Scroll element into view.
*
* @static
* @param {HTMLElement} el Element to scroll into view
* @param {Object} [config] Configuration options
* @param {string} [config.duration='fast'] jQuery animation duration value
* @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
* to scroll in both directions
* @param {Function} [config.complete] Function to call when scrolling completes.
* Deprecated since 0.15.4, use the return promise instead.
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.static.scrollIntoView = function ( el, config ) {
var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window,
deferred = $.Deferred();
// Configuration initialization
config = config || {};
animations = {};
callback = typeof config.complete === 'function' && config.complete;
if ( callback ) {
OO.ui.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
}
container = this.getClosestScrollableContainer( el, config.direction );
$container = $( container );
elementDimensions = this.getDimensions( el );
containerDimensions = this.getDimensions( container );
$window = $( this.getWindow( el ) );
// Compute the element's position relative to the container
if ( $container.is( 'html, body' ) ) {
// If the scrollable container is the root, this is easy
position = {
top: elementDimensions.rect.top,
bottom: $window.innerHeight() - elementDimensions.rect.bottom,
left: elementDimensions.rect.left,
right: $window.innerWidth() - elementDimensions.rect.right
};
} else {
// Otherwise, we have to subtract el's coordinates from container's coordinates
position = {
top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
};
}
if ( !config.direction || config.direction === 'y' ) {
if ( position.top < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + position.top;
} else if ( position.top > 0 && position.bottom < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
}
}
if ( !config.direction || config.direction === 'x' ) {
if ( position.left < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + position.left;
} else if ( position.left > 0 && position.right < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
}
}
if ( !$.isEmptyObject( animations ) ) {
$container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
$container.queue( function ( next ) {
if ( callback ) {
callback();
}
deferred.resolve();
next();
} );
} else {
if ( callback ) {
callback();
}
deferred.resolve();
}
return deferred.promise();
};
/**
* Force the browser to reconsider whether it really needs to render scrollbars inside the element
* and reserve space for them, because it probably doesn't.
*
* Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
* similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
* to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
* and then reattach (or show) them back.
*
* @static
* @param {HTMLElement} el Element to reconsider the scrollbars on
*/
OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
var i, len, scrollLeft, scrollTop, nodes = [];
// Save scroll position
scrollLeft = el.scrollLeft;
scrollTop = el.scrollTop;
// Detach all children
while ( el.firstChild ) {
nodes.push( el.firstChild );
el.removeChild( el.firstChild );
}
// Force reflow
void el.offsetHeight;
// Reattach all children
for ( i = 0, len = nodes.length; i < len; i++ ) {
el.appendChild( nodes[ i ] );
}
// Restore scroll position (no-op if scrollbars disappeared)
el.scrollLeft = scrollLeft;
el.scrollTop = scrollTop;
};
/* Methods */
/**
* Toggle visibility of an element.
*
* @param {boolean} [show] Make element visible, omit to toggle visibility
* @fires visible
* @chainable
*/
OO.ui.Element.prototype.toggle = function ( show ) {
show = show === undefined ? !this.visible : !!show;
if ( show !== this.isVisible() ) {
this.visible = show;
this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
this.emit( 'toggle', show );
}
return this;
};
/**
* Check if element is visible.
*
* @return {boolean} element is visible
*/
OO.ui.Element.prototype.isVisible = function () {
return this.visible;
};
/**
* Get element data.
*
* @return {Mixed} Element data
*/
OO.ui.Element.prototype.getData = function () {
return this.data;
};
/**
* Set element data.
*
* @param {Mixed} data Element data
* @chainable
*/
OO.ui.Element.prototype.setData = function ( data ) {
this.data = data;
return this;
};
/**
* Check if element supports one or more methods.
*
* @param {string|string[]} methods Method or list of methods to check
* @return {boolean} All methods are supported
*/
OO.ui.Element.prototype.supports = function ( methods ) {
var i, len,
support = 0;
methods = Array.isArray( methods ) ? methods : [ methods ];
for ( i = 0, len = methods.length; i < len; i++ ) {
if ( $.isFunction( this[ methods[ i ] ] ) ) {
support++;
}
}
return methods.length === support;
};
/**
* Update the theme-provided classes.
*
* @localdoc This is called in element mixins and widget classes any time state changes.
* Updating is debounced, minimizing overhead of changing multiple attributes and
* guaranteeing that theme updates do not occur within an element's constructor
*/
OO.ui.Element.prototype.updateThemeClasses = function () {
OO.ui.theme.queueUpdateElementClasses( this );
};
/**
* Get the HTML tag name.
*
* Override this method to base the result on instance information.
*
* @return {string} HTML tag name
*/
OO.ui.Element.prototype.getTagName = function () {
return this.constructor.static.tagName;
};
/**
* Check if the element is attached to the DOM
*
* @return {boolean} The element is attached to the DOM
*/
OO.ui.Element.prototype.isElementAttached = function () {
return $.contains( this.getElementDocument(), this.$element[ 0 ] );
};
/**
* Get the DOM document.
*
* @return {HTMLDocument} Document object
*/
OO.ui.Element.prototype.getElementDocument = function () {
// Don't cache this in other ways either because subclasses could can change this.$element
return OO.ui.Element.static.getDocument( this.$element );
};
/**
* Get the DOM window.
*
* @return {Window} Window object
*/
OO.ui.Element.prototype.getElementWindow = function () {
return OO.ui.Element.static.getWindow( this.$element );
};
/**
* Get closest scrollable container.
*
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
};
/**
* Get group element is in.
*
* @return {OO.ui.mixin.GroupElement|null} Group element, null if none
*/
OO.ui.Element.prototype.getElementGroup = function () {
return this.elementGroup;
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
*/
OO.ui.Element.prototype.setElementGroup = function ( group ) {
this.elementGroup = group;
return this;
};
/**
* Scroll element into view.
*
* @param {Object} [config] Configuration options
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
if (
!this.isElementAttached() ||
!this.isVisible() ||
( this.getElementGroup() && !this.getElementGroup().isVisible() )
) {
return $.Deferred().resolve();
}
return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
};
/**
* Restore the pre-infusion dynamic state for this widget.
*
* This method is called after #$element has been inserted into DOM. The parameter is the return
* value of #gatherPreInfuseState.
*
* @protected
* @param {Object} state
*/
OO.ui.Element.prototype.restorePreInfuseState = function () {
};
| src/Element.js | /**
* Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
* that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
* connected to them and can't be interacted with.
*
* @abstract
* @class
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
* to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
* for an example.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
* @cfg {string} [id] The HTML id attribute used in the rendered tag.
* @cfg {string} [text] Text to insert
* @cfg {Array} [content] An array of content elements to append (after #text).
* Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
* Instances of OO.ui.Element will have their $element appended.
* @cfg {jQuery} [$content] Content elements to append (after #text).
* @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
* @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
* Data can also be specified with the #setData method.
*/
OO.ui.Element = function OoUiElement( config ) {
// Configuration initialization
config = config || {};
// Properties
this.$ = $;
this.visible = true;
this.data = config.data;
this.$element = config.$element ||
$( document.createElement( this.getTagName() ) );
this.elementGroup = null;
// Initialization
if ( Array.isArray( config.classes ) ) {
this.$element.addClass( config.classes.join( ' ' ) );
}
if ( config.id ) {
this.$element.attr( 'id', config.id );
}
if ( config.text ) {
this.$element.text( config.text );
}
if ( config.content ) {
// The `content` property treats plain strings as text; use an
// HtmlSnippet to append HTML content. `OO.ui.Element`s get their
// appropriate $element appended.
this.$element.append( config.content.map( function ( v ) {
if ( typeof v === 'string' ) {
// Escape string so it is properly represented in HTML.
return document.createTextNode( v );
} else if ( v instanceof OO.ui.HtmlSnippet ) {
// Bypass escaping.
return v.toString();
} else if ( v instanceof OO.ui.Element ) {
return v.$element;
}
return v;
} ) );
}
if ( config.$content ) {
// The `$content` property treats plain strings as HTML.
this.$element.append( config.$content );
}
};
/* Setup */
OO.initClass( OO.ui.Element );
/* Static Properties */
/**
* The name of the HTML tag used by the element.
*
* The static value may be ignored if the #getTagName method is overridden.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Element.static.tagName = 'div';
/* Static Methods */
/**
* Reconstitute a JavaScript object corresponding to a widget created
* by the PHP implementation.
*
* @param {string|HTMLElement|jQuery} idOrNode
* A DOM id (if a string) or node for the widget to infuse.
* @return {OO.ui.Element}
* The `OO.ui.Element` corresponding to this (infusable) document node.
* For `Tag` objects emitted on the HTML side (used occasionally for content)
* the value returned is a newly-created Element wrapping around the existing
* DOM node.
*/
OO.ui.Element.static.infuse = function ( idOrNode ) {
var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
// Verify that the type matches up.
// FIXME: uncomment after T89721 is fixed (see T90929)
/*
if ( !( obj instanceof this['class'] ) ) {
throw new Error( 'Infusion type mismatch!' );
}
*/
return obj;
};
/**
* Implementation helper for `infuse`; skips the type check and has an
* extra property so that only the top-level invocation touches the DOM.
*
* @private
* @param {string|HTMLElement|jQuery} idOrNode
* @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
* when the top-level widget of this infusion is inserted into DOM,
* replacing the original node; or false for top-level invocation.
* @return {OO.ui.Element}
*/
OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
// look for a cached result of a previous infusion.
var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren;
if ( typeof idOrNode === 'string' ) {
id = idOrNode;
$elem = $( document.getElementById( id ) );
} else {
$elem = $( idOrNode );
id = $elem.attr( 'id' );
}
if ( !$elem.length ) {
throw new Error( 'Widget not found: ' + id );
}
if ( $elem[ 0 ].oouiInfused ) {
$elem = $elem[ 0 ].oouiInfused;
}
data = $elem.data( 'ooui-infused' );
if ( data ) {
// cached!
if ( data === true ) {
throw new Error( 'Circular dependency! ' + id );
}
if ( domPromise ) {
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = data.constructor.static.gatherPreInfuseState( $elem, data );
// restore dynamic state after the new element is re-inserted into DOM under infused parent
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
infusedChildren = $elem.data( 'ooui-infused-children' );
if ( infusedChildren && infusedChildren.length ) {
infusedChildren.forEach( function ( data ) {
var state = data.constructor.static.gatherPreInfuseState( $elem, data );
domPromise.done( data.restorePreInfuseState.bind( data, state ) );
} );
}
}
return data;
}
data = $elem.attr( 'data-ooui' );
if ( !data ) {
throw new Error( 'No infusion data found: ' + id );
}
try {
data = $.parseJSON( data );
} catch ( _ ) {
data = null;
}
if ( !( data && data._ ) ) {
throw new Error( 'No valid infusion data found: ' + id );
}
if ( data._ === 'Tag' ) {
// Special case: this is a raw Tag; wrap existing node, don't rebuild.
return new OO.ui.Element( { $element: $elem } );
}
parts = data._.split( '.' );
cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
if ( cls === undefined ) {
// The PHP output might be old and not including the "OO.ui" prefix
// TODO: Remove this back-compat after next major release
cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
if ( cls === undefined ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
}
// Verify that we're creating an OO.ui.Element instance
parent = cls.parent;
while ( parent !== undefined ) {
if ( parent === OO.ui.Element ) {
// Safe
break;
}
parent = parent.parent;
}
if ( parent !== OO.ui.Element ) {
throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
}
if ( domPromise === false ) {
top = $.Deferred();
domPromise = top.promise();
}
$elem.data( 'ooui-infused', true ); // prevent loops
data.id = id; // implicit
infusedChildren = [];
data = OO.copy( data, null, function deserialize( value ) {
var infused;
if ( OO.isPlainObject( value ) ) {
if ( value.tag ) {
infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
infusedChildren.push( infused );
// Flatten the structure
infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
infused.$element.removeData( 'ooui-infused-children' );
return infused;
}
if ( value.html !== undefined ) {
return new OO.ui.HtmlSnippet( value.html );
}
}
} );
// allow widgets to reuse parts of the DOM
data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
// pick up dynamic state, like focus, value of form inputs, scroll position, etc.
state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
// rebuild widget
// eslint-disable-next-line new-cap
obj = new cls( data );
// now replace old DOM with this new DOM.
if ( top ) {
// An efficient constructor might be able to reuse the entire DOM tree of the original element,
// so only mutate the DOM if we need to.
if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
$elem.replaceWith( obj.$element );
// This element is now gone from the DOM, but if anyone is holding a reference to it,
// let's allow them to OO.ui.infuse() it and do what they expect (T105828).
// Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
$elem[ 0 ].oouiInfused = obj.$element;
}
top.resolve();
}
obj.$element.data( 'ooui-infused', obj );
obj.$element.data( 'ooui-infused-children', infusedChildren );
// set the 'data-ooui' attribute so we can identify infused widgets
obj.$element.attr( 'data-ooui', '' );
// restore dynamic state after the new element is inserted into DOM
domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
return obj;
};
/**
* Pick out parts of `node`'s DOM to be reused when infusing a widget.
*
* This method **must not** make any changes to the DOM, only find interesting pieces and add them
* to `config` (which should then be returned). Actual DOM juggling should then be done by the
* constructor, which will be given the enhanced config.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
return config;
};
/**
* Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
* (and its children) that represent an Element of the same class and the given configuration,
* generated by the PHP implementation.
*
* This method is called just before `node` is detached from the DOM. The return value of this
* function will be passed to #restorePreInfuseState after the newly created widget's #$element
* is inserted into DOM to replace `node`.
*
* @protected
* @param {HTMLElement} node
* @param {Object} config
* @return {Object}
*/
OO.ui.Element.static.gatherPreInfuseState = function () {
return {};
};
/**
* Get a jQuery function within a specific document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
* @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
* not in an iframe
* @return {Function} Bound jQuery function
*/
OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
function wrapper( selector ) {
return $( selector, wrapper.context );
}
wrapper.context = this.getDocument( context );
if ( $iframe ) {
wrapper.$iframe = $iframe;
}
return wrapper;
};
/**
* Get the document of an element.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
* @return {HTMLDocument|null} Document object
*/
OO.ui.Element.static.getDocument = function ( obj ) {
// jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
// Empty jQuery selections might have a context
obj.context ||
// HTMLElement
obj.ownerDocument ||
// Window
obj.document ||
// HTMLDocument
( obj.nodeType === 9 && obj ) ||
null;
};
/**
* Get the window of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
* @return {Window} Window object
*/
OO.ui.Element.static.getWindow = function ( obj ) {
var doc = this.getDocument( obj );
return doc.defaultView;
};
/**
* Get the direction of an element or document.
*
* @static
* @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
* @return {string} Text direction, either 'ltr' or 'rtl'
*/
OO.ui.Element.static.getDir = function ( obj ) {
var isDoc, isWin;
if ( obj instanceof jQuery ) {
obj = obj[ 0 ];
}
isDoc = obj.nodeType === 9;
isWin = obj.document !== undefined;
if ( isDoc || isWin ) {
if ( isWin ) {
obj = obj.document;
}
obj = obj.body;
}
return $( obj ).css( 'direction' );
};
/**
* Get the offset between two frames.
*
* TODO: Make this function not use recursion.
*
* @static
* @param {Window} from Window of the child frame
* @param {Window} [to=window] Window of the parent frame
* @param {Object} [offset] Offset to start with, used internally
* @return {Object} Offset object, containing left and top properties
*/
OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
var i, len, frames, frame, rect;
if ( !to ) {
to = window;
}
if ( !offset ) {
offset = { top: 0, left: 0 };
}
if ( from.parent === from ) {
return offset;
}
// Get iframe element
frames = from.parent.document.getElementsByTagName( 'iframe' );
for ( i = 0, len = frames.length; i < len; i++ ) {
if ( frames[ i ].contentWindow === from ) {
frame = frames[ i ];
break;
}
}
// Recursively accumulate offset values
if ( frame ) {
rect = frame.getBoundingClientRect();
offset.left += rect.left;
offset.top += rect.top;
if ( from !== to ) {
this.getFrameOffset( from.parent, offset );
}
}
return offset;
};
/**
* Get the offset between two elements.
*
* The two elements may be in a different frame, but in that case the frame $element is in must
* be contained in the frame $anchor is in.
*
* @static
* @param {jQuery} $element Element whose position to get
* @param {jQuery} $anchor Element to get $element's position relative to
* @return {Object} Translated position coordinates, containing top and left properties
*/
OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
var iframe, iframePos,
pos = $element.offset(),
anchorPos = $anchor.offset(),
elementDocument = this.getDocument( $element ),
anchorDocument = this.getDocument( $anchor );
// If $element isn't in the same document as $anchor, traverse up
while ( elementDocument !== anchorDocument ) {
iframe = elementDocument.defaultView.frameElement;
if ( !iframe ) {
throw new Error( '$element frame is not contained in $anchor frame' );
}
iframePos = $( iframe ).offset();
pos.left += iframePos.left;
pos.top += iframePos.top;
elementDocument = iframe.ownerDocument;
}
pos.left -= anchorPos.left;
pos.top -= anchorPos.top;
return pos;
};
/**
* Get element border sizes.
*
* @static
* @param {HTMLElement} el Element to measure
* @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
*/
OO.ui.Element.static.getBorders = function ( el ) {
var doc = el.ownerDocument,
win = doc.defaultView,
style = win.getComputedStyle( el, null ),
$el = $( el ),
top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
return {
top: top,
left: left,
bottom: bottom,
right: right
};
};
/**
* Get dimensions of an element or window.
*
* @static
* @param {HTMLElement|Window} el Element to measure
* @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
*/
OO.ui.Element.static.getDimensions = function ( el ) {
var $el, $win,
doc = el.ownerDocument || el.document,
win = doc.defaultView;
if ( win === el || el === doc.documentElement ) {
$win = $( win );
return {
borders: { top: 0, left: 0, bottom: 0, right: 0 },
scroll: {
top: $win.scrollTop(),
left: $win.scrollLeft()
},
scrollbar: { right: 0, bottom: 0 },
rect: {
top: 0,
left: 0,
bottom: $win.innerHeight(),
right: $win.innerWidth()
}
};
} else {
$el = $( el );
return {
borders: this.getBorders( el ),
scroll: {
top: $el.scrollTop(),
left: $el.scrollLeft()
},
scrollbar: {
right: $el.innerWidth() - el.clientWidth,
bottom: $el.innerHeight() - el.clientHeight
},
rect: el.getBoundingClientRect()
};
}
};
/**
* Get scrollable object parent
*
* documentElement can't be used to get or set the scrollTop
* property on Blink. Changing and testing its value lets us
* use 'body' or 'documentElement' based on what is working.
*
* https://code.google.com/p/chromium/issues/detail?id=303131
*
* @static
* @param {HTMLElement} el Element to find scrollable parent for
* @return {HTMLElement} Scrollable parent
*/
OO.ui.Element.static.getRootScrollableElement = function ( el ) {
var scrollTop, body;
if ( OO.ui.scrollableElement === undefined ) {
body = el.ownerDocument.body;
scrollTop = body.scrollTop;
body.scrollTop = 1;
if ( body.scrollTop === 1 ) {
body.scrollTop = scrollTop;
OO.ui.scrollableElement = 'body';
} else {
OO.ui.scrollableElement = 'documentElement';
}
}
return el.ownerDocument[ OO.ui.scrollableElement ];
};
/**
* Get closest scrollable container.
*
* Traverses up until either a scrollable element or the root is reached, in which case the window
* will be returned.
*
* @static
* @param {HTMLElement} el Element to find scrollable container for
* @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
var i, val,
// props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
props = [ 'overflow-x', 'overflow-y' ],
$parent = $( el ).parent();
if ( dimension === 'x' || dimension === 'y' ) {
props = [ 'overflow-' + dimension ];
}
while ( $parent.length ) {
if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
return $parent[ 0 ];
}
i = props.length;
while ( i-- ) {
val = $parent.css( props[ i ] );
if ( val === 'auto' || val === 'scroll' ) {
return $parent[ 0 ];
}
}
$parent = $parent.parent();
}
return this.getDocument( el ).body;
};
/**
* Scroll element into view.
*
* @static
* @param {HTMLElement} el Element to scroll into view
* @param {Object} [config] Configuration options
* @param {string} [config.duration='fast'] jQuery animation duration value
* @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
* to scroll in both directions
* @param {Function} [config.complete] Function to call when scrolling completes.
* Deprecated since 0.15.4, use the return promise instead.
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.static.scrollIntoView = function ( el, config ) {
var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window,
deferred = $.Deferred();
// Configuration initialization
config = config || {};
animations = {};
callback = typeof config.complete === 'function' && config.complete;
container = this.getClosestScrollableContainer( el, config.direction );
$container = $( container );
elementDimensions = this.getDimensions( el );
containerDimensions = this.getDimensions( container );
$window = $( this.getWindow( el ) );
// Compute the element's position relative to the container
if ( $container.is( 'html, body' ) ) {
// If the scrollable container is the root, this is easy
position = {
top: elementDimensions.rect.top,
bottom: $window.innerHeight() - elementDimensions.rect.bottom,
left: elementDimensions.rect.left,
right: $window.innerWidth() - elementDimensions.rect.right
};
} else {
// Otherwise, we have to subtract el's coordinates from container's coordinates
position = {
top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
};
}
if ( !config.direction || config.direction === 'y' ) {
if ( position.top < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + position.top;
} else if ( position.top > 0 && position.bottom < 0 ) {
animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
}
}
if ( !config.direction || config.direction === 'x' ) {
if ( position.left < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + position.left;
} else if ( position.left > 0 && position.right < 0 ) {
animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
}
}
if ( !$.isEmptyObject( animations ) ) {
$container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
$container.queue( function ( next ) {
if ( callback ) {
callback();
}
deferred.resolve();
next();
} );
} else {
if ( callback ) {
callback();
}
deferred.resolve();
}
return deferred.promise();
};
/**
* Force the browser to reconsider whether it really needs to render scrollbars inside the element
* and reserve space for them, because it probably doesn't.
*
* Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
* similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
* to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
* and then reattach (or show) them back.
*
* @static
* @param {HTMLElement} el Element to reconsider the scrollbars on
*/
OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
var i, len, scrollLeft, scrollTop, nodes = [];
// Save scroll position
scrollLeft = el.scrollLeft;
scrollTop = el.scrollTop;
// Detach all children
while ( el.firstChild ) {
nodes.push( el.firstChild );
el.removeChild( el.firstChild );
}
// Force reflow
void el.offsetHeight;
// Reattach all children
for ( i = 0, len = nodes.length; i < len; i++ ) {
el.appendChild( nodes[ i ] );
}
// Restore scroll position (no-op if scrollbars disappeared)
el.scrollLeft = scrollLeft;
el.scrollTop = scrollTop;
};
/* Methods */
/**
* Toggle visibility of an element.
*
* @param {boolean} [show] Make element visible, omit to toggle visibility
* @fires visible
* @chainable
*/
OO.ui.Element.prototype.toggle = function ( show ) {
show = show === undefined ? !this.visible : !!show;
if ( show !== this.isVisible() ) {
this.visible = show;
this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
this.emit( 'toggle', show );
}
return this;
};
/**
* Check if element is visible.
*
* @return {boolean} element is visible
*/
OO.ui.Element.prototype.isVisible = function () {
return this.visible;
};
/**
* Get element data.
*
* @return {Mixed} Element data
*/
OO.ui.Element.prototype.getData = function () {
return this.data;
};
/**
* Set element data.
*
* @param {Mixed} data Element data
* @chainable
*/
OO.ui.Element.prototype.setData = function ( data ) {
this.data = data;
return this;
};
/**
* Check if element supports one or more methods.
*
* @param {string|string[]} methods Method or list of methods to check
* @return {boolean} All methods are supported
*/
OO.ui.Element.prototype.supports = function ( methods ) {
var i, len,
support = 0;
methods = Array.isArray( methods ) ? methods : [ methods ];
for ( i = 0, len = methods.length; i < len; i++ ) {
if ( $.isFunction( this[ methods[ i ] ] ) ) {
support++;
}
}
return methods.length === support;
};
/**
* Update the theme-provided classes.
*
* @localdoc This is called in element mixins and widget classes any time state changes.
* Updating is debounced, minimizing overhead of changing multiple attributes and
* guaranteeing that theme updates do not occur within an element's constructor
*/
OO.ui.Element.prototype.updateThemeClasses = function () {
OO.ui.theme.queueUpdateElementClasses( this );
};
/**
* Get the HTML tag name.
*
* Override this method to base the result on instance information.
*
* @return {string} HTML tag name
*/
OO.ui.Element.prototype.getTagName = function () {
return this.constructor.static.tagName;
};
/**
* Check if the element is attached to the DOM
*
* @return {boolean} The element is attached to the DOM
*/
OO.ui.Element.prototype.isElementAttached = function () {
return $.contains( this.getElementDocument(), this.$element[ 0 ] );
};
/**
* Get the DOM document.
*
* @return {HTMLDocument} Document object
*/
OO.ui.Element.prototype.getElementDocument = function () {
// Don't cache this in other ways either because subclasses could can change this.$element
return OO.ui.Element.static.getDocument( this.$element );
};
/**
* Get the DOM window.
*
* @return {Window} Window object
*/
OO.ui.Element.prototype.getElementWindow = function () {
return OO.ui.Element.static.getWindow( this.$element );
};
/**
* Get closest scrollable container.
*
* @return {HTMLElement} Closest scrollable container
*/
OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
};
/**
* Get group element is in.
*
* @return {OO.ui.mixin.GroupElement|null} Group element, null if none
*/
OO.ui.Element.prototype.getElementGroup = function () {
return this.elementGroup;
};
/**
* Set group element is in.
*
* @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
* @chainable
*/
OO.ui.Element.prototype.setElementGroup = function ( group ) {
this.elementGroup = group;
return this;
};
/**
* Scroll element into view.
*
* @param {Object} [config] Configuration options
* @return {jQuery.Promise} Promise which resolves when the scroll is complete
*/
OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
if (
!this.isElementAttached() ||
!this.isVisible() ||
( this.getElementGroup() && !this.getElementGroup().isVisible() )
) {
return $.Deferred().resolve();
}
return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
};
/**
* Restore the pre-infusion dynamic state for this widget.
*
* This method is called after #$element has been inserted into DOM. The parameter is the return
* value of #gatherPreInfuseState.
*
* @protected
* @param {Object} state
*/
OO.ui.Element.prototype.restorePreInfuseState = function () {
};
| Follow-up 1dc6a45: Emit deprecations from Element#scrollIntoView callback
Change-Id: I21ce2c187064dac8a27548d2b4087d1c49e47834
| src/Element.js | Follow-up 1dc6a45: Emit deprecations from Element#scrollIntoView callback | <ide><path>rc/Element.js
<ide>
<ide> animations = {};
<ide> callback = typeof config.complete === 'function' && config.complete;
<add> if ( callback ) {
<add> OO.ui.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
<add> }
<ide> container = this.getClosestScrollableContainer( el, config.direction );
<ide> $container = $( container );
<ide> elementDimensions = this.getDimensions( el ); |
|
Java | apache-2.0 | eb640be678c71d8aa4da94f2384845d34bc1d2e7 | 0 | junlapong/proguard-maven-plugin,joeljons/proguard-maven-plugin,junlapong/proguard-maven-plugin,wvengen/proguard-maven-plugin,joeljons/proguard-maven-plugin,wvengen/proguard-maven-plugin | /**
* Pyx4me framework
* Copyright (C) 2006-2007 pyx4.com.
*
* @author vlads
* @version $Id$
*/
package com.pyx4me.maven.proguard;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.codehaus.plexus.archiver.jar.JarArchiver;
/**
*
* <p>
* The Obfuscate task provides a stand-alone obfuscation task
* </p>
*
* @goal proguard
* @phase package
* @description Create small jar files using ProGuard
* @requiresDependencyResolution compile
*/
public class ProGuardMojo extends AbstractMojo {
/**
* Recursively reads configuration options from the given file filename
*
* @parameter default-value="${basedir}/proguard.conf"
*/
private File proguardInclude;
/**
* ProGuard configuration options
*
* @parameter
*/
private String[] options;
/**
* Specifies not to obfuscate the input class files.
*
* @parameter default-value="true"
*/
private boolean obfuscate;
/**
* Specifies that project compile dependencies be added as -libraryjars to
* proguard arguments. Dependency itself is not included in resulting jar
*
* @parameter default-value="true"
*/
private boolean includeDependency;
/**
* Bundle project dependency to resulting jar. Specifies list of artifact
* inclusions
*
* @parameter
*/
private Assembly assembly;
/**
* Additional -libraryjars e.g. ${java.home}/lib/rt.jar Project compile
* dependency are added automaticaly. See exclusions
*
* @parameter
*/
private List libs;
/**
* List of dependency exclusions
*
* @parameter
*/
private List exclusions;
/**
* Specifies the input jar name (or wars, ears, zips) of the application to
* be processed.
*
* @parameter expression="${project.build.finalName}.jar"
* @required
*/
protected String injar;
/**
* Apply ProGuard classpathentry Filters to input jar. e.g.
* <code>!**.gif,!**/tests/**'</code>
*
* @parameter
*/
protected String inFilter;
/**
* Specifies the names of the output jars. If attach=true the value ignored
* and name constructed base on classifier If empty input jar would be
* overdriven.
*
* @parameter
*/
protected String outjar;
/**
* Specifies whether or not to attach the created artifact to the project
*
* @parameter default-value="false"
*/
private boolean attach = false;
/**
* Specifies attach artifact type
*
* @parameter default-value="jar"
*/
private String attachArtifactType;
/**
* Specifies attach artifact Classifier, Ignored if attach=false
*
* @parameter default-value="small"
*/
private String attachArtifactClassifier;
/**
* Set to false to exclude the attachArtifactClassifier from the Artifact
* final name. Default value is true.
*
* @parameter default-value="true"
*/
private boolean appendClassifier;
/**
* Set to true to include META-INF/maven/** maven descriptord
*
* @parameter default-value="false"
*/
private boolean addMavenDescriptor;
/**
* Directory containing the input and generated JAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
protected File outputDirectory;
/**
* The Maven project reference where the plugin is currently being executed.
* The default value is populated from maven.
*
* @parameter expression="${project}"
* @readonly
* @required
*/
protected MavenProject mavenProject;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List pluginArtifacts;
/**
* @component
*/
private MavenProjectHelper projectHelper;
/**
* The Jar archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#jar}"
* @required
*/
private JarArchiver jarArchiver;
/**
* The maven archive configuration to use. only if assembly is used.
*
* @parameter
*/
protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
/**
* The max memory the forked java process should use, e.g. 256m
*
* @parameter
*/
protected String maxMemory;
private Log log;
static final String proguardMainClass = "proguard.ProGuard";
/**
* ProGuard docs: Names with special characters like spaces and parentheses
* must be quoted with single or double quotes.
*/
private static String fileNameToString(String fileName) {
return "'" + fileName + "'";
}
private static String fileToString(File file) {
return fileNameToString(file.toString());
}
private boolean useArtifactClassifier() {
return appendClassifier && ((attachArtifactClassifier != null) && (attachArtifactClassifier.length() > 0));
}
public void execute() throws MojoExecutionException, MojoFailureException {
log = getLog();
boolean mainIsJar = mavenProject.getPackaging().equals("jar");
boolean mainIsPom = mavenProject.getPackaging().equals("pom");
File inJarFile = new File(outputDirectory, injar);
if (mainIsJar && (!inJarFile.exists())) {
throw new MojoFailureException("Can't find file " + inJarFile);
}
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
throw new MojoFailureException("Can't create " + outputDirectory);
}
}
File outJarFile;
boolean sameArtifact;
if (attach) {
outjar = nameNoType(injar);
if (useArtifactClassifier()) {
outjar += "-" + attachArtifactClassifier;
}
outjar += "." + attachArtifactType;
}
if ((outjar != null) && (!outjar.equals(injar))) {
sameArtifact = false;
outJarFile = (new File(outputDirectory, outjar)).getAbsoluteFile();
} else {
sameArtifact = true;
outJarFile = inJarFile.getAbsoluteFile();
File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_base.jar");
if (baseFile.exists()) {
if (!baseFile.delete()) {
throw new MojoFailureException("Can't delete " + baseFile);
}
}
if (inJarFile.exists()) {
if (!inJarFile.renameTo(baseFile)) {
throw new MojoFailureException("Can't rename " + inJarFile);
}
}
inJarFile = baseFile;
}
ArrayList args = new ArrayList();
if (log.isDebugEnabled()) {
List dependancy = mavenProject.getCompileArtifacts();
for (Iterator i = dependancy.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- compile artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getArtifacts().iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getDependencies().iterator(); i.hasNext();) {
Dependency artifact = (Dependency) i.next();
log.debug("--- dependency " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
}
Set inPath = new HashSet();
boolean hasInclusionLibrary = false;
if (assembly != null) {
for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
Inclusion inc = (Inclusion) iter.next();
if (!inc.library) {
File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
inPath.add(file.toString());
log.debug("--- ADD injars:" + inc.artifactId);
StringBuffer filter = new StringBuffer(fileToString(file));
filter.append("(!META-INF/MANIFEST.MF");
if (!addMavenDescriptor) {
filter.append(",");
filter.append("!META-INF/maven/**");
}
if (inc.filter != null) {
filter.append(",").append(inc.filter);
}
filter.append(")");
args.add("-injars");
args.add(filter.toString());
} else {
hasInclusionLibrary = true;
log.debug("--- ADD libraryjars:" + inc.artifactId);
// This may not be CompileArtifacts, maven 2.0.6 bug
File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
inPath.add(file.toString());
args.add("-libraryjars");
args.add(fileToString(file));
}
}
}
if ((!mainIsPom) && inJarFile.exists()) {
args.add("-injars");
StringBuffer filter = new StringBuffer(fileToString(inJarFile));
if ((inFilter != null) || (!addMavenDescriptor)) {
filter.append("(");
boolean coma = false;
if (!addMavenDescriptor) {
coma = true;
filter.append("!META-INF/maven/**");
}
if (inFilter != null) {
if (coma) {
filter.append(",");
}
filter.append(inFilter);
}
filter.append(")");
}
args.add(filter.toString());
}
args.add("-outjars");
args.add(fileToString(outJarFile));
if (!obfuscate) {
args.add("-dontobfuscate");
}
if (proguardInclude != null) {
if (proguardInclude.exists()) {
args.add("-include");
args.add(fileToString(proguardInclude));
log.debug("proguardInclude " + proguardInclude);
} else {
log.debug("proguardInclude config does not exists " + proguardInclude);
}
}
if (includeDependency) {
List dependency = this.mavenProject.getCompileArtifacts();
for (Iterator i = dependency.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
// dependency filter
if (isExclusion(artifact)) {
continue;
}
File file = getClasspathElement(artifact, mavenProject);
if (inPath.contains(file.toString())) {
log.debug("--- ignore libraryjars since one in injar:" + artifact.getArtifactId());
continue;
}
log.debug("--- ADD libraryjars:" + artifact.getArtifactId());
args.add("-libraryjars");
args.add(fileToString(file));
}
}
if (libs != null) {
for (Iterator i = libs.iterator(); i.hasNext();) {
Object lib = i.next();
args.add("-libraryjars");
args.add(fileNameToString(lib.toString()));
}
}
args.add("-printmapping");
args.add(fileToString((new File(outputDirectory, "proguard_map.txt").getAbsoluteFile())));
args.add("-printseeds");
args.add(fileToString((new File(outputDirectory, "proguard_seeds.txt").getAbsoluteFile())));
if (log.isDebugEnabled()) {
args.add("-verbose");
}
if (options != null) {
for (int i = 0; i < options.length; i++) {
args.add(options[i]);
}
}
log.info("execute ProGuard " + args.toString());
proguardMain(getProguardJar(this), args, this);
if ((assembly != null) && (hasInclusionLibrary)) {
log.info("creating assembly");
File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_result.jar");
if (baseFile.exists()) {
if (!baseFile.delete()) {
throw new MojoFailureException("Can't delete " + baseFile);
}
}
File archiverFile = outJarFile.getAbsoluteFile();
if (!outJarFile.renameTo(baseFile)) {
throw new MojoFailureException("Can't rename " + outJarFile);
}
MavenArchiver archiver = new MavenArchiver();
archiver.setArchiver(jarArchiver);
archiver.setOutputFile(archiverFile);
archive.setAddMavenDescriptor(addMavenDescriptor);
try {
jarArchiver.addArchivedFileSet(baseFile);
for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
Inclusion inc = (Inclusion) iter.next();
if (inc.library) {
File file;
Artifact artifact = getDependancy(inc, mavenProject);
file = getClasspathElement(artifact, mavenProject);
if (file.isDirectory()) {
getLog().info("merge project: " + artifact.getArtifactId() + " " + file);
jarArchiver.addDirectory(file);
} else {
getLog().info("merge artifact: " + artifact.getArtifactId());
jarArchiver.addArchivedFileSet(file);
}
}
}
archiver.createArchive(mavenProject, archive);
} catch (Exception e) {
throw new MojoExecutionException("Unable to create jar", e);
}
}
if (attach && !sameArtifact) {
if (useArtifactClassifier()) {
projectHelper.attachArtifact(mavenProject, attachArtifactType, attachArtifactClassifier, outJarFile);
} else {
projectHelper.attachArtifact(mavenProject, attachArtifactType, null, outJarFile);
}
}
}
static boolean isVersionGrate(Artifact artifact1, Artifact artifact2) {
if ((artifact2 == null) || (artifact2.getVersion() == null)) {
return true;
}
if ((artifact1 == null) || (artifact1.getVersion() == null)) {
return false;
}
// Just very simple
return (artifact1.getVersion().compareTo(artifact2.getVersion()) > 0);
}
private static File getProguardJar(ProGuardMojo mojo) throws MojoExecutionException {
Artifact proguardArtifact = null;
int proguardArtifactDistance = -1;
// This should be solved in Maven 2.1
for (Iterator i = mojo.pluginArtifacts.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
if ("proguard".equals(artifact.getArtifactId())) {
int distance = artifact.getDependencyTrail().size();
mojo.getLog().debug("proguard DependencyTrail: " + distance);
if (proguardArtifactDistance == -1) {
proguardArtifact = artifact;
} else if (distance < proguardArtifactDistance) {
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
// if (isVersionGrate(artifact, proguardArtifact)) {
// proguardArtifact = artifact;
// break;
// }
}
}
if (proguardArtifact != null) {
mojo.getLog().debug("proguardArtifact: " + proguardArtifact.getFile());
return proguardArtifact.getFile().getAbsoluteFile();
}
mojo.getLog().info("proguard jar not found in pluginArtifacts");
ClassLoader cl;
cl = mojo.getClass().getClassLoader();
// cl = Thread.currentThread().getContextClassLoader();
String classResource = "/" + proguardMainClass.replace('.', '/') + ".class";
URL url = cl.getResource(classResource);
if (url == null) {
throw new MojoExecutionException("Obfuscation failed ProGuard (" + proguardMainClass
+ ") not found in classpath");
}
String proguardJar = url.toExternalForm();
if (proguardJar.startsWith("jar:file:")) {
proguardJar = proguardJar.substring("jar:file:".length());
proguardJar = proguardJar.substring(0, proguardJar.indexOf('!'));
} else {
throw new MojoExecutionException("Unrecognized location (" + proguardJar + ") in classpath");
}
return new File(proguardJar);
}
private static void proguardMain(File proguardJar, ArrayList argsList, ProGuardMojo mojo)
throws MojoExecutionException {
Java java = new Java();
Project antProject = new Project();
antProject.setName(mojo.mavenProject.getName());
antProject.init();
DefaultLogger antLogger = new DefaultLogger();
antLogger.setOutputPrintStream(System.out);
antLogger.setErrorPrintStream(System.err);
antLogger.setMessageOutputLevel(mojo.log.isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO);
antProject.addBuildListener(antLogger);
antProject.setBaseDir(mojo.mavenProject.getBasedir());
java.setProject(antProject);
java.setTaskName("proguard");
mojo.getLog().info("proguard jar: " + proguardJar);
java.createClasspath().setLocation(proguardJar);
// java.createClasspath().setPath(System.getProperty("java.class.path"));
java.setClassname(proguardMainClass);
java.setFailonerror(true);
java.setFork(true);
// get the maxMemory setting
if (mojo.maxMemory != null) {
java.setMaxmemory(mojo.maxMemory);
}
for (Iterator i = argsList.iterator(); i.hasNext();) {
java.createArg().setValue(i.next().toString());
}
int result = java.executeJava();
if (result != 0) {
throw new MojoExecutionException("Obfuscation failed (result=" + result + ")");
}
}
private static String nameNoType(String artifactname) {
return artifactname.substring(0, artifactname.lastIndexOf('.'));
}
private static Artifact getDependancy(Inclusion inc, MavenProject mavenProject) throws MojoExecutionException {
Set dependancy = mavenProject.getArtifacts();
for (Iterator i = dependancy.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
if (inc.match(artifact)) {
return artifact;
}
}
throw new MojoExecutionException("artifactId Not found " + inc.artifactId);
}
private boolean isExclusion(Artifact artifact) {
if (exclusions == null) {
return false;
}
for (Iterator iter = exclusions.iterator(); iter.hasNext();) {
Exclusion excl = (Exclusion) iter.next();
if (excl.match(artifact)) {
return true;
}
}
return false;
}
private static File getClasspathElement(Artifact artifact, MavenProject mavenProject) throws MojoExecutionException {
if (artifact.getClassifier() != null) {
return artifact.getFile();
}
String refId = artifact.getGroupId() + ":" + artifact.getArtifactId();
MavenProject project = (MavenProject) mavenProject.getProjectReferences().get(refId);
if (project != null) {
return new File(project.getBuild().getOutputDirectory());
} else {
File file = artifact.getFile();
if ((file == null) || (!file.exists())) {
throw new MojoExecutionException("Dependency Resolution Required " + artifact);
}
return file;
}
}
}
| src/main/java/com/pyx4me/maven/proguard/ProGuardMojo.java | /**
* Pyx4me framework
* Copyright (C) 2006-2007 pyx4.com.
*
* @author vlads
* @version $Id$
*/
package com.pyx4me.maven.proguard;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.codehaus.plexus.archiver.jar.JarArchiver;
/**
*
* <p>
* The Obfuscate task provides a stand-alone obfuscation task
* </p>
*
* @goal proguard
* @phase package
* @description Create small jar files using ProGuard
* @requiresDependencyResolution compile
*/
public class ProGuardMojo extends AbstractMojo {
/**
* Recursively reads configuration options from the given file filename
*
* @parameter default-value="${basedir}/proguard.conf"
*/
private File proguardInclude;
/**
* ProGuard configuration options
*
* @parameter
*/
private String[] options;
/**
* Specifies not to obfuscate the input class files.
*
* @parameter default-value="true"
*/
private boolean obfuscate;
/**
* Specifies that project compile dependencies be added as -libraryjars to
* proguard arguments. Dependency itself is not included in resulting jar
*
* @parameter default-value="true"
*/
private boolean includeDependency;
/**
* Bundle project dependency to resulting jar. Specifies list of artifact
* inclusions
*
* @parameter
*/
private Assembly assembly;
/**
* Additional -libraryjars e.g. ${java.home}/lib/rt.jar Project compile
* dependency are added automaticaly. See exclusions
*
* @parameter
*/
private List libs;
/**
* List of dependency exclusions
*
* @parameter
*/
private List exclusions;
/**
* Specifies the input jar name (or wars, ears, zips) of the application to
* be processed.
*
* @parameter expression="${project.build.finalName}.jar"
* @required
*/
protected String injar;
/**
* Apply ProGuard classpathentry Filters to input jar. e.g.
* <code>!**.gif,!**/tests/**'</code>
*
* @parameter
*/
protected String inFilter;
/**
* Specifies the names of the output jars. If attach=true the value ignored
* and name constructed base on classifier If empty input jar would be
* overdriven.
*
* @parameter
*/
protected String outjar;
/**
* Specifies whether or not to attach the created artifact to the project
*
* @parameter default-value="false"
*/
private boolean attach = false;
/**
* Specifies attach artifact type
*
* @parameter default-value="jar"
*/
private String attachArtifactType;
/**
* Specifies attach artifact Classifier, Ignored if attach=false
*
* @parameter default-value="small"
*/
private String attachArtifactClassifier;
/**
* Set to false to exclude the attachArtifactClassifier from the Artifact
* final name. Default value is true.
*
* @parameter default-value="true"
*/
private boolean appendClassifier;
/**
* Set to true to include META-INF/maven/** maven descriptord
*
* @parameter default-value="false"
*/
private boolean addMavenDescriptor;
/**
* Directory containing the input and generated JAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
protected File outputDirectory;
/**
* The Maven project reference where the plugin is currently being executed.
* The default value is populated from maven.
*
* @parameter expression="${project}"
* @readonly
* @required
*/
protected MavenProject mavenProject;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List pluginArtifacts;
/**
* @component
*/
private MavenProjectHelper projectHelper;
/**
* The Jar archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#jar}"
* @required
*/
private JarArchiver jarArchiver;
/**
* The maven archive configuration to use. only if assembly is used.
*
* @parameter
*/
protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
/**
* The max memory the forked java process should use, e.g. 256m
*
* @parameter
*/
protected String maxMemory;
private Log log;
static final String proguardMainClass = "proguard.ProGuard";
/**
* ProGuard docs: Names with special characters like spaces and parentheses
* must be quoted with single or double quotes.
*/
private static String fileNameToString(String fileName) {
return "'" + fileName + "'";
}
private static String fileToString(File file) {
return fileNameToString(file.toString());
}
private boolean useArtifactClassifier() {
return appendClassifier && ((attachArtifactClassifier != null) && (attachArtifactClassifier.length() > 0));
}
public void execute() throws MojoExecutionException, MojoFailureException {
log = getLog();
boolean mainIsJar = mavenProject.getPackaging().equals("jar");
boolean mainIsPom = mavenProject.getPackaging().equals("pom");
File inJarFile = new File(outputDirectory, injar);
if (mainIsJar && (!inJarFile.exists())) {
throw new MojoFailureException("Can't find file " + inJarFile);
}
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
throw new MojoFailureException("Can't create " + outputDirectory);
}
}
File outJarFile;
boolean sameArtifact;
if (attach) {
outjar = nameNoType(injar);
if (useArtifactClassifier()) {
outjar += "-" + attachArtifactClassifier;
}
outjar += "." + attachArtifactType;
}
if ((outjar != null) && (!outjar.equals(injar))) {
sameArtifact = false;
outJarFile = (new File(outputDirectory, outjar)).getAbsoluteFile();
} else {
sameArtifact = true;
outJarFile = inJarFile.getAbsoluteFile();
File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_base.jar");
if (baseFile.exists()) {
if (!baseFile.delete()) {
throw new MojoFailureException("Can't delete " + baseFile);
}
}
if (inJarFile.exists()) {
if (!inJarFile.renameTo(baseFile)) {
throw new MojoFailureException("Can't rename " + inJarFile);
}
}
inJarFile = baseFile;
}
ArrayList args = new ArrayList();
if (log.isDebugEnabled()) {
List dependancy = mavenProject.getCompileArtifacts();
for (Iterator i = dependancy.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- compile artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getArtifacts().iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
log.debug("--- artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
for (Iterator i = mavenProject.getDependencies().iterator(); i.hasNext();) {
Dependency artifact = (Dependency) i.next();
log.debug("--- dependency " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getType() + ":" + artifact.getClassifier() + " Scope:" + artifact.getScope());
}
}
Set inPath = new HashSet();
boolean hasInclusionLibrary = false;
if (assembly != null) {
for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
Inclusion inc = (Inclusion) iter.next();
if (!inc.library) {
File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
inPath.add(file.toString());
log.debug("--- ADD injars:" + inc.artifactId);
StringBuffer filter = new StringBuffer(fileToString(file));
filter.append("(!META-INF/MANIFEST.MF");
if (!addMavenDescriptor) {
filter.append(",");
filter.append("!META-INF/maven/**");
}
if (inc.filter != null) {
filter.append(",").append(inc.filter);
}
filter.append(")");
args.add("-injars");
args.add(filter.toString());
} else {
hasInclusionLibrary = true;
log.debug("--- ADD libraryjars:" + inc.artifactId);
// This may not be CompileArtifacts, maven 2.0.6 bug
File file = getClasspathElement(getDependancy(inc, mavenProject), mavenProject);
inPath.add(file.toString());
args.add("-libraryjars");
args.add(fileToString(file));
}
}
}
if ((!mainIsPom) && inJarFile.exists()) {
args.add("-injars");
StringBuffer filter = new StringBuffer(fileToString(inJarFile));
if ((inFilter != null) || (!addMavenDescriptor)) {
filter.append("(");
boolean coma = false;
if (!addMavenDescriptor) {
coma = true;
filter.append("!META-INF/maven/**");
}
if (inFilter != null) {
if (coma) {
filter.append(",");
}
filter.append(inFilter);
}
filter.append(")");
}
args.add(filter.toString());
}
args.add("-outjars");
args.add(fileToString(outJarFile));
if (!obfuscate) {
args.add("-dontobfuscate");
}
if (proguardInclude != null) {
if (proguardInclude.exists()) {
args.add("-include");
args.add(fileToString(proguardInclude));
log.debug("proguardInclude " + proguardInclude);
} else {
log.debug("proguardInclude config does not exists " + proguardInclude);
}
}
if (includeDependency) {
List dependency = this.mavenProject.getCompileArtifacts();
for (Iterator i = dependency.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
// dependency filter
if (isExclusion(artifact)) {
continue;
}
File file = getClasspathElement(artifact, mavenProject);
if (inPath.contains(file.toString())) {
log.debug("--- ignore libraryjars since one in injar:" + artifact.getArtifactId());
continue;
}
log.debug("--- ADD libraryjars:" + artifact.getArtifactId());
args.add("-libraryjars");
args.add(fileToString(file));
}
}
if (libs != null) {
for (Iterator i = libs.iterator(); i.hasNext();) {
Object lib = i.next();
args.add("-libraryjars");
args.add(fileNameToString(lib.toString()));
}
}
args.add("-printmapping");
args.add(fileToString((new File(outputDirectory, "proguard_map.txt").getAbsoluteFile())));
args.add("-printseeds");
args.add(fileToString((new File(outputDirectory, "proguard_seeds.txt").getAbsoluteFile())));
if (log.isDebugEnabled()) {
args.add("-verbose");
}
if (options != null) {
for (int i = 0; i < options.length; i++) {
args.add(options[i]);
}
}
log.info("execute ProGuard " + args.toString());
proguardMain(getProguardJar(this), args, this);
if ((assembly != null) && (hasInclusionLibrary)) {
log.info("creating assembly");
File baseFile = new File(outputDirectory, nameNoType(injar) + "_proguard_result.jar");
if (baseFile.exists()) {
if (!baseFile.delete()) {
throw new MojoFailureException("Can't delete " + baseFile);
}
}
File archiverFile = outJarFile.getAbsoluteFile();
if (!outJarFile.renameTo(baseFile)) {
throw new MojoFailureException("Can't rename " + outJarFile);
}
MavenArchiver archiver = new MavenArchiver();
archiver.setArchiver(jarArchiver);
archiver.setOutputFile(archiverFile);
archive.setAddMavenDescriptor(addMavenDescriptor);
try {
jarArchiver.addArchivedFileSet(baseFile);
for (Iterator iter = assembly.inclusions.iterator(); iter.hasNext();) {
Inclusion inc = (Inclusion) iter.next();
if (inc.library) {
File file;
Artifact artifact = getDependancy(inc, mavenProject);
file = getClasspathElement(artifact, mavenProject);
if (file.isDirectory()) {
getLog().info("merge project: " + artifact.getArtifactId() + " " + file);
jarArchiver.addDirectory(file);
} else {
getLog().info("merge artifact: " + artifact.getArtifactId());
jarArchiver.addArchivedFileSet(file);
}
}
}
archiver.createArchive(mavenProject, archive);
} catch (Exception e) {
throw new MojoExecutionException("Unable to create jar", e);
}
}
if (attach && !sameArtifact) {
if (useArtifactClassifier()) {
projectHelper.attachArtifact(mavenProject, attachArtifactType, attachArtifactClassifier, outJarFile);
} else {
projectHelper.attachArtifact(mavenProject, attachArtifactType, null, outJarFile);
}
}
}
static boolean isVersionGrate(Artifact artifact1, Artifact artifact2) {
if ((artifact2 == null) || (artifact2.getVersion() == null)) {
return true;
}
if ((artifact1 == null) || (artifact1.getVersion() == null)) {
return false;
}
// Just very simple
return (artifact1.getVersion().compareTo(artifact2.getVersion()) > 0);
}
private static File getProguardJar(ProGuardMojo mojo) throws MojoExecutionException {
Artifact proguardArtifact = null;
// This should be solved in Maven 2.1
for (Iterator i = mojo.pluginArtifacts.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
if ("proguard".equals(artifact.getArtifactId())) {
if (isVersionGrate(artifact, proguardArtifact)) {
proguardArtifact = artifact;
}
}
mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
}
if (proguardArtifact != null) {
mojo.getLog().debug("proguardArtifact: " + proguardArtifact.getFile());
return proguardArtifact.getFile().getAbsoluteFile();
}
mojo.getLog().info("proguard jar not found in pluginArtifacts");
ClassLoader cl;
cl = mojo.getClass().getClassLoader();
// cl = Thread.currentThread().getContextClassLoader();
String classResource = "/" + proguardMainClass.replace('.', '/') + ".class";
URL url = cl.getResource(classResource);
if (url == null) {
throw new MojoExecutionException("Obfuscation failed ProGuard (" + proguardMainClass
+ ") not found in classpath");
}
String proguardJar = url.toExternalForm();
if (proguardJar.startsWith("jar:file:")) {
proguardJar = proguardJar.substring("jar:file:".length());
proguardJar = proguardJar.substring(0, proguardJar.indexOf('!'));
} else {
throw new MojoExecutionException("Unrecognized location (" + proguardJar + ") in classpath");
}
return new File(proguardJar);
}
private static void proguardMain(File proguardJar, ArrayList argsList, ProGuardMojo mojo)
throws MojoExecutionException {
Java java = new Java();
Project antProject = new Project();
antProject.setName(mojo.mavenProject.getName());
antProject.init();
DefaultLogger antLogger = new DefaultLogger();
antLogger.setOutputPrintStream(System.out);
antLogger.setErrorPrintStream(System.err);
antLogger.setMessageOutputLevel(mojo.log.isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO);
antProject.addBuildListener(antLogger);
antProject.setBaseDir(mojo.mavenProject.getBasedir());
java.setProject(antProject);
java.setTaskName("proguard");
mojo.getLog().info("proguard jar: " + proguardJar);
java.createClasspath().setLocation(proguardJar);
// java.createClasspath().setPath(System.getProperty("java.class.path"));
java.setClassname(proguardMainClass);
java.setFailonerror(true);
java.setFork(true);
// get the maxMemory setting
if (mojo.maxMemory != null) {
java.setMaxmemory(mojo.maxMemory);
}
for (Iterator i = argsList.iterator(); i.hasNext();) {
java.createArg().setValue(i.next().toString());
}
int result = java.executeJava();
if (result != 0) {
throw new MojoExecutionException("Obfuscation failed (result=" + result + ")");
}
}
private static String nameNoType(String artifactname) {
return artifactname.substring(0, artifactname.lastIndexOf('.'));
}
private static Artifact getDependancy(Inclusion inc, MavenProject mavenProject) throws MojoExecutionException {
Set dependancy = mavenProject.getArtifacts();
for (Iterator i = dependancy.iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
if (inc.match(artifact)) {
return artifact;
}
}
throw new MojoExecutionException("artifactId Not found " + inc.artifactId);
}
private boolean isExclusion(Artifact artifact) {
if (exclusions == null) {
return false;
}
for (Iterator iter = exclusions.iterator(); iter.hasNext();) {
Exclusion excl = (Exclusion) iter.next();
if (excl.match(artifact)) {
return true;
}
}
return false;
}
private static File getClasspathElement(Artifact artifact, MavenProject mavenProject) throws MojoExecutionException {
if (artifact.getClassifier() != null) {
return artifact.getFile();
}
String refId = artifact.getGroupId() + ":" + artifact.getArtifactId();
MavenProject project = (MavenProject) mavenProject.getProjectReferences().get(refId);
if (project != null) {
return new File(project.getBuild().getOutputDirectory());
} else {
File file = artifact.getFile();
if ((file == null) || (!file.exists())) {
throw new MojoExecutionException("Dependency Resolution Required " + artifact);
}
return file;
}
}
}
| Use different version of proguard
git-svn-id: 1387d01a548a1d97a58480e53f0534bc9b70bf05@1530 64363475-2d43-4506-900a-d995b6e1408b
| src/main/java/com/pyx4me/maven/proguard/ProGuardMojo.java | Use different version of proguard | <ide><path>rc/main/java/com/pyx4me/maven/proguard/ProGuardMojo.java
<ide> private static File getProguardJar(ProGuardMojo mojo) throws MojoExecutionException {
<ide>
<ide> Artifact proguardArtifact = null;
<add> int proguardArtifactDistance = -1;
<ide> // This should be solved in Maven 2.1
<ide> for (Iterator i = mojo.pluginArtifacts.iterator(); i.hasNext();) {
<ide> Artifact artifact = (Artifact) i.next();
<add> mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
<ide> if ("proguard".equals(artifact.getArtifactId())) {
<del> if (isVersionGrate(artifact, proguardArtifact)) {
<add> int distance = artifact.getDependencyTrail().size();
<add> mojo.getLog().debug("proguard DependencyTrail: " + distance);
<add> if (proguardArtifactDistance == -1) {
<ide> proguardArtifact = artifact;
<del> }
<del> }
<del> mojo.getLog().debug("pluginArtifact: " + artifact.getFile());
<add> } else if (distance < proguardArtifactDistance) {
<add> proguardArtifact = artifact;
<add> proguardArtifactDistance = distance;
<add> }
<add> // if (isVersionGrate(artifact, proguardArtifact)) {
<add> // proguardArtifact = artifact;
<add> // break;
<add> // }
<add> }
<ide> }
<ide> if (proguardArtifact != null) {
<ide> mojo.getLog().debug("proguardArtifact: " + proguardArtifact.getFile()); |
|
Java | apache-2.0 | e6a196d51cc2c3e3081242e38cf91bce5120d5af | 0 | AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.webkit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Base64;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.MediumTest;
import androidx.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
import java.util.Map;
@MediumTest
@RunWith(AndroidJUnit4.class)
public class WebSettingsCompatForceDarkTest {
private final String mNoDarkThemeSupport = Base64.encodeToString((
"<html>\n"
+ " <head>"
+ " </head>"
+ " <body>"
+ " </body>"
+ "</html>").getBytes(), Base64.NO_PADDING);
private final String mDarkThemeSupport = Base64.encodeToString((
"<html>"
+ " <head>"
+ " <meta name=\"color-scheme\" content=\"light dark\">"
+ " <style>"
+ " @media (prefers-color-scheme: dark) {"
+ " body {background-color: green; }"
+ " </style>"
+ " </head>"
+ " <body>"
+ " </body>"
+ "</html>"
).getBytes(), Base64.NO_PADDING);
// LayoutParams are null until WebView has a parent Activity.
// Test testForceDark_rendersDark requires LayoutParams to define
// width and height of WebView to capture its bitmap representation.
@Rule
public final ActivityTestRule<WebViewTestActivity> mActivityRule =
new ActivityTestRule<>(WebViewTestActivity.class);
private WebViewOnUiThread mWebViewOnUiThread;
@Before
public void setUp() {
mWebViewOnUiThread = new WebViewOnUiThread(mActivityRule.getActivity().getWebView());
}
@After
public void tearDown() {
if (mWebViewOnUiThread != null) {
mWebViewOnUiThread.cleanUp();
}
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_default. Modifications to this test should
* be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
public void testForceDark_default() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
assertEquals("The default force dark state should be AUTO",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_AUTO);
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_rendersDark. Modifications to this test
* should be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
public void testForceDark_rendersDark() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
setWebViewSize(64, 64);
// Loading about:blank into a force-dark-on webview should result in a dark background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
assertEquals("Force dark should have been set to ON",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_ON);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
// Loading about:blank into a force-dark-off webview should result in a light background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
assertEquals("Force dark should have been set to OFF",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_OFF);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be light",
Color.luminance(getWebPageColor()) > 0.5f);
}
/**
* Test to exercise USER_AGENT_DARKENING_ONLY option,
* i.e. web contents are always darkened by a user agent.
*/
@Test
public void testForceDark_userAgentDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
// Loading empty page with or without dark theme support into a force-dark-on webview with
// force dark only algorithm should result in a dark background.
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.USER_AGENT_DARKENING_ONLY);
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
}
/**
* Test to exercise WEB_THEME_DARKENING_ONLY option,
* i.e. web contents are darkened only by web theme.
*/
// TODO(amalova): Enable test when meta-tag is supported by WV
@Test
@Ignore
public void testForceDark_webThemeDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.WEB_THEME_DARKENING_ONLY);
// Loading a page without dark-theme support should result in a light background as web
// page is not darken by a user agent
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be light", Color.luminance(getWebPageColor()) > 0.5f);
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green", Color.GREEN == getWebPageColor());
}
/**
* Test to exercise PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING option,
* i.e. web contents are darkened by a user agent if there is no dark web theme.
*/
// TODO(amalova): Enable test when meta-tag is supported by WV
@Test
@Ignore
public void testForceDark_preferWebThemeOverUADarkening() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING);
// Loading a page without dark-theme support should result in a dark background as
// web page is darken by a user agent
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green", Color.GREEN == getWebPageColor());
}
private void setWebViewSize(final int width, final int height) {
WebkitUtils.onMainThreadSync(() -> {
WebView webView = mWebViewOnUiThread.getWebViewOnCurrentThread();
ViewGroup.LayoutParams params = webView.getLayoutParams();
params.height = height;
params.width = width;
webView.setLayoutParams(params);
});
}
private int getWebPageColor() {
Map<Integer, Integer> histogram;
Integer[] colourValues;
histogram = getBitmapHistogram(mWebViewOnUiThread.captureBitmap(), 0, 0, 64, 64);
assertEquals("Bitmap should have a single colour", histogram.size(), 1);
colourValues = histogram.keySet().toArray(new Integer[0]);
return colourValues[0];
}
private Map<Integer, Integer> getBitmapHistogram(
Bitmap bitmap, int x, int y, int width, int height) {
Map<Integer, Integer> histogram = new HashMap<>();
for (int pixel : getBitmapPixels(bitmap, x, y, width, height)) {
histogram.put(pixel, histogram.getOrDefault(pixel, 0) + 1);
}
return histogram;
}
private int[] getBitmapPixels(Bitmap bitmap, int x, int y, int width, int height) {
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, x, y, width, height);
return pixels;
}
}
| webkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.webkit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Base64;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import androidx.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
import java.util.Map;
@RunWith(AndroidJUnit4.class)
public class WebSettingsCompatForceDarkTest {
private final String mNoDarkThemeSupport = Base64.encodeToString((
"<html>\n"
+ " <head>"
+ " </head>"
+ " <body>"
+ " </body>"
+ "</html>").getBytes(), Base64.NO_PADDING);
private final String mDarkThemeSupport = Base64.encodeToString((
"<html>"
+ " <head>"
+ " <meta name=\"color-scheme\" content=\"light dark\">"
+ " <style>"
+ " @media (prefers-color-scheme: dark) {"
+ " body {background-color: green; }"
+ " </style>"
+ " </head>"
+ " <body>"
+ " </body>"
+ "</html>"
).getBytes(), Base64.NO_PADDING);
// LayoutParams are null until WebView has a parent Activity.
// Test testForceDark_rendersDark requires LayoutParams to define
// width and height of WebView to capture its bitmap representation.
@Rule
public final ActivityTestRule<WebViewTestActivity> mActivityRule =
new ActivityTestRule<>(WebViewTestActivity.class);
private WebViewOnUiThread mWebViewOnUiThread;
@Before
public void setUp() {
mWebViewOnUiThread = new WebViewOnUiThread(mActivityRule.getActivity().getWebView());
}
@After
public void tearDown() {
if (mWebViewOnUiThread != null) {
mWebViewOnUiThread.cleanUp();
}
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_default. Modifications to this test should
* be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
@SmallTest
public void testForceDark_default() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
assertEquals("The default force dark state should be AUTO",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_AUTO);
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_rendersDark. Modifications to this test
* should be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
@SmallTest
public void testForceDark_rendersDark() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
setWebViewSize(64, 64);
// Loading about:blank into a force-dark-on webview should result in a dark background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
assertEquals("Force dark should have been set to ON",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_ON);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
// Loading about:blank into a force-dark-off webview should result in a light background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
assertEquals("Force dark should have been set to OFF",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_OFF);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be light",
Color.luminance(getWebPageColor()) > 0.5f);
}
/**
* Test to exercise USER_AGENT_DARKENING_ONLY option,
* i.e. web contents are always darkened by a user agent.
*/
@Test
@SmallTest
public void testForceDark_userAgentDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
// Loading empty page with or without dark theme support into a force-dark-on webview with
// force dark only algorithm should result in a dark background.
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.USER_AGENT_DARKENING_ONLY);
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
}
/**
* Test to exercise WEB_THEME_DARKENING_ONLY option,
* i.e. web contents are darkened only by web theme.
*/
// TODO(amalova): Enable test when meta-tag is supported by WV
@Test
@SmallTest
@Ignore
public void testForceDark_webThemeDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.WEB_THEME_DARKENING_ONLY);
// Loading a page without dark-theme support should result in a light background as web
// page is not darken by a user agent
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be light", Color.luminance(getWebPageColor()) > 0.5f);
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green", Color.GREEN == getWebPageColor());
}
/**
* Test to exercise PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING option,
* i.e. web contents are darkened by a user agent if there is no dark web theme.
*/
// TODO(amalova): Enable test when meta-tag is supported by WV
@Test
@SmallTest
@Ignore
public void testForceDark_preferWebThemeOverUADarkening() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
setWebViewSize(64, 64);
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING);
// Loading a page without dark-theme support should result in a dark background as
// web page is darken by a user agent
mWebViewOnUiThread.loadDataAndWaitForCompletion(mNoDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark", Color.luminance(getWebPageColor()) < 0.5f);
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green", Color.GREEN == getWebPageColor());
}
private void setWebViewSize(final int width, final int height) {
WebkitUtils.onMainThreadSync(() -> {
WebView webView = mWebViewOnUiThread.getWebViewOnCurrentThread();
ViewGroup.LayoutParams params = webView.getLayoutParams();
params.height = height;
params.width = width;
webView.setLayoutParams(params);
});
}
private int getWebPageColor() {
Map<Integer, Integer> histogram;
Integer[] colourValues;
histogram = getBitmapHistogram(mWebViewOnUiThread.captureBitmap(), 0, 0, 64, 64);
assertEquals("Bitmap should have a single colour", histogram.size(), 1);
colourValues = histogram.keySet().toArray(new Integer[0]);
return colourValues[0];
}
private Map<Integer, Integer> getBitmapHistogram(
Bitmap bitmap, int x, int y, int width, int height) {
Map<Integer, Integer> histogram = new HashMap<>();
for (int pixel : getBitmapPixels(bitmap, x, y, width, height)) {
histogram.put(pixel, histogram.getOrDefault(pixel, 0) + 1);
}
return histogram;
}
private int[] getBitmapPixels(Bitmap bitmap, int x, int y, int width, int height) {
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, x, y, width, height);
return pixels;
}
}
| Fix WebSettingsCompatForceDarkTest failing due to timeout issues.
Force dark tests launch an Activity and inflates WebView. These
operations are slow therefore they should been @MediumTest.
Bug: 142790600
Bug: 143453809
Test: none
Change-Id: Icce357e73adf89020dd115797fdde03d6c13e872
| webkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java | Fix WebSettingsCompatForceDarkTest failing due to timeout issues. | <ide><path>ebkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java
<ide> import android.webkit.WebView;
<ide>
<ide> import androidx.test.ext.junit.runners.AndroidJUnit4;
<del>import androidx.test.filters.SmallTest;
<add>import androidx.test.filters.MediumTest;
<ide> import androidx.test.rule.ActivityTestRule;
<ide>
<ide> import org.junit.After;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<add>@MediumTest
<ide> @RunWith(AndroidJUnit4.class)
<ide> public class WebSettingsCompatForceDarkTest {
<ide> private final String mNoDarkThemeSupport = Base64.encodeToString((
<ide> * be reflected in that test as necessary. See http://go/modifying-webview-cts.
<ide> */
<ide> @Test
<del> @SmallTest
<ide> public void testForceDark_default() throws Throwable {
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
<ide>
<ide> * should be reflected in that test as necessary. See http://go/modifying-webview-cts.
<ide> */
<ide> @Test
<del> @SmallTest
<ide> public void testForceDark_rendersDark() throws Throwable {
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
<ide> setWebViewSize(64, 64);
<ide> * i.e. web contents are always darkened by a user agent.
<ide> */
<ide> @Test
<del> @SmallTest
<ide> public void testForceDark_userAgentDarkeningOnly() {
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
<ide> */
<ide> // TODO(amalova): Enable test when meta-tag is supported by WV
<ide> @Test
<del> @SmallTest
<ide> @Ignore
<ide> public void testForceDark_webThemeDarkeningOnly() {
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
<ide> */
<ide> // TODO(amalova): Enable test when meta-tag is supported by WV
<ide> @Test
<del> @SmallTest
<ide> @Ignore
<ide> public void testForceDark_preferWebThemeOverUADarkening() {
<ide> WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK); |
|
Java | apache-2.0 | 8f9770273461bdd0f04d6ba8ba82794967155e8c | 0 | aeshell/aesh-readline,aeshell/aesh-readline,aeshell/aesh-readline | /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aesh.readline;
import org.aesh.readline.completion.Completion;
import org.aesh.readline.terminal.Key;
import org.aesh.readline.tty.terminal.TestConnection;
import org.aesh.utils.Config;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href=mailto:[email protected]">Ståle W. Pedersen</a>
*/
public class CompletionReadlineTest {
@Test
public void testCompletion() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().equals("foo"))
co.addCompletionCandidate("foobar");
});
completions.add(co -> {
if(co.getBuffer().equals("bar")) {
co.addCompletionCandidate("barfoo");
co.doAppendSeparator(false);
}
});
completions.add( co -> {
if(co.getBuffer().equals("le")) {
co.addCompletionCandidate("less");
co.setSeparator(':');
}
});
TestConnection term = new TestConnection(completions);
term.read("foo".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("foobar ");
term.readline(completions);
term.read("bar".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("barfoo");
term.readline(completions);
term.read("le".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("less:");
}
@Test
public void testCompletionEmptyLine() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().trim().equals("")) {
co.addCompletionCandidate("bar");
co.addCompletionCandidate("foo");
}
});
TestConnection term = new TestConnection(completions);
term.read(" ".getBytes());
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.CTRL_I);
term.assertOutputBuffer(": \nbar foo \n:");
term.clearOutputBuffer();
term.read("a");
term.read(Config.getLineSeparator());
term.assertLine("a ");
}
@Test
public void testCompletionMidLine() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().trim().startsWith("1 ")) {
co.addCompletionCandidate("1 foo");
}
});
TestConnection term = new TestConnection(completions);
term.read("1 bah".getBytes());
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.CTRL_I);
term.assertBuffer("1 foo bah");
term.clearOutputBuffer();
term.read("A");
term.read(Config.getLineSeparator());
term.assertLine("1 foo Abah");
}
@Test
public void testCompletionsMidLine() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().trim().startsWith("1 ")) {
co.addCompletionCandidate("bar");
co.addCompletionCandidate("foo");
}
});
TestConnection term = new TestConnection(completions);
term.read("1 bah".getBytes());
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.CTRL_I);
term.assertOutputBuffer(": 1 bah\nbar foo \n: 1 bah");
term.clearOutputBuffer();
term.read("A");
term.read(Config.getLineSeparator());
term.assertLine("1 Abah");
}
}
| readline/src/test/java/org/aesh/readline/CompletionReadlineTest.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aesh.readline;
import org.aesh.readline.completion.Completion;
import org.aesh.readline.terminal.Key;
import org.aesh.readline.tty.terminal.TestConnection;
import org.aesh.utils.Config;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href=mailto:[email protected]">Ståle W. Pedersen</a>
*/
public class CompletionReadlineTest {
@Test
public void testCompletion() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().equals("foo"))
co.addCompletionCandidate("foobar");
});
completions.add(co -> {
if(co.getBuffer().equals("bar")) {
co.addCompletionCandidate("barfoo");
co.doAppendSeparator(false);
}
});
completions.add( co -> {
if(co.getBuffer().equals("le")) {
co.addCompletionCandidate("less");
co.setSeparator(':');
}
});
TestConnection term = new TestConnection(completions);
term.read("foo".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("foobar ");
term.readline(completions);
term.read("bar".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("barfoo");
term.readline(completions);
term.read("le".getBytes());
term.read(Key.CTRL_I);
term.read(Config.getLineSeparator());
term.assertLine("less:");
}
@Test
public void testCompletionEmptyLine() {
List<Completion> completions = new ArrayList<>();
completions.add(co -> {
if(co.getBuffer().trim().equals("")) {
co.addCompletionCandidate("bar");
co.addCompletionCandidate("foo");
}
});
TestConnection term = new TestConnection(completions);
term.read(" ".getBytes());
term.read(Key.LEFT);
term.read(Key.LEFT);
term.read(Key.CTRL_I);
term.assertOutputBuffer(": \nbar foo \n:");
term.clearOutputBuffer();
term.read("a");
term.read(Config.getLineSeparator());
term.assertLine("a ");
}
}
| added tests to verify mid line completions work as expected
| readline/src/test/java/org/aesh/readline/CompletionReadlineTest.java | added tests to verify mid line completions work as expected | <ide><path>eadline/src/test/java/org/aesh/readline/CompletionReadlineTest.java
<ide> term.assertLine("a ");
<ide> }
<ide>
<add> @Test
<add> public void testCompletionMidLine() {
<add> List<Completion> completions = new ArrayList<>();
<add> completions.add(co -> {
<add> if(co.getBuffer().trim().startsWith("1 ")) {
<add> co.addCompletionCandidate("1 foo");
<add> }
<add> });
<add>
<add> TestConnection term = new TestConnection(completions);
<add>
<add> term.read("1 bah".getBytes());
<add> term.read(Key.LEFT);
<add> term.read(Key.LEFT);
<add> term.read(Key.LEFT);
<add> term.read(Key.CTRL_I);
<add> term.assertBuffer("1 foo bah");
<add> term.clearOutputBuffer();
<add> term.read("A");
<add> term.read(Config.getLineSeparator());
<add> term.assertLine("1 foo Abah");
<add> }
<add>
<add>
<add> @Test
<add> public void testCompletionsMidLine() {
<add> List<Completion> completions = new ArrayList<>();
<add> completions.add(co -> {
<add> if(co.getBuffer().trim().startsWith("1 ")) {
<add> co.addCompletionCandidate("bar");
<add> co.addCompletionCandidate("foo");
<add> }
<add> });
<add>
<add> TestConnection term = new TestConnection(completions);
<add>
<add> term.read("1 bah".getBytes());
<add> term.read(Key.LEFT);
<add> term.read(Key.LEFT);
<add> term.read(Key.LEFT);
<add> term.read(Key.CTRL_I);
<add> term.assertOutputBuffer(": 1 bah\nbar foo \n: 1 bah");
<add> term.clearOutputBuffer();
<add> term.read("A");
<add> term.read(Config.getLineSeparator());
<add> term.assertLine("1 Abah");
<add> }
<add>
<ide> } |
|
Java | bsd-3-clause | 721e4f3ae87f8b4e67b3a212e9e18f87a5183778 | 0 | CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers | package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.dao.*;
import gov.nih.nci.cabig.caaers.dao.meddra.LowLevelTermDao;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.domain.attribution.AdverseEventAttribution;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTree;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.TreeNode;
import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.service.InteroperationService;
import gov.nih.nci.cabig.caaers.service.ReportService;
import gov.nih.nci.cabig.caaers.tools.ObjectTools;
import static gov.nih.nci.cabig.caaers.tools.ObjectTools.reduce;
import static gov.nih.nci.cabig.caaers.tools.ObjectTools.reduceAll;
import gov.nih.nci.cabig.caaers.utils.ConfigProperty;
import gov.nih.nci.cabig.caaers.utils.Lov;
import gov.nih.nci.cabig.caaers.web.dwr.AjaxOutput;
import gov.nih.nci.cabig.caaers.web.dwr.IndexChange;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.bean.Row;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelImpl;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.OptimisticLockingFailureException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class CreateAdverseEventAjaxFacade {
private static final Log log = LogFactory.getLog(CreateAdverseEventAjaxFacade.class);
private static Class<?>[] CONTROLLERS = {
CreateAdverseEventController.class, EditAdverseEventController.class
};
private StudyDao studyDao;
private ParticipantDao participantDao;
private CtcTermDao ctcTermDao;
private CtcCategoryDao ctcCategoryDao;
private CtcDao ctcDao;
private LowLevelTermDao lowLevelTermDao;
private ExpeditedAdverseEventReportDao aeReportDao;
private RoutineAdverseEventReportDao roReportDao;
private ResearchStaffDao researchStaffDao;
private AnatomicSiteDao anatomicSiteDao;
private InteroperationService interoperationService;
private PriorTherapyDao priorTherapyDao;
private PreExistingConditionDao preExistingConditionDao;
private AgentDao agentDao;
private TreatmentAssignmentDao treatmentAssignmentDao;
private ExpeditedReportTree expeditedReportTree;
private ConfigProperty configProperty;
private ReportService reportService;
private LabCategoryDao labCategoryDao;
private LabTermDao labTermDao;
private ChemoAgentDao chemoAgentDao;
private InterventionSiteDao interventionSiteDao;
private CtepStudyDiseaseDao ctepStudyDiseaseDao;
public List<AnatomicSite> matchAnatomicSite(String text) {
return anatomicSiteDao.getBySubnames(extractSubnames(text));
}
public AnatomicSite getAnatomicSiteById(String anatomicSiteId) throws Exception {
return anatomicSiteDao.getById(Integer.parseInt(anatomicSiteId));
}
public String buildAnatomicSiteTable(final Map parameterMap, String tableId, HttpServletRequest request) throws Exception {
try {
TableModel model = getTableModel(parameterMap, request);
List<AnatomicSite> anatomicSites = anatomicSiteDao.getAll();
String onInvokeAction = "showDiseaseSiteTable('" + tableId + "')";
addTableAndRowToModel(model, tableId, anatomicSites, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("name");
columnTerm.setTitle("Primary site of disease");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.AnatomicSiteLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the anatomicSites" + e.toString() + " message" + e.getMessage());
}
return "";
}
private TableModel getTableModel(Map parameterMap, HttpServletRequest request) {
Context context = null;
if (parameterMap == null) {
context = new HttpServletRequestContext(request);
} else {
context = new HttpServletRequestContext(request, parameterMap);
}
TableModel model = new TableModelImpl(context);
return model;
}
public List<PriorTherapy> matchPriorTherapies(String text) {
return priorTherapyDao.getBySubnames(extractSubnames(text));
}
public List<PreExistingCondition> matchPreExistingConds(String text) {
return preExistingConditionDao.getBySubnames(extractSubnames(text));
}
public List<LowLevelTerm> matchLowLevelTermsByCode(String text) {
return lowLevelTermDao.getBySubnames(extractSubnames(text));
}
public List<ChemoAgent> matchChemoAgents(String text) {
String[] excerpts = {text};
List<ChemoAgent> agents = chemoAgentDao.getBySubname(excerpts);
return agents;
}
public ChemoAgent getChemoAgentById(String chemoAgentId) throws Exception {
return chemoAgentDao.getById(Integer.parseInt(chemoAgentId));
}
public String buildChemoAgentsTable(final Map parameterMap, String tableId, HttpServletRequest request) throws Exception {
try {
List<ChemoAgent> chemoAgents = chemoAgentDao.getAll();
TableModel model = getTableModel(parameterMap, request);
String onInvokeAction = "showChemoAgentsTable('" + tableId + "')";
addTableAndRowToModel(model, tableId, chemoAgents, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("name");
columnTerm.setTitle("Agent");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.ChemoAgentLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the ctc terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
public List<InterventionSite> matchInterventionSites(String text) {
String[] excerpts = {text};
List<InterventionSite> sites = interventionSiteDao.getBySubname(excerpts);
return sites;
}
public List<Agent> matchAgents(String text) {
List<Agent> agents = agentDao.getBySubnames(extractSubnames(text));
return ObjectTools.reduceAll(agents, "id", "name", "nscNumber", "description");
}
public Integer getDiseaseFromStudyDisease(String studyDiseaseId) {
CtepStudyDisease ctepStudyDisease= ctepStudyDiseaseDao.getById(Integer.parseInt(studyDiseaseId));
return ctepStudyDisease.getTerm().getId();
}
public ResearchStaff getResearchStaff(String text) {
ResearchStaff researchStaff = researchStaffDao.getById(Integer.parseInt(text));
return reduce(researchStaff, "id", "firstName", "lastName", "middleName", "emailAddress", "phoneNumber", "faxNumber");
}
public List<Participant> matchParticipants(String text, Integer studyId) {
List<Participant> participants;
if (studyId == null) {
participants = participantDao.getBySubnamesJoinOnIdentifier(extractSubnames(text));
} else {
participants = participantDao.matchParticipantByStudy(studyId, text);
}
// cut down objects for serialization
return reduceAll(participants, "firstName", "lastName", "id", "primaryIdentifierValue");
}
/* Depracated and replace by a hql based query to enhance performance
public List<Participant> matchParticipants(String text, Integer studyId) {
List<Participant> participants = participantRepository.getBySubnames(extractSubnames(text));
if (studyId != null) {
for (Iterator<Participant> it = participants.iterator(); it.hasNext();) {
Participant participant = it.next();
if (!onStudy(participant, studyId)) it.remove();
}
}
// cut down objects for serialization
return reduceAll(participants, "firstName", "lastName", "id");
}
*/
private boolean onStudy(Participant participant, Integer studyId) {
boolean onStudy = false;
for (StudyParticipantAssignment assignment : participant.getAssignments()) {
if (assignment.getStudySite().getStudy().getId().equals(studyId)) {
onStudy = true;
break;
}
}
return onStudy;
}
/* Depracated and replace by a hql based query to enhance performance
public List<Study> matchStudies(String text, Integer participantId) {
List<Study> studies = studyDao.getBySubnames(extractSubnames(text));
if (participantId != null) {
for (Iterator<Study> it = studies.iterator(); it.hasNext();) {
Study study = it.next();
if (!onStudy(study, participantId)) it.remove();
}
}
// cut down objects for serialization
return reduceAll(studies, "id", "shortTitle");
}
*/
/*
* The extra condition "o.status <> 'Administratively Complete'" as fix for bug 9514
*/
public List<Study> matchStudies(String text, Integer participantId, boolean ignoreCompletedStudy) {
List<Study> studies;
if (participantId == null) {
studies = studyDao.getBySubnamesJoinOnIdentifier(extractSubnames(text),
(ignoreCompletedStudy) ? "o.status <> '" + Study.STATUS_ADMINISTRATIVELY_COMPLETE + "'" : null);
} else {
studies = studyDao.matchStudyByParticipant(participantId, text,
(ignoreCompletedStudy) ? "o.status <> '" + Study.STATUS_ADMINISTRATIVELY_COMPLETE + "'" : null);
}
// cut down objects for serialization
return reduceAll(studies, "id", "shortTitle", "primaryIdentifierValue");
}
private boolean onStudy(Study study, Integer participantId) {
boolean onStudy = false;
for (StudySite studySite : study.getStudySites()) {
for (StudyParticipantAssignment assignment : studySite.getStudyParticipantAssignments()) {
if (assignment.getParticipant().getId().equals(participantId)) {
onStudy = true;
break;
}
}
}
return onStudy;
}
public List<CtcTerm> matchTerms(String text, Integer ctcVersionId, Integer ctcCategoryId, int limit) throws Exception {
List<CtcTerm> terms = ctcTermDao.getBySubname(extractSubnames(text), ctcVersionId, ctcCategoryId);
// cut down objects for serialization
for (CtcTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getCtc().setCategories(null);
}
while (terms.size() > limit) {
terms.remove(terms.size() - 1);
}
return terms;
}
public List<CtcTerm> getTermsByCategory(Integer ctcCategoryId) throws Exception {
List<CtcTerm> terms = ctcCategoryDao.getById(ctcCategoryId).getTerms();
// cut down objects for serialization
for (CtcTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getCtc().setCategories(null);
}
return terms;
}
public List<CtcTerm> getTermByTermId(String ctcTermId) throws Exception {
List<CtcTerm> terms = new ArrayList<CtcTerm>();
CtcTerm ctcTerm = ctcTermDao.getById(Integer.parseInt(ctcTermId));
ctcTerm.getCategory().setTerms(null);
ctcTerm.getCategory().getCtc().setCategories(null);
terms.add(ctcTerm);
return terms;
}
public String buildTermsTableByCategory(final Map parameterMap,Integer ctcCategoryId, String tableId, HttpServletRequest request) throws Exception {
if (ctcCategoryId == null || ctcCategoryId == 0) {
return "";
}
try {
List<CtcTerm> terms = getTermsByCategory(ctcCategoryId);
TableModel model = getTableModel(parameterMap, request);
String onInvokeAction = "buildTable('command'," + ctcCategoryId.intValue() + ",'" + tableId + "')";
addTableAndRowToModel(model, tableId, terms, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("fullName");
columnTerm.setTitle("CTC term");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.CtcTermLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the ctc terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
public List<CtcCategory> getCategories(int ctcVersionId) {
List<CtcCategory> categories = ctcDao.getById(ctcVersionId).getCategories();
// cut down objects for serialization
for (CtcCategory category : categories) {
category.setTerms(null);
}
return categories;
}
public List<? extends CodedGrade> getTermGrades(int ctcTermId) {
List<CodedGrade> list = ctcTermDao.getById(ctcTermId).getGrades();
// have to detect whether it's a collection of Grade or CtcGrade;
// if the latter, need to call reduce
if (list.size() == 0) {
return list;
} else if (list.get(0) instanceof Grade) {
return list;
} else {
return reduceAll(list, "grade", "text");
}
}
public List<LabTerm> matchLabTerms(String text, Integer labCategoryId) {
List<LabTerm> terms = labTermDao.getBySubname(extractSubnames(text), labCategoryId);
// cut down objects for serialization
for (LabTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getLabVersion().setCategories(null);
}
return terms;
}
public LabTerm getLabTermById(String labTermId) throws Exception {
LabTerm labTerm = labTermDao.getById(Integer.parseInt(labTermId));
// cut down objects for serialization
labTerm.getCategory().setTerms(null);
labTerm.getCategory().getLabVersion().setCategories(null);
return labTerm;
}
public String buildLabTermsTable(final Map parameterMap, String labCategoryId, String tableId, HttpServletRequest request) throws Exception {
if (labCategoryId == null || labCategoryId.equalsIgnoreCase("")) {
return "";
}
try {
TableModel model = getTableModel(parameterMap, request);
List<LabTerm> terms = getLabTermsByCategory(Integer.parseInt(labCategoryId));
String onInvokeAction = "showLabsTable('" + labCategoryId + "','" + tableId + "')";
addTableAndRowToModel(model, tableId, terms, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("term");
columnTerm.setTitle("Lab test name");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.LabTermLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the lab terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
private void addTableAndRowToModel(final TableModel model, final String tableId, final Object items, final String onInvokeAction) {
Table table = model.getTableInstance();
table.setForm("command");
table.setTableId(tableId);
table.setTitle("");
table.setAutoIncludeParameters(Boolean.FALSE);
table.setImagePath(model.getContext().getContextPath() + "/images/table/*.gif");
table.setFilterable(false);
table.setSortable(true);
table.setShowPagination(true);
table.setItems(items);
table.setOnInvokeAction(onInvokeAction);
model.addTable(table);
Row row = model.getRowInstance();
row.setHighlightRow(Boolean.TRUE);
model.addRow(row);
}
public List<LabTerm> getLabTermsByCategory(Integer labCategoryId) {
List<LabTerm> terms;
if (labCategoryId == 0) {
terms = labTermDao.getAll();
} else {
terms = labCategoryDao.getById(labCategoryId).getTerms();
}
// cut down objects for serialization
for (LabTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getLabVersion().setCategories(null);
}
return terms;
}
public List<LabCategory> getLabCategories() {
List<LabCategory> categories = labCategoryDao.getAll();
// cut down objects for serialization
for (LabCategory category : categories) {
category.setTerms(null);
}
return categories;
}
//will return the labTestNamesRefData Lov's matching the testName.
public List<Lov> matchLabTestNames(String testName) {
List<Lov> lovs = new ArrayList<Lov>();
for (Lov lov : configProperty.getMap().get("labTestNamesRefData")) {
if (StringUtils.containsIgnoreCase(lov.getDesc(), testName)) lovs.add(lov);
}
return ObjectTools.reduceAll(lovs, "code", "desc");
}
public List<TreatmentAssignment> matchTreatmentAssignment(String text, int studyId) {
List<TreatmentAssignment> treatmentAssignments = treatmentAssignmentDao.getAssignmentsByStudyId(text, studyId);
return ObjectTools.reduceAll(treatmentAssignments, "id", "code", "description");
}
private String[] extractSubnames(String text) {
return text.split("\\s+");
}
public boolean pushAdverseEventToStudyCalendar(int aeReportId) {
ExpeditedAdverseEventReport report = aeReportDao.getById(aeReportId);
try {
interoperationService.pushToStudyCalendar(report);
return true;
} catch (CaaersSystemException ex) {
log.warn("Interoperation Service, is not working properly", ex);
// this happens if the interoperationService isn't correctly configured
return false;
} catch (RuntimeException re) {
log.error("Unexpected error in communicating with study calendar", re);
return false;
}
}
public boolean pushRoutineAdverseEventToStudyCalendar(int aeReportId) {
RoutineAdverseEventReport report = roReportDao.getById(aeReportId);
try {
interoperationService.pushToStudyCalendar(report);
return true;
} catch (CaaersSystemException ex) {
log.warn("Interoperation Service, is not working properly", ex);
// this happens if the interoperationService isn't correctly configured
return false;
} catch (RuntimeException re) {
log.error("Unexpected error in communicating with study calendar", re);
return false;
}
}
public String withdrawReportVersion(int aeReportId, int reportId) {
ExpeditedAdverseEventReport aeReport = aeReportDao.getById(aeReportId);
for (Report report : aeReport.getReports()) {
if (report.getId().equals(reportId) && !report.getLastVersion().getReportStatus().equals(ReportStatus.COMPLETED)) {
reportService.withdrawLastReportVersion(report);
break;
}
}
aeReportDao.save(aeReport);
return "Success";
}
/**
* Generic method which returns the contents of a JSP form section for the given
* named section.
*/
public String addFormSection(String name, int index, Integer aeReportId) {
return renderIndexedAjaxView(name + "FormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the basic AE entry form for
* the adverse event with the given index
*
* @param index
* @return
*/
public String addRoutineAeMeddra(int index, Integer aeReportId) {
return renderIndexedAjaxView("routineAdverseEventMeddraFormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the other causes form for
* the other cause with the given index
*
* @param index
* @return
*/
public String addPriorTherapy(int index, Integer aeReportId) {
return renderIndexedAjaxView("priorTherapyFormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the other causes form for
* the other cause with the given index
*
* @param index
* @return
*/
public String addPriorTherapyAgent(int index, int parentIndex, Integer aeReportId) {
return renderIndexedAjaxView("priorTherapyAgentFormSection", index, parentIndex, aeReportId);
}
public double calculateBodySurfaceArea(double ht, String htUOM, double wt, String wtUOM) {
return ParticipantHistory.bodySuraceArea(ht, htUOM, wt, wtUOM);
}
/**
* Reorders the list property of the current session command, moving the element at
* <code>objectIndex</code> to <code>targetIndex</code> and shifting everything else
* around as appropriate.
* <p/>
* <p>
* Note that other than the extract command bit, this is entirely non-ae-flow-specific.
* </p>
*
* @return A list of changes indicating which elements of the list were moved and where to.
* This list will be empty if the requested change is invalid or if the change is a no-op.
*/
@SuppressWarnings({"unchecked"})
public AjaxOutput reorder(String listProperty, int objectIndex, int targetIndex) {
Object command = extractCommand();
List<Object> list = (List<Object>) new BeanWrapperImpl(command).getPropertyValue(listProperty);
if (targetIndex >= list.size()) {
log.debug("Attempted to move past the end; " + targetIndex + " >= " + list.size());
return new AjaxOutput("Unable to reorder. Attempted to delete beyond the end; " + targetIndex + " >= " + list.size());
}
if (targetIndex < 0) {
log.debug("Attempted to move past the start; " + targetIndex + " < 0");
return new AjaxOutput("Unable to reorder. Attempted to move past the start; " + targetIndex + " < 0");
}
if (objectIndex == targetIndex) {
log.debug("No move requested; " + objectIndex + " == " + targetIndex);
return new AjaxOutput();
}
if (0 > objectIndex || objectIndex >= list.size()) {
log.debug("No " + listProperty + " with index " + objectIndex);
return new AjaxOutput();
}
Object o = list.remove(objectIndex);
list.add(targetIndex, o);
List<IndexChange> changes = createMoveChangeList(objectIndex, targetIndex);
addDisplayNames(listProperty, changes);
try {
saveIfAlreadyPersistent((ExpeditedAdverseEventInputCommand) command);
} catch( OptimisticLockingFailureException ole){
log.error("Error occured while reordering [listProperty :" + listProperty +
", objectIndex :" + targetIndex +
", targetIndex :" + targetIndex +"]", ole);
return new AjaxOutput("Unable to reorder at this point. The same data is being modified by someone else, please restart the page flow");
}
return new AjaxOutput(changes);
}
private List<IndexChange> createMoveChangeList(int original, int target) {
List<IndexChange> list = new ArrayList<IndexChange>();
if (original < target) {
list.add(new IndexChange(original, target));
for (int i = original + 1; i <= target; i++) {
list.add(new IndexChange(i, i - 1));
}
} else {
for (int i = target; i < original; i++) {
list.add(new IndexChange(i, i + 1));
}
list.add(new IndexChange(original, target));
}
return list;
}
/**
* When we delte an element which has been attributed, the attribution also needs to be deleted.
* @param o
*/
public void cascaeDeleteToAttributions(DomainObject o, ExpeditedAdverseEventReport aeReport){
for(AdverseEvent ae : aeReport.getAdverseEvents()){
if(o instanceof RadiationIntervention){
deleteAttribution(o, ae.getRadiationAttributions(), ae);
}else if(o instanceof MedicalDevice) {
deleteAttribution(o, ae.getDeviceAttributions(), ae);
}else if(o instanceof SurgeryIntervention) {
deleteAttribution(o, ae.getSurgeryAttributions(), ae);
}else if(o instanceof CourseAgent) {
deleteAttribution(o, ae.getCourseAgentAttributions(), ae);
}else if(o instanceof ConcomitantMedication) {
deleteAttribution(o, ae.getConcomitantMedicationAttributions(), ae);
}else if(o instanceof OtherCause) {
deleteAttribution(o, ae.getOtherCauseAttributions(), ae);
}else if(o instanceof DiseaseHistory) {
deleteAttribution(o, ae.getDiseaseAttributions(), ae);
}
}
}
public void deleteAttribution(DomainObject obj, List<? extends AdverseEventAttribution<? extends DomainObject>> attributions, AdverseEvent ae){
AdverseEventAttribution<? extends DomainObject> unwantedAttribution = null;
for(AdverseEventAttribution<? extends DomainObject> attribution : attributions){
if(obj.getId().equals(attribution.getCause().getId())) {
unwantedAttribution = attribution;
break;
}
}
if(unwantedAttribution != null){
attributions.remove(unwantedAttribution);
unwantedAttribution.setAdverseEvent(null);
}
}
/**
* Deletes an element in a list property of the current session command, shifting everything
* else around as appropriate.
* <p/>
* <p>
* Note that other than the extract command bit, this is entirely non-ae-flow-specific.
* </p>
*
* @return A list of changes indicating which elements of the list were moved and where to.
* This list will be empty if the requested change is invalid or if the change is a no-op.
* The element to remove will be represented by a move to a negative index.
*/
@SuppressWarnings({"unchecked"})
public AjaxOutput remove(String listProperty, int indexToDelete) {
ExpeditedAdverseEventInputCommand command = (ExpeditedAdverseEventInputCommand)extractCommand();
command.reassociate(); //reassociate to session
command.getStudy(); //this is to fix the LazyInit execption on "Save&Continue" after a delete(GForge #11981, comments has the details)
List<Object> list = (List<Object>) new BeanWrapperImpl(command).getPropertyValue(listProperty);
if (indexToDelete >= list.size()) {
log.debug("Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
return new AjaxOutput("Unable to delete. Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
}
if (indexToDelete < 0) {
log.debug("Attempted to delete from an invalid index; " + indexToDelete + " < 0");
return new AjaxOutput("Unable to delete. Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
}
List<IndexChange> changes = createDeleteChangeList(indexToDelete, list.size());
Object removedObject = list.get(indexToDelete);
cascaeDeleteToAttributions((DomainObject)removedObject, command.getAeReport());
list.remove(indexToDelete);
addDisplayNames(listProperty, changes);
try{
saveIfAlreadyPersistent(command);
}catch(DataIntegrityViolationException die){
log.error("Error occured while deleting [listProperty :" + listProperty +
", indexToDelete :" + indexToDelete +
"]", die);
return new AjaxOutput("Unable to delete. The object being removed is referenced elsewhere.");
}catch(OptimisticLockingFailureException ole){
log.error("Error occured while deleting [listProperty :" + listProperty +
", indexToDelete :" + indexToDelete +
"]", ole);
return new AjaxOutput("Unable to delete. The same data is being modified by someone else, please restart the page flow.");
}
return new AjaxOutput(changes);
}
private List<IndexChange> createDeleteChangeList(int indexToDelete, int length) {
List<IndexChange> changes = new ArrayList<IndexChange>();
changes.add(new IndexChange(indexToDelete, null));
for (int i = indexToDelete + 1; i < length; i++) {
changes.add(new IndexChange(i, i - 1));
}
return changes;
}
private void addDisplayNames(String listProperty, List<IndexChange> changes) {
TreeNode listNode = expeditedReportTree.find(listProperty.split("\\.", 2)[1]);
for (IndexChange change : changes) {
if (change.getCurrent() != null) {
change.setCurrentDisplayName(listNode.getDisplayName(change.getCurrent()));
}
}
}
private void saveIfAlreadyPersistent(ExpeditedAdverseEventInputCommand command) {
if (command.getAeReport().getId() != null) {
aeReportDao.save(command.getAeReport());
}
}
private String renderIndexedAjaxView(String viewName, int index, Integer aeReportId) {
return renderIndexedAjaxView(viewName, index, null, aeReportId);
}
private String renderIndexedAjaxView(String viewName, int index, Integer parentIndex, Integer aeReportId) {
Map<String, String> params = new LinkedHashMap<String, String>(); // preserve order for testing
params.put("index", Integer.toString(index));
if (parentIndex != null) params.put("parentIndex", Integer.toString(parentIndex));
return renderAjaxView(viewName, aeReportId, params);
}
private String renderAjaxView(String viewName, Integer aeReportId, Map<String, String> params) {
WebContext webContext = WebContextFactory.get();
if (aeReportId != null) params.put("aeReport", aeReportId.toString());
params.put(AbstractAdverseEventInputController.AJAX_SUBVIEW_PARAMETER, viewName);
String url = String.format("%s?%s",
getCurrentPageContextRelative(webContext), createQueryString(params));
log.debug("Attempting to return contents of " + url);
try {
String html = webContext.forwardToString(url);
if (log.isDebugEnabled()) log.debug("Retrieved HTML:\n" + html);
return html;
} catch (ServletException e) {
throw new CaaersSystemException(e);
} catch (IOException e) {
throw new CaaersSystemException(e);
}
}
private Object extractCommand() {
WebContext webContext = WebContextFactory.get();
Object command = null;
for (Class<?> controllerClass : CONTROLLERS) {
String formSessionAttributeName = controllerClass.getName() + ".FORM.command";
command = webContext.getSession().getAttribute(formSessionAttributeName);
if (command == null) {
log.debug("Command not found using name " + formSessionAttributeName);
} else {
log.debug("Command found using name " + formSessionAttributeName);
break;
}
}
if (command == null) {
throw new CaaersSystemException("Could not find command in session");
} else {
return command;
}
}
private String getCurrentPageContextRelative(WebContext webContext) {
String contextPath = webContext.getHttpServletRequest().getContextPath();
String page = webContext.getCurrentPage();
if (contextPath == null) {
log.debug("context path not set");
return page;
} else if (!page.startsWith(contextPath)) {
log.debug(page + " does not start with context path " + contextPath);
return page;
} else {
return page.substring(contextPath.length());
}
}
// TODO: there's got to be a library version of this somewhere
private String createQueryString(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append('=').append(entry.getValue())
.append('&');
}
return sb.toString().substring(0, sb.length() - 1);
}
////// CONFIGURATION
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Required
public void setParticipantDao(final ParticipantDao participantDao) {
this.participantDao = participantDao;
}
@Required
public void setCtcDao(CtcDao ctcDao) {
this.ctcDao = ctcDao;
}
@Required
public void setCtcTermDao(CtcTermDao ctcTermDao) {
this.ctcTermDao = ctcTermDao;
}
@Required
public void setAeReportDao(ExpeditedAdverseEventReportDao aeReportDao) {
this.aeReportDao = aeReportDao;
}
@Required
public void setResearchStaffDao(ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
@Required
public void setInteroperationService(InteroperationService interoperationService) {
this.interoperationService = interoperationService;
}
@Required
public void setAnatomicSiteDao(AnatomicSiteDao anatomicSiteDao) {
this.anatomicSiteDao = anatomicSiteDao;
}
@Required
public void setPriorTherapyDao(PriorTherapyDao priorTherapyDao) {
this.priorTherapyDao = priorTherapyDao;
}
@Required
public void setCtcCategoryDao(CtcCategoryDao ctcCategoryDao) {
this.ctcCategoryDao = ctcCategoryDao;
}
@Required
public void setLowLevelTermDao(LowLevelTermDao lowLevelTermDao) {
this.lowLevelTermDao = lowLevelTermDao;
}
@Required
public void setPreExistingConditionDao(
PreExistingConditionDao preExistingConditionDao) {
this.preExistingConditionDao = preExistingConditionDao;
}
@Required
public void setAgentDao(AgentDao agentDao) {
this.agentDao = agentDao;
}
@Required
public void setExpeditedReportTree(ExpeditedReportTree expeditedReportTree) {
this.expeditedReportTree = expeditedReportTree;
}
@Required
public ConfigProperty getConfigurationProperty() {
return configProperty;
}
public void setConfigurationProperty(ConfigProperty configProperty) {
this.configProperty = configProperty;
}
@Required
public TreatmentAssignmentDao getTreatmentAssignmentDao() {
return treatmentAssignmentDao;
}
public void setTreatmentAssignmentDao(TreatmentAssignmentDao treatmentAssignmentDao) {
this.treatmentAssignmentDao = treatmentAssignmentDao;
}
@Required
public void setReportService(ReportService reportService) {
this.reportService = reportService;
}
@Required
public void setRoutineAdverseEventReportDao(RoutineAdverseEventReportDao roReportDao) {
this.roReportDao = roReportDao;
}
@Required
public LabCategoryDao getLabCategoryDao() {
return labCategoryDao;
}
public void setLabCategoryDao(LabCategoryDao labCategoryDao) {
this.labCategoryDao = labCategoryDao;
}
@Required
public LabTermDao getLabTermDao() {
return labTermDao;
}
public void setLabTermDao(LabTermDao labTermDao) {
this.labTermDao = labTermDao;
}
@Required
public ChemoAgentDao getChemoAgentDao() {
return chemoAgentDao;
}
public void setChemoAgentDao(ChemoAgentDao chemoAgentDao) {
this.chemoAgentDao = chemoAgentDao;
}
@Required
public InterventionSiteDao getInterventionSiteDao() {
return interventionSiteDao;
}
public void setInterventionSiteDao(InterventionSiteDao interventionSiteDao) {
this.interventionSiteDao = interventionSiteDao;
}
@Required
public CtepStudyDiseaseDao getCtepStudyDiseaseDao() {
return ctepStudyDiseaseDao;
}
public void setCtepStudyDiseaseDao(CtepStudyDiseaseDao ctepStudyDiseaseDao) {
this.ctepStudyDiseaseDao = ctepStudyDiseaseDao;
}
}
| projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateAdverseEventAjaxFacade.java | package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.dao.*;
import gov.nih.nci.cabig.caaers.dao.meddra.LowLevelTermDao;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.domain.attribution.AdverseEventAttribution;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTree;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.TreeNode;
import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.repository.ParticipantRepository;
import gov.nih.nci.cabig.caaers.service.InteroperationService;
import gov.nih.nci.cabig.caaers.service.ReportService;
import gov.nih.nci.cabig.caaers.tools.ObjectTools;
import static gov.nih.nci.cabig.caaers.tools.ObjectTools.reduce;
import static gov.nih.nci.cabig.caaers.tools.ObjectTools.reduceAll;
import gov.nih.nci.cabig.caaers.utils.ConfigProperty;
import gov.nih.nci.cabig.caaers.utils.Lov;
import gov.nih.nci.cabig.caaers.web.dwr.AjaxOutput;
import gov.nih.nci.cabig.caaers.web.dwr.IndexChange;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.bean.Row;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelImpl;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.OptimisticLockingFailureException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class CreateAdverseEventAjaxFacade {
private static final Log log = LogFactory.getLog(CreateAdverseEventAjaxFacade.class);
private static Class<?>[] CONTROLLERS = {
CreateAdverseEventController.class, EditAdverseEventController.class
};
private StudyDao studyDao;
private ParticipantRepository participantRepository;
private CtcTermDao ctcTermDao;
private CtcCategoryDao ctcCategoryDao;
private CtcDao ctcDao;
private LowLevelTermDao lowLevelTermDao;
private ExpeditedAdverseEventReportDao aeReportDao;
private RoutineAdverseEventReportDao roReportDao;
private ResearchStaffDao researchStaffDao;
private AnatomicSiteDao anatomicSiteDao;
private InteroperationService interoperationService;
private PriorTherapyDao priorTherapyDao;
private PreExistingConditionDao preExistingConditionDao;
private AgentDao agentDao;
private TreatmentAssignmentDao treatmentAssignmentDao;
private ExpeditedReportTree expeditedReportTree;
private ConfigProperty configProperty;
private ReportService reportService;
private LabCategoryDao labCategoryDao;
private LabTermDao labTermDao;
private ChemoAgentDao chemoAgentDao;
private InterventionSiteDao interventionSiteDao;
private CtepStudyDiseaseDao ctepStudyDiseaseDao;
public List<AnatomicSite> matchAnatomicSite(String text) {
return anatomicSiteDao.getBySubnames(extractSubnames(text));
}
public AnatomicSite getAnatomicSiteById(String anatomicSiteId) throws Exception {
return anatomicSiteDao.getById(Integer.parseInt(anatomicSiteId));
}
public String buildAnatomicSiteTable(final Map parameterMap, String tableId, HttpServletRequest request) throws Exception {
try {
TableModel model = getTableModel(parameterMap, request);
List<AnatomicSite> anatomicSites = anatomicSiteDao.getAll();
String onInvokeAction = "showDiseaseSiteTable('" + tableId + "')";
addTableAndRowToModel(model, tableId, anatomicSites, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("name");
columnTerm.setTitle("Primary site of disease");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.AnatomicSiteLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the anatomicSites" + e.toString() + " message" + e.getMessage());
}
return "";
}
private TableModel getTableModel(Map parameterMap, HttpServletRequest request) {
Context context = null;
if (parameterMap == null) {
context = new HttpServletRequestContext(request);
} else {
context = new HttpServletRequestContext(request, parameterMap);
}
TableModel model = new TableModelImpl(context);
return model;
}
public List<PriorTherapy> matchPriorTherapies(String text) {
return priorTherapyDao.getBySubnames(extractSubnames(text));
}
public List<PreExistingCondition> matchPreExistingConds(String text) {
return preExistingConditionDao.getBySubnames(extractSubnames(text));
}
public List<LowLevelTerm> matchLowLevelTermsByCode(String text) {
return lowLevelTermDao.getBySubnames(extractSubnames(text));
}
public List<ChemoAgent> matchChemoAgents(String text) {
String[] excerpts = {text};
List<ChemoAgent> agents = chemoAgentDao.getBySubname(excerpts);
return agents;
}
public ChemoAgent getChemoAgentById(String chemoAgentId) throws Exception {
return chemoAgentDao.getById(Integer.parseInt(chemoAgentId));
}
public String buildChemoAgentsTable(final Map parameterMap, String tableId, HttpServletRequest request) throws Exception {
try {
List<ChemoAgent> chemoAgents = chemoAgentDao.getAll();
TableModel model = getTableModel(parameterMap, request);
String onInvokeAction = "showChemoAgentsTable('" + tableId + "')";
addTableAndRowToModel(model, tableId, chemoAgents, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("name");
columnTerm.setTitle("Agent");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.ChemoAgentLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the ctc terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
public List<InterventionSite> matchInterventionSites(String text) {
String[] excerpts = {text};
List<InterventionSite> sites = interventionSiteDao.getBySubname(excerpts);
return sites;
}
public List<Agent> matchAgents(String text) {
List<Agent> agents = agentDao.getBySubnames(extractSubnames(text));
return ObjectTools.reduceAll(agents, "id", "name", "nscNumber", "description");
}
public Integer getDiseaseFromStudyDisease(String studyDiseaseId) {
CtepStudyDisease ctepStudyDisease= ctepStudyDiseaseDao.getById(Integer.parseInt(studyDiseaseId));
return ctepStudyDisease.getTerm().getId();
}
public ResearchStaff getResearchStaff(String text) {
ResearchStaff researchStaff = researchStaffDao.getById(Integer.parseInt(text));
return reduce(researchStaff, "id", "firstName", "lastName", "middleName", "emailAddress", "phoneNumber", "faxNumber");
}
public List<Participant> matchParticipants(String text, Integer studyId) {
List<Participant> participants;
if (studyId == null) {
participants = participantRepository.getBySubnamesJoinOnIdentifier(extractSubnames(text));
} else {
participants = participantRepository.matchParticipantByStudy(studyId, text);
}
// cut down objects for serialization
return reduceAll(participants, "firstName", "lastName", "id", "primaryIdentifierValue");
}
/* Depracated and replace by a hql based query to enhance performance
public List<Participant> matchParticipants(String text, Integer studyId) {
List<Participant> participants = participantRepository.getBySubnames(extractSubnames(text));
if (studyId != null) {
for (Iterator<Participant> it = participants.iterator(); it.hasNext();) {
Participant participant = it.next();
if (!onStudy(participant, studyId)) it.remove();
}
}
// cut down objects for serialization
return reduceAll(participants, "firstName", "lastName", "id");
}
*/
private boolean onStudy(Participant participant, Integer studyId) {
boolean onStudy = false;
for (StudyParticipantAssignment assignment : participant.getAssignments()) {
if (assignment.getStudySite().getStudy().getId().equals(studyId)) {
onStudy = true;
break;
}
}
return onStudy;
}
/* Depracated and replace by a hql based query to enhance performance
public List<Study> matchStudies(String text, Integer participantId) {
List<Study> studies = studyDao.getBySubnames(extractSubnames(text));
if (participantId != null) {
for (Iterator<Study> it = studies.iterator(); it.hasNext();) {
Study study = it.next();
if (!onStudy(study, participantId)) it.remove();
}
}
// cut down objects for serialization
return reduceAll(studies, "id", "shortTitle");
}
*/
/*
* The extra condition "o.status <> 'Administratively Complete'" as fix for bug 9514
*/
public List<Study> matchStudies(String text, Integer participantId, boolean ignoreCompletedStudy) {
List<Study> studies;
if (participantId == null) {
studies = studyDao.getBySubnamesJoinOnIdentifier(extractSubnames(text),
(ignoreCompletedStudy) ? "o.status <> '" + Study.STATUS_ADMINISTRATIVELY_COMPLETE + "'" : null);
} else {
studies = studyDao.matchStudyByParticipant(participantId, text,
(ignoreCompletedStudy) ? "o.status <> '" + Study.STATUS_ADMINISTRATIVELY_COMPLETE + "'" : null);
}
// cut down objects for serialization
return reduceAll(studies, "id", "shortTitle", "primaryIdentifierValue");
}
private boolean onStudy(Study study, Integer participantId) {
boolean onStudy = false;
for (StudySite studySite : study.getStudySites()) {
for (StudyParticipantAssignment assignment : studySite.getStudyParticipantAssignments()) {
if (assignment.getParticipant().getId().equals(participantId)) {
onStudy = true;
break;
}
}
}
return onStudy;
}
public List<CtcTerm> matchTerms(String text, Integer ctcVersionId, Integer ctcCategoryId, int limit) throws Exception {
List<CtcTerm> terms = ctcTermDao.getBySubname(extractSubnames(text), ctcVersionId, ctcCategoryId);
// cut down objects for serialization
for (CtcTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getCtc().setCategories(null);
}
while (terms.size() > limit) {
terms.remove(terms.size() - 1);
}
return terms;
}
public List<CtcTerm> getTermsByCategory(Integer ctcCategoryId) throws Exception {
List<CtcTerm> terms = ctcCategoryDao.getById(ctcCategoryId).getTerms();
// cut down objects for serialization
for (CtcTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getCtc().setCategories(null);
}
return terms;
}
public List<CtcTerm> getTermByTermId(String ctcTermId) throws Exception {
List<CtcTerm> terms = new ArrayList<CtcTerm>();
CtcTerm ctcTerm = ctcTermDao.getById(Integer.parseInt(ctcTermId));
ctcTerm.getCategory().setTerms(null);
ctcTerm.getCategory().getCtc().setCategories(null);
terms.add(ctcTerm);
return terms;
}
public String buildTermsTableByCategory(final Map parameterMap,Integer ctcCategoryId, String tableId, HttpServletRequest request) throws Exception {
if (ctcCategoryId == null || ctcCategoryId == 0) {
return "";
}
try {
List<CtcTerm> terms = getTermsByCategory(ctcCategoryId);
TableModel model = getTableModel(parameterMap, request);
String onInvokeAction = "buildTable('command'," + ctcCategoryId.intValue() + ",'" + tableId + "')";
addTableAndRowToModel(model, tableId, terms, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("fullName");
columnTerm.setTitle("CTC term");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.CtcTermLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the ctc terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
public List<CtcCategory> getCategories(int ctcVersionId) {
List<CtcCategory> categories = ctcDao.getById(ctcVersionId).getCategories();
// cut down objects for serialization
for (CtcCategory category : categories) {
category.setTerms(null);
}
return categories;
}
public List<? extends CodedGrade> getTermGrades(int ctcTermId) {
List<CodedGrade> list = ctcTermDao.getById(ctcTermId).getGrades();
// have to detect whether it's a collection of Grade or CtcGrade;
// if the latter, need to call reduce
if (list.size() == 0) {
return list;
} else if (list.get(0) instanceof Grade) {
return list;
} else {
return reduceAll(list, "grade", "text");
}
}
public List<LabTerm> matchLabTerms(String text, Integer labCategoryId) {
List<LabTerm> terms = labTermDao.getBySubname(extractSubnames(text), labCategoryId);
// cut down objects for serialization
for (LabTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getLabVersion().setCategories(null);
}
return terms;
}
public LabTerm getLabTermById(String labTermId) throws Exception {
LabTerm labTerm = labTermDao.getById(Integer.parseInt(labTermId));
// cut down objects for serialization
labTerm.getCategory().setTerms(null);
labTerm.getCategory().getLabVersion().setCategories(null);
return labTerm;
}
public String buildLabTermsTable(final Map parameterMap, String labCategoryId, String tableId, HttpServletRequest request) throws Exception {
if (labCategoryId == null || labCategoryId.equalsIgnoreCase("")) {
return "";
}
try {
TableModel model = getTableModel(parameterMap, request);
List<LabTerm> terms = getLabTermsByCategory(Integer.parseInt(labCategoryId));
String onInvokeAction = "showLabsTable('" + labCategoryId + "','" + tableId + "')";
addTableAndRowToModel(model, tableId, terms, onInvokeAction);
Column columnTerm = model.getColumnInstance();
columnTerm.setProperty("term");
columnTerm.setTitle("Lab test name");
columnTerm.setCell("gov.nih.nci.cabig.caaers.web.search.link.LabTermLinkDisplayCell");
model.addColumn(columnTerm);
return model.assemble().toString();
}
catch (Exception e) {
log.error("error while retriving the lab terms" + e.toString() + " message" + e.getMessage());
}
return "";
}
private void addTableAndRowToModel(final TableModel model, final String tableId, final Object items, final String onInvokeAction) {
Table table = model.getTableInstance();
table.setForm("command");
table.setTableId(tableId);
table.setTitle("");
table.setAutoIncludeParameters(Boolean.FALSE);
table.setImagePath(model.getContext().getContextPath() + "/images/table/*.gif");
table.setFilterable(false);
table.setSortable(true);
table.setShowPagination(true);
table.setItems(items);
table.setOnInvokeAction(onInvokeAction);
model.addTable(table);
Row row = model.getRowInstance();
row.setHighlightRow(Boolean.TRUE);
model.addRow(row);
}
public List<LabTerm> getLabTermsByCategory(Integer labCategoryId) {
List<LabTerm> terms;
if (labCategoryId == 0) {
terms = labTermDao.getAll();
} else {
terms = labCategoryDao.getById(labCategoryId).getTerms();
}
// cut down objects for serialization
for (LabTerm term : terms) {
term.getCategory().setTerms(null);
term.getCategory().getLabVersion().setCategories(null);
}
return terms;
}
public List<LabCategory> getLabCategories() {
List<LabCategory> categories = labCategoryDao.getAll();
// cut down objects for serialization
for (LabCategory category : categories) {
category.setTerms(null);
}
return categories;
}
//will return the labTestNamesRefData Lov's matching the testName.
public List<Lov> matchLabTestNames(String testName) {
List<Lov> lovs = new ArrayList<Lov>();
for (Lov lov : configProperty.getMap().get("labTestNamesRefData")) {
if (StringUtils.containsIgnoreCase(lov.getDesc(), testName)) lovs.add(lov);
}
return ObjectTools.reduceAll(lovs, "code", "desc");
}
public List<TreatmentAssignment> matchTreatmentAssignment(String text, int studyId) {
List<TreatmentAssignment> treatmentAssignments = treatmentAssignmentDao.getAssignmentsByStudyId(text, studyId);
return ObjectTools.reduceAll(treatmentAssignments, "id", "code", "description");
}
private String[] extractSubnames(String text) {
return text.split("\\s+");
}
public boolean pushAdverseEventToStudyCalendar(int aeReportId) {
ExpeditedAdverseEventReport report = aeReportDao.getById(aeReportId);
try {
interoperationService.pushToStudyCalendar(report);
return true;
} catch (CaaersSystemException ex) {
log.warn("Interoperation Service, is not working properly", ex);
// this happens if the interoperationService isn't correctly configured
return false;
} catch (RuntimeException re) {
log.error("Unexpected error in communicating with study calendar", re);
return false;
}
}
public boolean pushRoutineAdverseEventToStudyCalendar(int aeReportId) {
RoutineAdverseEventReport report = roReportDao.getById(aeReportId);
try {
interoperationService.pushToStudyCalendar(report);
return true;
} catch (CaaersSystemException ex) {
log.warn("Interoperation Service, is not working properly", ex);
// this happens if the interoperationService isn't correctly configured
return false;
} catch (RuntimeException re) {
log.error("Unexpected error in communicating with study calendar", re);
return false;
}
}
public String withdrawReportVersion(int aeReportId, int reportId) {
ExpeditedAdverseEventReport aeReport = aeReportDao.getById(aeReportId);
for (Report report : aeReport.getReports()) {
if (report.getId().equals(reportId) && !report.getLastVersion().getReportStatus().equals(ReportStatus.COMPLETED)) {
reportService.withdrawLastReportVersion(report);
break;
}
}
aeReportDao.save(aeReport);
return "Success";
}
/**
* Generic method which returns the contents of a JSP form section for the given
* named section.
*/
public String addFormSection(String name, int index, Integer aeReportId) {
return renderIndexedAjaxView(name + "FormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the basic AE entry form for
* the adverse event with the given index
*
* @param index
* @return
*/
public String addRoutineAeMeddra(int index, Integer aeReportId) {
return renderIndexedAjaxView("routineAdverseEventMeddraFormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the other causes form for
* the other cause with the given index
*
* @param index
* @return
*/
public String addPriorTherapy(int index, Integer aeReportId) {
return renderIndexedAjaxView("priorTherapyFormSection", index, aeReportId);
}
/**
* Returns the HTML for the section of the other causes form for
* the other cause with the given index
*
* @param index
* @return
*/
public String addPriorTherapyAgent(int index, int parentIndex, Integer aeReportId) {
return renderIndexedAjaxView("priorTherapyAgentFormSection", index, parentIndex, aeReportId);
}
public double calculateBodySurfaceArea(double ht, String htUOM, double wt, String wtUOM) {
return ParticipantHistory.bodySuraceArea(ht, htUOM, wt, wtUOM);
}
/**
* Reorders the list property of the current session command, moving the element at
* <code>objectIndex</code> to <code>targetIndex</code> and shifting everything else
* around as appropriate.
* <p/>
* <p>
* Note that other than the extract command bit, this is entirely non-ae-flow-specific.
* </p>
*
* @return A list of changes indicating which elements of the list were moved and where to.
* This list will be empty if the requested change is invalid or if the change is a no-op.
*/
@SuppressWarnings({"unchecked"})
public AjaxOutput reorder(String listProperty, int objectIndex, int targetIndex) {
Object command = extractCommand();
List<Object> list = (List<Object>) new BeanWrapperImpl(command).getPropertyValue(listProperty);
if (targetIndex >= list.size()) {
log.debug("Attempted to move past the end; " + targetIndex + " >= " + list.size());
return new AjaxOutput("Unable to reorder. Attempted to delete beyond the end; " + targetIndex + " >= " + list.size());
}
if (targetIndex < 0) {
log.debug("Attempted to move past the start; " + targetIndex + " < 0");
return new AjaxOutput("Unable to reorder. Attempted to move past the start; " + targetIndex + " < 0");
}
if (objectIndex == targetIndex) {
log.debug("No move requested; " + objectIndex + " == " + targetIndex);
return new AjaxOutput();
}
if (0 > objectIndex || objectIndex >= list.size()) {
log.debug("No " + listProperty + " with index " + objectIndex);
return new AjaxOutput();
}
Object o = list.remove(objectIndex);
list.add(targetIndex, o);
List<IndexChange> changes = createMoveChangeList(objectIndex, targetIndex);
addDisplayNames(listProperty, changes);
try {
saveIfAlreadyPersistent((ExpeditedAdverseEventInputCommand) command);
} catch( OptimisticLockingFailureException ole){
log.error("Error occured while reordering [listProperty :" + listProperty +
", objectIndex :" + targetIndex +
", targetIndex :" + targetIndex +"]", ole);
return new AjaxOutput("Unable to reorder at this point. The same data is being modified by someone else, please restart the page flow");
}
return new AjaxOutput(changes);
}
private List<IndexChange> createMoveChangeList(int original, int target) {
List<IndexChange> list = new ArrayList<IndexChange>();
if (original < target) {
list.add(new IndexChange(original, target));
for (int i = original + 1; i <= target; i++) {
list.add(new IndexChange(i, i - 1));
}
} else {
for (int i = target; i < original; i++) {
list.add(new IndexChange(i, i + 1));
}
list.add(new IndexChange(original, target));
}
return list;
}
/**
* When we delte an element which has been attributed, the attribution also needs to be deleted.
* @param o
*/
public void cascaeDeleteToAttributions(DomainObject o, ExpeditedAdverseEventReport aeReport){
for(AdverseEvent ae : aeReport.getAdverseEvents()){
if(o instanceof RadiationIntervention){
deleteAttribution(o, ae.getRadiationAttributions(), ae);
}else if(o instanceof MedicalDevice) {
deleteAttribution(o, ae.getDeviceAttributions(), ae);
}else if(o instanceof SurgeryIntervention) {
deleteAttribution(o, ae.getSurgeryAttributions(), ae);
}else if(o instanceof CourseAgent) {
deleteAttribution(o, ae.getCourseAgentAttributions(), ae);
}else if(o instanceof ConcomitantMedication) {
deleteAttribution(o, ae.getConcomitantMedicationAttributions(), ae);
}else if(o instanceof OtherCause) {
deleteAttribution(o, ae.getOtherCauseAttributions(), ae);
}else if(o instanceof DiseaseHistory) {
deleteAttribution(o, ae.getDiseaseAttributions(), ae);
}
}
}
public void deleteAttribution(DomainObject obj, List<? extends AdverseEventAttribution<? extends DomainObject>> attributions, AdverseEvent ae){
AdverseEventAttribution<? extends DomainObject> unwantedAttribution = null;
for(AdverseEventAttribution<? extends DomainObject> attribution : attributions){
if(obj.getId().equals(attribution.getCause().getId())) {
unwantedAttribution = attribution;
break;
}
}
if(unwantedAttribution != null){
attributions.remove(unwantedAttribution);
unwantedAttribution.setAdverseEvent(null);
}
}
/**
* Deletes an element in a list property of the current session command, shifting everything
* else around as appropriate.
* <p/>
* <p>
* Note that other than the extract command bit, this is entirely non-ae-flow-specific.
* </p>
*
* @return A list of changes indicating which elements of the list were moved and where to.
* This list will be empty if the requested change is invalid or if the change is a no-op.
* The element to remove will be represented by a move to a negative index.
*/
@SuppressWarnings({"unchecked"})
public AjaxOutput remove(String listProperty, int indexToDelete) {
ExpeditedAdverseEventInputCommand command = (ExpeditedAdverseEventInputCommand)extractCommand();
command.reassociate(); //reassociate to session
command.getStudy(); //this is to fix the LazyInit execption on "Save&Continue" after a delete(GForge #11981, comments has the details)
List<Object> list = (List<Object>) new BeanWrapperImpl(command).getPropertyValue(listProperty);
if (indexToDelete >= list.size()) {
log.debug("Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
return new AjaxOutput("Unable to delete. Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
}
if (indexToDelete < 0) {
log.debug("Attempted to delete from an invalid index; " + indexToDelete + " < 0");
return new AjaxOutput("Unable to delete. Attempted to delete beyond the end; " + indexToDelete + " >= " + list.size());
}
List<IndexChange> changes = createDeleteChangeList(indexToDelete, list.size());
Object removedObject = list.get(indexToDelete);
cascaeDeleteToAttributions((DomainObject)removedObject, command.getAeReport());
list.remove(indexToDelete);
addDisplayNames(listProperty, changes);
try{
saveIfAlreadyPersistent(command);
}catch(DataIntegrityViolationException die){
log.error("Error occured while deleting [listProperty :" + listProperty +
", indexToDelete :" + indexToDelete +
"]", die);
return new AjaxOutput("Unable to delete. The object being removed is referenced elsewhere.");
}catch(OptimisticLockingFailureException ole){
log.error("Error occured while deleting [listProperty :" + listProperty +
", indexToDelete :" + indexToDelete +
"]", ole);
return new AjaxOutput("Unable to delete. The same data is being modified by someone else, please restart the page flow.");
}
return new AjaxOutput(changes);
}
private List<IndexChange> createDeleteChangeList(int indexToDelete, int length) {
List<IndexChange> changes = new ArrayList<IndexChange>();
changes.add(new IndexChange(indexToDelete, null));
for (int i = indexToDelete + 1; i < length; i++) {
changes.add(new IndexChange(i, i - 1));
}
return changes;
}
private void addDisplayNames(String listProperty, List<IndexChange> changes) {
TreeNode listNode = expeditedReportTree.find(listProperty.split("\\.", 2)[1]);
for (IndexChange change : changes) {
if (change.getCurrent() != null) {
change.setCurrentDisplayName(listNode.getDisplayName(change.getCurrent()));
}
}
}
private void saveIfAlreadyPersistent(ExpeditedAdverseEventInputCommand command) {
if (command.getAeReport().getId() != null) {
aeReportDao.save(command.getAeReport());
}
}
private String renderIndexedAjaxView(String viewName, int index, Integer aeReportId) {
return renderIndexedAjaxView(viewName, index, null, aeReportId);
}
private String renderIndexedAjaxView(String viewName, int index, Integer parentIndex, Integer aeReportId) {
Map<String, String> params = new LinkedHashMap<String, String>(); // preserve order for testing
params.put("index", Integer.toString(index));
if (parentIndex != null) params.put("parentIndex", Integer.toString(parentIndex));
return renderAjaxView(viewName, aeReportId, params);
}
private String renderAjaxView(String viewName, Integer aeReportId, Map<String, String> params) {
WebContext webContext = WebContextFactory.get();
if (aeReportId != null) params.put("aeReport", aeReportId.toString());
params.put(AbstractAdverseEventInputController.AJAX_SUBVIEW_PARAMETER, viewName);
String url = String.format("%s?%s",
getCurrentPageContextRelative(webContext), createQueryString(params));
log.debug("Attempting to return contents of " + url);
try {
String html = webContext.forwardToString(url);
if (log.isDebugEnabled()) log.debug("Retrieved HTML:\n" + html);
return html;
} catch (ServletException e) {
throw new CaaersSystemException(e);
} catch (IOException e) {
throw new CaaersSystemException(e);
}
}
private Object extractCommand() {
WebContext webContext = WebContextFactory.get();
Object command = null;
for (Class<?> controllerClass : CONTROLLERS) {
String formSessionAttributeName = controllerClass.getName() + ".FORM.command";
command = webContext.getSession().getAttribute(formSessionAttributeName);
if (command == null) {
log.debug("Command not found using name " + formSessionAttributeName);
} else {
log.debug("Command found using name " + formSessionAttributeName);
break;
}
}
if (command == null) {
throw new CaaersSystemException("Could not find command in session");
} else {
return command;
}
}
private String getCurrentPageContextRelative(WebContext webContext) {
String contextPath = webContext.getHttpServletRequest().getContextPath();
String page = webContext.getCurrentPage();
if (contextPath == null) {
log.debug("context path not set");
return page;
} else if (!page.startsWith(contextPath)) {
log.debug(page + " does not start with context path " + contextPath);
return page;
} else {
return page.substring(contextPath.length());
}
}
// TODO: there's got to be a library version of this somewhere
private String createQueryString(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append('=').append(entry.getValue())
.append('&');
}
return sb.toString().substring(0, sb.length() - 1);
}
////// CONFIGURATION
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Required
public void setParticipantRepository(ParticipantRepository participantRepository) {
this.participantRepository = participantRepository;
}
@Required
public void setCtcDao(CtcDao ctcDao) {
this.ctcDao = ctcDao;
}
@Required
public void setCtcTermDao(CtcTermDao ctcTermDao) {
this.ctcTermDao = ctcTermDao;
}
@Required
public void setAeReportDao(ExpeditedAdverseEventReportDao aeReportDao) {
this.aeReportDao = aeReportDao;
}
@Required
public void setResearchStaffDao(ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
@Required
public void setInteroperationService(InteroperationService interoperationService) {
this.interoperationService = interoperationService;
}
@Required
public void setAnatomicSiteDao(AnatomicSiteDao anatomicSiteDao) {
this.anatomicSiteDao = anatomicSiteDao;
}
@Required
public void setPriorTherapyDao(PriorTherapyDao priorTherapyDao) {
this.priorTherapyDao = priorTherapyDao;
}
@Required
public void setCtcCategoryDao(CtcCategoryDao ctcCategoryDao) {
this.ctcCategoryDao = ctcCategoryDao;
}
@Required
public void setLowLevelTermDao(LowLevelTermDao lowLevelTermDao) {
this.lowLevelTermDao = lowLevelTermDao;
}
@Required
public void setPreExistingConditionDao(
PreExistingConditionDao preExistingConditionDao) {
this.preExistingConditionDao = preExistingConditionDao;
}
@Required
public void setAgentDao(AgentDao agentDao) {
this.agentDao = agentDao;
}
@Required
public void setExpeditedReportTree(ExpeditedReportTree expeditedReportTree) {
this.expeditedReportTree = expeditedReportTree;
}
@Required
public ConfigProperty getConfigurationProperty() {
return configProperty;
}
public void setConfigurationProperty(ConfigProperty configProperty) {
this.configProperty = configProperty;
}
@Required
public TreatmentAssignmentDao getTreatmentAssignmentDao() {
return treatmentAssignmentDao;
}
public void setTreatmentAssignmentDao(TreatmentAssignmentDao treatmentAssignmentDao) {
this.treatmentAssignmentDao = treatmentAssignmentDao;
}
@Required
public void setReportService(ReportService reportService) {
this.reportService = reportService;
}
@Required
public void setRoutineAdverseEventReportDao(RoutineAdverseEventReportDao roReportDao) {
this.roReportDao = roReportDao;
}
@Required
public LabCategoryDao getLabCategoryDao() {
return labCategoryDao;
}
public void setLabCategoryDao(LabCategoryDao labCategoryDao) {
this.labCategoryDao = labCategoryDao;
}
@Required
public LabTermDao getLabTermDao() {
return labTermDao;
}
public void setLabTermDao(LabTermDao labTermDao) {
this.labTermDao = labTermDao;
}
@Required
public ChemoAgentDao getChemoAgentDao() {
return chemoAgentDao;
}
public void setChemoAgentDao(ChemoAgentDao chemoAgentDao) {
this.chemoAgentDao = chemoAgentDao;
}
@Required
public InterventionSiteDao getInterventionSiteDao() {
return interventionSiteDao;
}
public void setInterventionSiteDao(InterventionSiteDao interventionSiteDao) {
this.interventionSiteDao = interventionSiteDao;
}
@Required
public CtepStudyDiseaseDao getCtepStudyDiseaseDao() {
return ctepStudyDiseaseDao;
}
public void setCtepStudyDiseaseDao(CtepStudyDiseaseDao ctepStudyDiseaseDao) {
this.ctepStudyDiseaseDao = ctepStudyDiseaseDao;
}
}
| removing studyservice..
SVN-Revision: 4505
| projects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateAdverseEventAjaxFacade.java | removing studyservice.. | <ide><path>rojects/web/src/main/java/gov/nih/nci/cabig/caaers/web/ae/CreateAdverseEventAjaxFacade.java
<ide> import gov.nih.nci.cabig.caaers.domain.expeditedfields.TreeNode;
<ide> import gov.nih.nci.cabig.caaers.domain.meddra.LowLevelTerm;
<ide> import gov.nih.nci.cabig.caaers.domain.report.Report;
<del>import gov.nih.nci.cabig.caaers.repository.ParticipantRepository;
<ide> import gov.nih.nci.cabig.caaers.service.InteroperationService;
<ide> import gov.nih.nci.cabig.caaers.service.ReportService;
<ide> import gov.nih.nci.cabig.caaers.tools.ObjectTools;
<ide> };
<ide>
<ide> private StudyDao studyDao;
<del> private ParticipantRepository participantRepository;
<add> private ParticipantDao participantDao;
<ide> private CtcTermDao ctcTermDao;
<ide> private CtcCategoryDao ctcCategoryDao;
<ide> private CtcDao ctcDao;
<ide> List<Agent> agents = agentDao.getBySubnames(extractSubnames(text));
<ide> return ObjectTools.reduceAll(agents, "id", "name", "nscNumber", "description");
<ide> }
<del>
<add>
<ide> public Integer getDiseaseFromStudyDisease(String studyDiseaseId) {
<ide> CtepStudyDisease ctepStudyDisease= ctepStudyDiseaseDao.getById(Integer.parseInt(studyDiseaseId));
<ide> return ctepStudyDisease.getTerm().getId();
<ide> public List<Participant> matchParticipants(String text, Integer studyId) {
<ide> List<Participant> participants;
<ide> if (studyId == null) {
<del> participants = participantRepository.getBySubnamesJoinOnIdentifier(extractSubnames(text));
<add> participants = participantDao.getBySubnamesJoinOnIdentifier(extractSubnames(text));
<ide> } else {
<del> participants = participantRepository.matchParticipantByStudy(studyId, text);
<add> participants = participantDao.matchParticipantByStudy(studyId, text);
<ide> }
<ide> // cut down objects for serialization
<ide> return reduceAll(participants, "firstName", "lastName", "id", "primaryIdentifierValue");
<ide> try {
<ide> saveIfAlreadyPersistent((ExpeditedAdverseEventInputCommand) command);
<ide> } catch( OptimisticLockingFailureException ole){
<del> log.error("Error occured while reordering [listProperty :" + listProperty +
<del> ", objectIndex :" + targetIndex +
<add> log.error("Error occured while reordering [listProperty :" + listProperty +
<add> ", objectIndex :" + targetIndex +
<ide> ", targetIndex :" + targetIndex +"]", ole);
<ide> return new AjaxOutput("Unable to reorder at this point. The same data is being modified by someone else, please restart the page flow");
<ide> }
<ide> }
<ide> return list;
<ide> }
<del>
<add>
<ide> /**
<ide> * When we delte an element which has been attributed, the attribution also needs to be deleted.
<ide> * @param o
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> public void deleteAttribution(DomainObject obj, List<? extends AdverseEventAttribution<? extends DomainObject>> attributions, AdverseEvent ae){
<ide> AdverseEventAttribution<? extends DomainObject> unwantedAttribution = null;
<ide> for(AdverseEventAttribution<? extends DomainObject> attribution : attributions){
<ide> unwantedAttribution = attribution;
<ide> break;
<ide> }
<del>
<add>
<ide> }
<ide> if(unwantedAttribution != null){
<ide> attributions.remove(unwantedAttribution);
<ide> Object removedObject = list.get(indexToDelete);
<ide> cascaeDeleteToAttributions((DomainObject)removedObject, command.getAeReport());
<ide> list.remove(indexToDelete);
<del>
<add>
<ide> addDisplayNames(listProperty, changes);
<ide> try{
<ide> saveIfAlreadyPersistent(command);
<ide> }catch(DataIntegrityViolationException die){
<del> log.error("Error occured while deleting [listProperty :" + listProperty +
<del> ", indexToDelete :" + indexToDelete +
<add> log.error("Error occured while deleting [listProperty :" + listProperty +
<add> ", indexToDelete :" + indexToDelete +
<ide> "]", die);
<ide> return new AjaxOutput("Unable to delete. The object being removed is referenced elsewhere.");
<ide> }catch(OptimisticLockingFailureException ole){
<del> log.error("Error occured while deleting [listProperty :" + listProperty +
<del> ", indexToDelete :" + indexToDelete +
<add> log.error("Error occured while deleting [listProperty :" + listProperty +
<add> ", indexToDelete :" + indexToDelete +
<ide> "]", ole);
<ide> return new AjaxOutput("Unable to delete. The same data is being modified by someone else, please restart the page flow.");
<ide> }
<ide> public void setStudyDao(StudyDao studyDao) {
<ide> this.studyDao = studyDao;
<ide> }
<del>
<del> @Required
<del> public void setParticipantRepository(ParticipantRepository participantRepository) {
<del> this.participantRepository = participantRepository;
<del> }
<add> @Required
<add> public void setParticipantDao(final ParticipantDao participantDao) {
<add> this.participantDao = participantDao;
<add> }
<add>
<add>
<ide>
<ide> @Required
<ide> public void setCtcDao(CtcDao ctcDao) {
<ide> public void setCtepStudyDiseaseDao(CtepStudyDiseaseDao ctepStudyDiseaseDao) {
<ide> this.ctepStudyDiseaseDao = ctepStudyDiseaseDao;
<ide> }
<del>
<del>
<del>
<del>
<del>
<add>
<add>
<add>
<add>
<add>
<ide> } |
|
JavaScript | apache-2.0 | 39f3bac1738e7f9003a236a80dabd8888018a5d6 | 0 | jadman02/testphonegap,jadman02/testphonegap | var refreshIntervalId;
var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png']
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function sendNotification(targetto,param){
firebase.auth().currentUser.getToken().then(function(idToken) {
var titlestring;
var bodystring;
if (param == 1){titlestring = 'New match created';bodystring='With ' + f_first;}
if (param == 2){titlestring = 'New date request received';bodystring='From ' + f_first;}
if (param == 3){titlestring = 'New date confirmed';bodystring='By ' + f_first;}
if (param == 4){titlestring = 'New message received';bodystring='From ' + f_first;}
if (param == 5){titlestring = 'New photo received';bodystring='From ' + f_first;}
if (param == 6){titlestring = 'Date cancelled';bodystring='With ' + f_first;}
var typesend;
if (d_type){typesend = d_type;}
else {typesend = 'date';}
$.post( "http://www.dateorduck.com/sendnotification.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,target:targetto,titlestring:titlestring,bodystring:bodystring,param:param,type:typesend,firstname:f_first} )
.done(function( data ) {
//alert(JSON.stringify(data));
});
});
}
function sharePop(){
facebookConnectPlugin.showDialog({
method: "share",
href: "http://www.dateorduck.com/",
hashtag: "#dateorduck"
//share_feedWeb: true, // iOS only
}, function (response) {}, function (response) {})
}
function appLink(){
facebookConnectPlugin.appInvite(
{
url: "https://fb.me/1554148374659639",
picture: "https://www.google.com.au/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
},
function(obj){
if(obj) {
if(obj.completionGesture == "cancel") {
// user canceled, bad guy
} else {
// user really invited someone :)
}
} else {
// user just pressed done, bad guy
}
},
function(obj){
// error
// alert(JSON.stringify(obj));
}
);
}
function fcm(){
NativeKeyboard.showMessenger({
onSubmit: function(text) {
//console.log("The user typed: " + text);
}
});
}
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
myApp.alert('Could not confirm your hometown.', 'Error');
clearHometown();
} else{
var predictionsarray = [];
$('.hometownprediction').remove();
predictions.forEach(function(prediction) {
predictionsarray.push(prediction.description);
});
}
var hometownpicker = myApp.picker({
input: '#homesearch',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } },
onChange:function (p, values, displayValues){$( '#homesearch' ).addClass("profilevaluechosen");},
onClose:function (p){hometownpicker.destroy();},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'hometown\')">' +
'<a href="#" class="link close-picker" onclick="clearHometown();" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: predictionsarray
}
]
});
hometownpicker.open();
};
function checkHometown(){
var hometownquery = $('#homesearch').val();
if (hometownquery == ''){
return false;}
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: hometownquery,types: ['(cities)'] }, displaySuggestions);
}
function clearHometown(){
$('#homesearch').val('');
}
function newHometown(){
$('#homesearch').remove();
$('.hometown-input').append('<textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>');
$('#homesearch').focus();
}
function fQuery(){
$.ajax({
url: "https://graph.facebook.com/v2.4/784956164912201?fields=context.fields(friends_using_app)",
type: "get",
data: { access_token: f_token},
success: function (response, textStatus, jqXHR) {
$.ajax({
url: "https://graph.facebook.com/v2.4/"+response.context.id+"/friends_using_app?summary=1",
type: "get",
data: { access_token: f_token},
success: function (response1, textStatus, jqXHR) {
try {
response1.summary.total_count;
var friendstring;
if (response1.summary.total_count ==0) {friendstring = 'No friends use this app'}
if (response1.summary.total_count ==1) {friendstring = '1 friend uses this app' }
if (response1.summary.total_count >1) {friendstring = response1.summary.total_count + ' friends use this app' }
if (response1.summary.total_count > 9){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
firebase.database().ref('users/' + f_uid).update({
recentfriends:'Y'
}).then(function() {});
}
if ((response1.summary.total_count > 4) && (response1.summary.total_count <10)){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = true;
$('.nearby-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.nearby-title').html('Nearby First');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
recentshare = false;
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').show();
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">'+friendstring+'</p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
if (response1.summary.total_count < 5){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = false;
recentshare = false;
$('.nearby-helper').show();
$('.recent-helper').show();
$('.nearby-title').html('<i class="pe-7s-lock pe-lg"></i> Nearby First (Locked)');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
$('.nearby-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.nearby-helper').html('<p style=margin-top:-10px;"padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.summary-helper').html('<p style="font-weight:bold;"></p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
} catch(err) {
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
// $('.recent-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to unlock this feature.</p>');
// $('.nearby-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">Invite friends to unlock features</p><div class="row"><div class="col-100"><a class="button active" href="#" onclick="getFriends">Unlock</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">Features are locked based on how many friends you invite to use the app.</p>');
// caught the reference error
// code here will execute **only** if variable was never declared
}
$( ".summary-helper" ).show();
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
}
function setWant(val){
$( ".homedate" ).addClass("disabled");
$( ".homeduck" ).addClass("disabled");
if (val == 0){
if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant();
}else {homewant = 'offline';updateWant();
}
}
else{$( ".homedate" ).addClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); }
}
}
if (val == 1){
if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); }
}
else{$( ".homeduck" ).addClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); }
}
}
}
function updateWant(){
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
if (homewant == 'offline'){
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
firebase.database().ref('users/' + f_uid).update({
homewant:homewant
}).then(function() {});
//Will update firebase user homewant
//Check if updateuser function is in go daddy file
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} )
.done(function( data ) {
//getMatches();
});
}).catch(function(error) {
// Handle error
});
}
function startCamera(){
navigator.camera.getPicture(conSuccess, conFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY});
}
function conSuccess(imageURI) {
//var image = document.getElementById('myImage');
//image.src = imageURI;
}
function conFail(message) {
// alert('Failed because: ' + message);
}
function doSomething() {
var i = Math.floor(Math.random() * 4) + 0;
$(".desktopimage").attr("src", desktoparray[i]);
}
var myFunction = function() {
doSomething();
var rand = Math.round(Math.random() * (1000 - 700)) + 700;
refreshIntervalId = setTimeout(myFunction, rand);
}
myFunction();
var mobile = 0;
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;}
else{
mobile = 0;
$('.login-loader').hide();
$('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>');
}
//if (mobile===1){
try {
// try to use localStorage
localStorage.test = 2;
} catch (e) {
// there was an error so...
myApp.alert('You are in Privacy Mode\.<br/>Please deactivate Privacy Mode in your browser', 'Error');
}
function directUser(id,type,firstname){
if ($('.chatpop').length > 0) {myApp.closeModal('.chatpop');}
if (type =='date'){createDate1(id,firstname,0);}
else {createDuck(id,firstname,0);}
}
// Initialize your app
var myApp = new Framework7({dynamicNavbar: true,modalActionsCloseByOutside:true,init: false});
// Export selectors engine
var $$ = Dom7;
var datatap, tapid, taptype, tapname;
var view1, view2, view3, view4;
var updatecontinuously = false;
var initialload = false;
var allowedchange = true;
var view3 = myApp.addView('#view-3');
var view4 = myApp.addView('#view-4');
var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,f_image,f_token, f_upper, f_lower, f_interested,sexuality;
var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
var f_auth_id;
var blocklist;
var lastkey;
var distancepicker;
var pickerDescribe,pickerDescribe2, pickerCustomToolbar;
var existingmessages;
var additions = 0;
var myPhotoBrowser;
var singlePhotoBrowser;
var calendarInline;
var keepopen;
var userpref;
var loadpref= false;
var loadpref2= false;
var loaded = false;
var myList;
var myphotosarray;
var matcheslistener;
var noresultstimeout;
var timeoutactive = false;
var radiussize = '100';
var radiusunit = 'Kilometres';
var sortby,offsounds;
var industry_u,hometown_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u,recentfriends;
var descriptionslist = [];
var nameslist = [];
var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">';
var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">';
var notifcount;
var swiperPhotos;
var swiperQuestions;
var myswiperphotos;
var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">';
var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">';
var mySwiper;
myApp.init();
var f_projectid;
var canloadchat;
var viewphotos = false;
var viewscroll = false;
var homewant;
var singlefxallowed = true;
var photoresponse;
var targetpicture;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var firebaseinit;
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
//soNow();
FCMPlugin.onNotification(function(data){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
cordova.plugins.notification.badge.set(data.ev4);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
if (latitudep){directUser(data.ev1,data.ev2,data.ev3);}
else{
datatap = true;
tapid = data.ev1;
taptype = data.ev2;
tapname = data.ev3;
}
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
myApp.addNotification({
title: 'Date or Duck',
subtitle:data.aps.alert.title,
message: data.aps.alert.body,
hold:2000,
closeOnClick:true,
onClick:function(){directUser(data.ev1,data.ev2,data.ev3);},
media: '<img width="44" height="44" style="border-radius:100%" src="media/icon-76.png">'
});
// alert( JSON.stringify(data) );
}
});
// Add views
view1 = myApp.addView('#view-1');
view2 = myApp.addView('#view-2', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
});
view3 = myApp.addView('#view-3');
view4 = myApp.addView('#view-4');
//setTimeout(function(){ alert("Hello");
//FCMPlugin.onTokenRefresh(function(token){
// alert( token );
//});
//alert("Hello2");
// }, 10000);
//authstatechanged user only
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var checkbadge = false;
if (f_projectid){checkbadge = false;}
else{checkbadge = true;}
cordova.plugins.notification.badge.get(function (badge) {
if (badge >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.'))
f_uid = user.providerData[0].uid;
f_auth_id = user.uid;
f_name = user.providerData[0].displayName;
f_first = f_name.substr(0,f_name.indexOf(' '));
f_email = user.providerData[0].email;
f_image = user.providerData[0].photoURL;
// if (subscribeset){}
// else{
// FCMPlugin.subscribeToTopic( f_uid, function(msg){
// alert( msg );
//}, function(err){
// alert( err );
//} );
//}
//subscribeset = true;
if (checkbadge){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/setbadge.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data1 ) {
var result1 = JSON.parse(data1);
cordova.plugins.notification.badge.set(result1[0].notificationcount);
if (result1[0].notificationcount >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
});
}
var originalid = window.localStorage.getItem("originalid");
if (!originalid) {window.localStorage.setItem("originalid", f_uid);}
// $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')");
// $( "#profilepic" ).empty();
// $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>');
firebase.database().ref('users/' + f_uid).update({
auth_id : f_auth_id
}).then(function() {getPreferences();});
} else {
$( ".ploader" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
var originalid = window.localStorage.getItem("originalid");
if (originalid) {$( ".secondlogin" ).show();}
else {$( ".loginbutton" ).show();}
// No user is signed in.
}
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
function clearBadge(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/clearnotifications.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
});
});
$( ".notifspan" ).hide();
cordova.plugins.notification.badge.set(0);
}
function startApp(){
firebaseinit = localStorage.getItem('tokenStore');
if (firebaseinit){
var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
if (error){
myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')');
}
});
}
else {
//alert('no tokenStore');
}
}
//document.addEventListener("screenshot", function() {
// alert("Screenshot");
//}, false);
$$('.panel-right').on('panel:opened', function () {
leftPanel();
});
$$('.panel-right').on('panel:open', function () {
$( ".upgradeli" ).slideDown();
clearBadge();
});
$$('.panel-right').on('panel:closed', function () {
myList.deleteAllItems();
myList.clearCache();
clearBadge();
//firebase.database().ref('notifications/' + f_uid).off('value', notificationlist);
});
function compare(a,b) {
if (a.chat_expire < b.chat_expire)
return -1;
if (a.chat_expire > b.chat_expire)
return 1;
return 0;
}
$$('.panel-left').on('panel:closed', function () {
$(".timeline").empty();
});
$$('.panel-left').on('panel:open', function () {
rightPanel();
});
$$('.panel-right').on('panel:closed', function () {
$( ".upgradeli" ).hide();
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-1');
var geoupdate = Math.round(+new Date()/1000);
var firstupdate = false;
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
// Emulate 2s loading
//loaded = false;
if ($('.no-results-div').length > 0) {myApp.pullToRefreshDone();return false;}
var timesincelastupdate = Math.round(+new Date()/1000) - geoupdate;
if (firstupdate === false){getPreferences();firstupdate = true;}
else{
if (timesincelastupdate > 10){getPreferences();geoupdate = Math.round(+new Date()/1000);}
else {
random_all = shuffle(random_all);
randomswiper.removeAllSlides();
for (i = 0; i < random_all.length; i++) {
var index1 = f_date_match.indexOf(random_all[i].id);
var index2 = f_duck_match.indexOf(random_all[i].id);
var index3 = f_duck_me.indexOf(random_all[i].id);
var index4 = f_date_me.indexOf(random_all[i].id);
var slidewidth = $( document ).width() / 2.5;
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" class="swiper-lazy pp photo_'+random_all[i].id+' photo_'+randomid+'" data-src="'+random_all[i].profilepicstringsmall+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
randomswiper.appendSlide(slidecontent);
if (i == 0 || i==1 || i==2){
$(".photo_"+random_all[i].id).attr("src", random_all[i].profilepicstringsmall);
}
}
$( ".results-loader" ).show();
$( ".swiper-random" ).hide();
$( ".swiper-nearby" ).hide();
$( ".swiper-recent" ).hide();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
setTimeout(function(){
$( ".results-loader" ).hide();
$( ".swiper-random" ).show();
$( ".swiper-nearby" ).show();
$( ".swiper-recent" ).show();
$( ".home-title" ).show();
$( ".nearby-helper" ).show();
$( ".recent-helper" ).show();
$( ".summary-helper" ).show();
}, 2000);
}
}
setTimeout(function () {
// Random image
myApp.pullToRefreshDone();
}, 1000);
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-2');
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
myList.deleteAllItems();
myList.clearCache();
setTimeout(function () {
// Random image
leftPanel();
myApp.pullToRefreshDone();
}, 1000);
});
var onSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function onError(error) {
if (error.code == '1'){
myApp.alert('we are using your approximate location, to improve accuracy go to location settings', 'Oops we cannot find you');
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('You must share your location on date or duck', 'Oops we cannot find you');
});
}
if ((error.code == '2') || (error.code == '3')){
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('There has been an error.', 'Oops we cannot find you');
});
}
}
function showtext(){
$( ".showtext" ).show();
}
function getWifilocation(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var apiGeolocationSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function mainLoaded(id,pid){
$( ".iconpos_" + id ).show();
$( ".default_" + pid).hide();
$( ".photo_"+ pid ).show();
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".maindivhome_" + pid).html('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');}
else{$( ".maindivhome_" + pid ).empty();}
}
});
}
var all_matches_photos=[];
var new_all = [];
var main_all = [];
var random_all = [];
var nearby_all = [];
var recent_all = [];
var nearbyshare = false, recentshare = false;
var randomswiper = myApp.swiper('.swiper-random', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = random_all;
photoBrowser(randomswiper.clickedIndex);}
});
var nearbyswiper = myApp.swiper('.swiper-nearby', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = nearby_all;
if (nearbyshare){
photoBrowser(nearbyswiper.clickedIndex);
}
else{}
}
});
var recentswiper = myApp.swiper('.swiper-recent', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = recent_all;
if (recentshare){
photoBrowser(recentswiper.clickedIndex);
}
else{}
}
});
function getMatches(){
$( ".content-here" ).empty();
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
$( ".results-loader" ).show();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
//alert('getmatch trigger' + homewant);
//can put any ads here
if ((initialload === false) && (availarray.length === 0)){
}
if (!homewant || homewant =='offline'){
$('.content-here').empty();
$( ".statusbar-overlay" ).css("background-color","#ccc");
$( ".buttons-home" ).hide();
$( ".toolbar" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
var swiperheight = $( window ).height() - 378;
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+
'<div class="topdiv">'+
// '<h3>Get Quacking!</h3>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">Get Quacking, It\'s Easy</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">date</span> if you want to find something more serious like a relationship.</div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">date</span> to find love <br/>(or at least try)</div>'+
'</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;margin-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">duck</span> if you want to get down to...ahem...business (replace the D with another letter). </div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">duck</span> to find fun <br/>(replace the D with another letter)</div>'+
'</div>'+
'</div>'+
'<div class="list-block-label" style="color:#666;margin-bottom:10px;">Choose one, or both. Your profile is hidden until you decide.</div>'+
'<div class="swiper-container swiper-helper-info" style="z-index:99999999999999;background-color:#ccc;color:#6d6d72;margin-left:-10px;margin-right:-10px;padding-top:10px;">'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">How this App Works</div>'+
' <div class="swiper-wrapper">'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px;"><i class="twa twa-4x twa-coffee" style="margin-top:5px;"></i><h2>Find your next<br/> coffee date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-wave" style="margin-top:5px;"></i><h2>Or invite someone over<br/> tonight...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-heart-eyes" style="margin-top:5px;"></i><h2>When you like someone, <br/>they can see...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-calendar" style="margin-top:5px;"></i><h2>Once you both agree on</br> a time to meet...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-clock12" style="margin-top:5px;"></i><h2>Chat is enabled until <br/>midnight of your date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-bomb" style="margin-top:5px;"></i><h2>You can send photos that delete after 24 hours...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-watch" style="margin-top:5px;"></i><h2>You can share availability<br/> to easily schedule dates</h2></div></div>'+
' </div>'+
'<div class="swiper-pagination-p" style="margin-top:-20px;margin-bottom:20px;"></div>'+
'</div>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:20px;margin-bottom:10px;margin-left:0px;">Support this app</div>'+
'<a href="#" class="button-big button active" style="margin-bottom:10px;" onclick="appLink()">Invite Friends</a>'+
'<a href="#" class="button-big button" style="margin-bottom:10px;" onclick="sharePop()">Share</a>'+
'<a class="button-big button external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? " style="margin-bottom:10px;">Send SMS</a>'+
'</div>');
$( ".ploader" ).hide();
var homeswiperhelper = myApp.swiper('.swiper-helper-info', {
pagination:'.swiper-pagination-p'
});
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
return false;
}
$( ".statusbar-overlay" ).css("background-color","#2196f3");
initialload = true;
if (recentfriends){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
}
else{
//check permission first
readPermissions();
}
if (updatecontinuously){}
else {setInterval(function(){ justGeo(); }, 599000);updatecontinuously=true;}
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
if (timeoutactive === true) {clearTimeout(noresultstimeout);}
timeoutactive = true;
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/locations.php", { want:homewant,projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,radiusunit:radiusunit,sexuality:sexuality,sortby:'random',latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
dbCall('random');
dbCall('distance');
dbCall('activity');
function dbCall(fetch){
var resultall = JSON.parse(data);
var result;
if (fetch == 'random'){result = resultall[2];}
if (fetch == 'distance'){result = resultall[1];}
if (fetch == 'activity'){result = resultall[0];}
var slidewidth = $( document ).width() / 2.5;
var halfwidth = -Math.abs(slidewidth / 2.23);
$( ".swiper-recent" ).css("height",slidewidth + "px");
$( ".swiper-nearby" ).css("height",slidewidth + "px");
$( ".swiper-random" ).css("height",slidewidth + "px");
var slide_number = 0;
descriptionslist = [];
nameslist = [];
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){
$( ".home-title" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
else {
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (i = 0; i < result.length; i++) {
var photosstringarray =[];
var photocount;
var photostring;
var blocked = 0;
var subtract = result[i].age;
var laston = result[i].timestamp;
var hometown_d = result[i].hometown;
var industry_d = result[i].industry;
var status_d = result[i].status;
var politics_d = result[i].politics;
var eyes_d = result[i].eyes;
var body_d = result[i].body;
var religion_d = result[i].religion;
var zodiac_d = result[i].zodiac;
var ethnicity_d = result[i].ethnicity;
var height_d = result[i].height;
var weight_d = result[i].weight;
var namescount = result[i].displayname.split(' ').length;
var matchname;
var minphotowidth = $( document ).width();
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var availarraystring='';
var availnotexpired = false;
if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){
//console.log(result[i].availstring);
var availablearrayindividual = JSON.parse(result[i].availstring);
//console.log(availablearrayindividual);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[i].availstring;}
}
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[i].largeurl){
var heightarray = result[i].heightslides.split(",");
var widtharray = result[i].widthslides.split(",");
//console.log(heightarray[0]);
//console.log(widtharray[0]);
if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'}
if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'}
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[i].largeurl.split(",").length;
photoarrayuserlarge = result[i].largeurl.split(",");
photoarrayusersmall = result[i].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368';
photocount = 1;
}
//console.log(photostring);
if(namescount === 1){matchname = result[i].displayname;}
else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));}
var matchdescription = result[i].description;
var swipernumber = subtract - f_lower;
var graphid = result[i].uid;
var distance = parseFloat(result[i].distance).toFixed(1);
var distancerounded = parseFloat(result[i].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var zz = new Date();
var mmn = zz.getTimezoneOffset();
//console.log(result[i].timestamp);
var timestampyear = result[i].timestamp.substring(0,4);
var timestampmonth = result[i].timestamp.substring(5,7);
var timestampday = result[i].timestamp.substring(8,10);
var timestamphour = result[i].timestamp.substring(11,13);
var timestampminute = result[i].timestamp.substring(14,16);
var timestampsecond = result[i].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var activecircle='';
//if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';}
//else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';}
if ($('.slide_' + graphid).length){
}
if (graphid != f_uid){
$('.swiper-' + subtract).show();
$('.header_' + subtract).show();
}
var blockedid = blocklist.indexOf(graphid);
//Do not show the users profile to themselves, and do not show profiles older than 1 month
if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){
var index1 = f_date_match.indexOf(graphid);
var index2 = f_duck_match.indexOf(graphid);
var index3 = f_duck_me.indexOf(graphid);
var index4 = f_date_me.indexOf(graphid);
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+' photo_'+randomid+'" data-src="'+profilepicstringsmall+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
if (fetch == 'random'){randomswiper.appendSlide(slidecontent);
random_all.push({profilepicstringsmall:profilepicstringsmall,hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (random_all[0].id == graphid || random_all[1].id == graphid || random_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'distance'){nearbyswiper.appendSlide(slidecontent);
nearby_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (nearby_all[0].id == graphid || nearby_all[1].id == graphid || nearby_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'activity'){recentswiper.appendSlide(slidecontent);
recent_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (recent_all[0].id == graphid || recent_all[1].id == graphid || recent_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
}
}
}
//if (nearbyshare){
//remove blur, unlock swiper
//}
//else{ $( ".nearby-helper" ).show();}
//if (recentshare){
//remove blur, unlock swiper
//}
//else{ $( ".recent-helper" ).show();}
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
if (random_all.length === 0){
if ($('.no-results-div').length > 0) {}
else{
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
}
else {$( ".home-title" ).show(); $('.content-here').empty();}
}
});
//here is the id token call
}).catch(function(error) {
// Handle error
});
$( ".ploader" ).hide();
$( ".toolbar" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
//$('.no-results-div').empty();
clearInterval(refreshIntervalId);
deletePhotos();
}
function justGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
//console.log('updatedtimestamp');
});
}).catch(function(error) {
// Handle error
});
}
function updateGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
getMatches();
});
}).catch(function(error) {
// alert('error' + error);
});
}
function getPreferences(){
// Test if user exists
if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);}
userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) {
var userexists = snapshot.child('lower').exists(); // true
if (userexists) {
// var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) {
// if (!snapshot.child("to_date").val()) {f_to_date = [];}
// else{f_to_date = snapshot.child("to_date").val();}
// if (!snapshot.child("to_duck").val()) {f_to_duck = [];}
// else{f_to_duck = snapshot.child("to_duck").val();}
// if (!snapshot.child("date_me").val()) {f_date_me = [];}
// else{f_date_me = snapshot.child("date_me").val();}
// if (!snapshot.child("duck_me").val()) {f_duck_me=[];}
// else{f_duck_me = snapshot.child("duck_me").val();}
// incommondate = f_to_date.filter(function(n) {
// return f_date_me.indexOf(n) != -1;
//});
//incommonduck = f_to_duck.filter(function(n) {
// return f_duck_me.indexOf(n) != -1;
//});
// });
hometown_u = snapshot.child("hometown").val();
industry_u = snapshot.child("industry").val();
status_u = snapshot.child("status").val();
politics_u = snapshot.child("politics").val();
eyes_u = snapshot.child("eyes").val();
body_u = snapshot.child("body").val();
religion_u = snapshot.child("religion").val();
zodiac_u = snapshot.child("zodiac").val();
ethnicity_u = snapshot.child("ethnicity").val();
height_u = snapshot.child("height").val();
weight_u = snapshot.child("weight").val();
homewant = snapshot.child("homewant").val();
recentfriends = snapshot.child("recentfriends").val();
if (snapshot.child("photoresponse").val()){
if (snapshot.child("photoresponse").val() == 'Y'){photoresponse = 'Y';f_image = snapshot.child("uploadurl").val();}
}
else{
photoresponse = 'N';
f_image = 'https://graph.facebook.com/'+f_uid+'/picture?width=100&height=100';
}
sortby = snapshot.child("sort").val();
if (sortby){
if (sortby == 'random'){sortBy(1);}
if (sortby == 'distance'){sortBy(2);}
if (sortby == 'activity'){sortBy(3);}
$( ".sortbutton" ).removeClass( "active" );
$( "#sort" + sortby ).addClass( "active" );
}
if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();}
if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());}
f_description = snapshot.child("description").val();
f_lower = snapshot.child("lower").val();
radiussize = snapshot.child("radius").val();
if(snapshot.child("radiusunit").val()){radiusunit = snapshot.child("radiusunit").val();}
else{radiusunit = "Kilometres";}
f_token = snapshot.child("token").val();
f_upper = snapshot.child("upper").val();
f_interested = snapshot.child("interested").val();
f_gender = snapshot.child("gender").val();
f_age = snapshot.child("age").val();
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
if (loadpref=== false){
if(homewant){
if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); }
if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active');}
}
loadpref = true;
establishNotif();
}
matchesListener();
}
else if (!userexists) {
addUser();
if (loadpref=== false){
firebase.database().ref('users/' + f_uid).once("value",function(snapshot) {
f_token = snapshot.child("token").val();
swipePopup(1);
});
//preferencesPopup();
}
loadpref = true;
}
});
}
function matchesListener(){
if (loaded === true){
firebase.database().ref("matches/" + f_uid).off('value', matcheslistener);
}
matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) {
f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
blocklist = [];
if (snapshot.val()){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);}
if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);}
if(obj.firstnumberdate){
//f_to_date
if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);}
//f_date_me
if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);}
}
if(obj.firstnumberduck){
//f_duck_me
if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);}
//f_to_duck
if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);}
}
if(obj.secondnumberdate){
//f_to_date
if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);}
//f_date_me
if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);}
}
if(obj.secondnumberduck){
//f_to_duck
if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);}
//f_duck_me
if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);}
}
if(obj.firstnumberdate && obj.secondnumberdate){
//f_date_match
if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
if(obj.firstnumberduck && obj.secondnumberduck){
//f_duck_match
if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
});
updatePhotos();
loaded = true;
}
else{
updatePhotos();
loaded = true;
}
});
getWifilocation();
}
function addUser() {
if (f_token){firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
token:f_token,
auth_id : f_auth_id
});}
else{
firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
auth_id : f_auth_id
});
}
}
function clickMe() {
pickerDescribe.open();
}
function keyUp(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var inputlength = $( "#userdescription" ).val().length;
$( "#maxdescription" ).empty();
$( "#maxdescription" ).append(inputlength + " / 100");
}
function updateUser(){
if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) {
myApp.alert('Please complete more profile information.', 'Missing Information');
return false;}
if (myswiperphotos){
myswiperphotos.destroy();
myswiperphotos = false;
}
var newage,newinterested,newgender;
if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;}
else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === false) {newinterested = f_interested;}
else {newinterested = pickerDescribe2.value[0];}
var userzdescription;
if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();}
else {userzdescription = '';}
//Need to delete old reference
if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];}
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
var lowerage,upperage;
if (pickerDescribe2.initialized === true) {
if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];}
else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];}
}
else {lowerage = f_lower;upperage = f_upper;}
//if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';}
//if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';}
//if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';}
//if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';}
availarray = [];
$( ".availrec" ).each(function() {
if ($( this ).hasClass( "selecrec" )){
var availinputid = $(this).attr('id').replace('aa_', '');
var valueinputted = $( "#picker"+availinputid ).val();
var supdate = $( ".suppdate_"+availinputid ).val();
if (valueinputted == 'Now'){daysaved ='Now';timesaved='';}
else{
valueinputted = valueinputted.split(' ');
var daysaved = valueinputted[0];
var timesaved = valueinputted[1];
}
availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate});
}
});
var availstring = JSON.stringify(availarray);
var availstringn = availstring.toString();
if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'}
//User Profile details
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
var uploadurl = '';
photoresponse = 'N';
if (f_largeurls.length > 0){photoresponse = 'Y';uploadurl = f_largeurls[0];}
else{photoresponse='N';uploadurl = '';}
firebase.database().ref('users/' + f_uid).update({
gender: newgender,
industry:industry_u,
hometown:hometown_u,
status:status_u,
politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u,
height: height_u,
weight: weight_u,
age: newage,
interested: newinterested,
lower: lowerage,
upper: upperage,
description:userzdescription,
radius:radiussize,
radiusunit:radiusunit,
availstring:availstring,
offsounds:offsounds,
photoresponse:photoresponse,
uploadurl:uploadurl
});
if (deletedphoto){
var newsmall = f_smallurls.toString();
var newlarge = f_largeurls.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
}
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,hometown:hometown_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} )
.done(function( data ) {
//if (f_gender && (f_gender != newgender)){
//deleteDatabase();
//}
//if (f_interested && (f_interested != newinterested)){
//deleteDatabase();
//}
});
}).catch(function(error) {
// Handle error
});
f_lower = lowerage;
f_upper = upperage;
//if (loadpref2===true){getWifilocation();}
loadpref2 = true;
myApp.closeModal();
$( ".popup-overlay" ).remove();
}
function processUpdate(){
$( '.donechange' ).show();
$( '.doneunchange' ).hide();
}
function processDupdate(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if (d_chat_expire){
var datemessageq = $( '#datemessageq' ).val();
var interestnewarray = [];
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestnewarray.push(interestadd);
}
});
var comparedinterest;
var compareninterest;
if (d_interest != null) {
comparedinterest = d_interest.toString();
}
else {comparedinterest = '';}
if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();}
if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest))
{
if (d_response=='Y'){noChange();}
else if (d_response=="W"){reverseRequest();dateConfirmationPage();}
}
else{dateRequest();}
}
else {dateRequest();}
}
var mynotifs = [];
function leftPanel(){
canscrollnotif = true;
mynotifs = [];
notifadditions=0;
if(!myList){
myList = myApp.virtualList('.virtual-notifications', {
// Array with plain HTML items
items: [],
height:89,
renderItem: function (index, item) {
var backgroundnotifcolor;
if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';}
if(item.from_uid == f_uid){
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
else{
//onclick="singleBrowser('+item.targetid+')"
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
}
});
}
var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) {
if (snapshot.val() === null){
// $('.title-notify').remove();
// $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>');
$('.nonefound').remove();
$('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$('.nonefound').remove();
var objs = snapshot.val();
var obg = [];
$.each(objs, function(i, obk) {obg.push (obk)});
//console.log(obg);
function compare(a,b) {
if (a.timestamp > b.timestamp)
return -1;
if (a.timestamp < b.timestamp)
return 1;
return 0;
}
obg.sort(compare);
$.each(obg, function(i, obj) {
var typetype = obj.type.substring(0, 4);
var correctimage;
var correctname;
var iconhtml;
var colordot;
var message_text;
var func;
var picturesrc;
var mediaicon;
var dateseenresponse;
if (typetype == 'date') {mediaicon = fdateicon;}
if (typetype == 'duck') {mediaicon = fduckicon;}
//need to see if a match still and then create function based on tha
var timestamptitle;
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - obj.timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = '1 minute ago';}
else if (tunixminago == 1) {timestamptitle = '1 minute ago';}
else if (tunixminago < 2) {timestamptitle = '1 minute ago';}
else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = '1 hour ago';}
else if (tunixminago < 62) {timestamptitle = '1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = '1 day ago';}
else if (tunixminago < 2880) {timestamptitle = '1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';}
else if (tunixminago == 10080) {timestamptitle = '1 week ago';}
else if (tunixminago < 20160) {timestamptitle = '1 week ago';}
else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';}
else if (tunixminago == 525600) {timestamptitle = '1 week ago';}
else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';}
else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';}
// onclick="singleBrowser('+targetid+')"
if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'}
if (obj.param=='image'){
if (obj.from_uid == f_uid){message_text = obj.message + 'sent';}
else {message_text = obj.message + 'received';}
iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';}
if (obj.param=='daterequest'){
if (obj.from_uid == f_uid){message_text = obj.message + ' sent';}
else {message_text = obj.message + ' received';}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='datedeleted'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='newmatch'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='dateconfirmed'){
message_text = obj.message;
iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
// if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';}
// if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';}
if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';}
else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';}
else{colordot = '';}
if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';}
else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';}
datemeinarray=0;
duckmeinarray=0;
datetoinarray=0;
ducktoinarray=0;
if (obj.from_uid == f_uid){picturesrc = obj.to_picture;}
else{picturesrc = obj.from_picture;}
var datesto = f_to_date.indexOf(correctimage);
if (datesto > -1) {
datetoinarray=1;
}
var datesme = f_date_me.indexOf(correctimage);
if (datesme > -1) {
datemeinarray=1;
}
var duckto = f_to_duck.indexOf(correctimage);
if (duckto > -1) {
ducktoinarray=1;
}
var duckme = f_duck_me.indexOf(correctimage);
if (duckme > -1) {
duckmeinarray=1;
}
if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) {
if (typetype == 'date') {func = 'createDate1';}
if (typetype == 'duck') {func = 'createDuck';}
}
else{func = 'singleUser'}
mynotifs.push({
title: message_text,
targetid:correctimage,
targetname:correctname,
picture:picturesrc,
from_name: obj.from_name,
to_name: obj.to_name,
from_uid: obj.from_uid,
to_uid: obj.to_uid,
icon:iconhtml,
colordot:colordot,
func:func,
type:typetype,
timestamptitle:timestamptitle
});
});
var notif2load = mynotifs.length;
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
for (i = 0; i < notifletsload; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
}
});
}
function rightPanel(){
$('.timeline-upcoming').empty();
myApp.sizeNavbars();
var rightdates = [];
var month = [];
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUN";
month[6] = "JUL";
month[7] = "AUG";
month[8] = "SEP";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var weekday = [];
weekday[0] = "SUN";
weekday[1] = "MON";
weekday[2] = "TUE";
weekday[3] = "WED";
weekday[4] = "THU";
weekday[5] = "FRI";
weekday[6] = "SAT";
var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
$('.timeline-upcoming').empty();
if (snapshot.val() === null){
$('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
rightdates.push(obj);
});
rightdates.sort(compare);
for (i = 0; i < rightdates.length; i++) {
var correctname;
var correctid;
var picturesrc;
if (rightdates[i].created_uid == f_uid) {picturesrc = rightdates[i].to_picture;correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;}
if (rightdates[i].created_uid != f_uid) {picturesrc = rightdates[i].from_picture;correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;}
var unix = Math.round(+new Date()/1000);
var c = new Date(rightdates[i].chat_expire*1000);
var cday = weekday[c.getDay()];
if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){
var d = new Date(rightdates[i].chat_expire*1000 - 3600);
var timehere;
if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;}
else {timehere='';}
var timestamptitle;
var datetype = rightdates[i].type.capitalize();
var datesidetitle;
var dayday = d.getDate();
var monthmonth = month[d.getMonth()];
var subtitletext,confirmtext;
if (rightdates[i].response =='Y') {
if (rightdates[i].type=='date' ){datesidetitle = 'Date';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';}
timestamptitle = datesidetitle + ' Confirmed';
var name_accepted;
if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';}
else {name_accepted = rightdates[i].received_name;}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>';
confirmtext='Date confirmed by '+name_accepted+' on '+cday;
}
if (rightdates[i].response =='W') {
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - rightdates[i].timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent now';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';}
if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';}
if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';}
if ($(".time_line_" + dayday)[0]){
} else {
$('.timeline').append('<div class="timeline-item" style="margin-bottom">'+
'<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+
//'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content time_line_'+dayday+'">'+
'</div>'+
'</div>');
}
$('.time_line_'+dayday).append(
'<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+
subtitletext+
// '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+
'<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+
'<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\''+picturesrc+'\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+
// '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+
'<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+
'</div>'+
'</a>'
);
if(rightdates[i].type=='date'){
//for (k = 0; k < rightdates[i].interest.length; k++) {
// $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>');
// }
}
}
}
}
});
}
function newAm(){
$( ".originalam" ).hide();
$( ".newam" ).show();
pickerDescribe.open();
}
function newMe(){
$( ".originalme" ).hide();
$( ".newme" ).show();
pickerDescribe2.open();
}
var deletedphoto;
function getData(){
deletedphoto = false;
if(photosloaded === false){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
var result = JSON.parse(data);
//console.log(result);
if (result!='77' && result[0].largeurl){
$( ".reorderbutton" ).removeClass('disabled');
$( ".deleteallbutton" ).removeClass('disabled');
f_smallurls = result[0].smallurl.split(',');
f_largeurls = result[0].largeurl.split(',');
//console.log(result[0].widthslides);
//console.log(result[0].heightslides);
addedwidth = result[0].widthslides.split(',');
addedheight = result[0].heightslides.split(',');
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
for (i = 0; i < f_largeurls.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
direction:'vertical',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
onClick:function(swiper, event){
}
});
}
else {
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
direction:'vertical'
});
}
});
}).catch(function(error) {
// Handle error
});
}
if (photosloaded === true){myswiperphotos.update();}
photosloaded = true;
}
function deleteIndividual(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
if ($( ".photosliderinfo" ).hasClass('pictures')){
myApp.confirm('Are you sure?', 'Delete Photo', function () {
myswiperphotos.removeSlide(myswiperphotos.clickedIndex);
f_largeurls.splice(myswiperphotos.clickedIndex, 1);
f_smallurls.splice(myswiperphotos.clickedIndex, 1);
addedwidth.splice(myswiperphotos.clickedIndex, 1);
addedheight.splice(myswiperphotos.clickedIndex, 1);
//console.log(addedwidth);
//console.log(addedheight);
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
deletedphoto = true;
myswiperphotos.update();
if (myswiperphotos.slides.length === 0){
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.updatePagination();
myswiperphotos.update();
}
});
}
else {
photosPopup();
}
}
function openAvaill(availtime){
if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');}
else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');}
}
function openAvail(availtime){
$( '.li_'+ availtime ).addClass('selecrec');
}
function removeAvail(availtime,availname,availnameonly){
$( '.li_'+ availtime ).removeClass('selecrec');
$('#picker'+availtime ).remove();
$('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>');
myApp.picker({
input: '#picker' + availtime,
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (availnameonly + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
var availarray = [];
function report(){
myApp.prompt('What is the problem?', 'Report '+targetname, function (value) {
if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;}
targetreported = true;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:value,
response:'N',
timestamp: t_unix,
};
var updates = {};
updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData;
if (f_uid == first_number){
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
}
else{
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
}
return firebase.database().ref().update(updates).then(function() {
myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');});
});
$(".modal-text-input").prop('maxlength','50');
}
function more(){
var swiperno = 0;
myApp.confirm('Are you sure?', 'Block '+targetname, function () {
var blockindex = myPhotoBrowser.swiper.activeIndex;
targetid = new_all[blockindex].id;
myPhotoBrowser.swiper.removeSlide(blockindex);
myPhotoBrowser.swiper.updateSlidesSize();
swiperQuestions.removeSlide(blockindex);
swiperQuestions.updateSlidesSize();
new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1));
if (new_all.length>0){
for (var i = 0; i < random_all.length; i++) {
if (random_all[i].id == targetid){
randomswiper.removeSlide(i);
randomswiper.updateSlidesSize();
random_all = random_all.slice(0,i).concat(random_all.slice(i+1));
}
}
for (var i = 0; i < nearby_all.length; i++) {
if (nearby_all[i].id == targetid){
nearbyswiper.removeSlide(i);
nearbyswiper.updateSlidesSize();
nearby_all = nearby_all.slice(0,i).concat(nearby_all.slice(i+1));
}
}
for (var i = 0; i < recent_all.length; i++) {
if (recent_all[i].id == targetid){
recentswiper.removeSlide(i);
recentswiper.updateSlidesSize();
recent_all = recent_all.slice(0,i).concat(recent_all.slice(i+1));
}
}
}
else {
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.destroy();
nearbyswiper.destroy();
recentswiper.destroy();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
var firstpos;
var lastpos;
myApp.closeModal('.actions-modal');
allowedchange = false;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("their dates failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid);
mydates.remove().then(function() {
//console.log("my dates Remove succeeded.")
})
.catch(function(error) {
//console.log("my dates failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
if (new_all.length>1){
if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';}
if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';}
if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext();swiperQuestions.slidePrev();swiperQuestions.slideNext(); }
else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
}
//myPhotoBrowser.swiper.slideTo(blockindex);
// console.log(all_matches_photos[swipertarget]);
// console.log(new_all);
if (new_all.length === 0){
myPhotoBrowser.close();myApp.closeModal();
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
// myPhotoBrowser.swiper.slideTo(blockindex);
if (new_all.length===1){
$( ".availyo_"+ new_all[0].id ).show();
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var targetdescription= new_all[0].description;
targetname = new_all[0].name;
var targetage = new_all[0].age;
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
if (new_all.length>0){
checkMatch(targetid);
}
});
}
var canscrollnotif = true;
function scrollNotifications(){
//console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top);
if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) {
if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;
setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000);
}
else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);}
}
}
function scrollMessages(){
if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20 || existingmessages < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}}
}
function showDecide(){
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
$( ".toolbardecide" ).show();
}
function closeCreate(){
myApp.closeModal('.actions-modal');
myApp.closeModal('.chatpop');
singlefxallowed = true;
}
function createDate(messageid,messagename,redirect){
if (redirect===0) {}
else { if ($('.chatpop').length > 0){return false;}}
var centerdiv;
if (messageid) {targetid = messageid;}
if (messagename) {targetname = messagename;}
singleUser(targetid,targetname,88);
existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){
cordova.plugins.notification.badge.get(function (badge) {
var newcount = badge-obj.new_message_count;
if (newcount < 1){
$( ".notifspan" ).hide();
}
else {
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
}
});
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
});
}
});
if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div class="navbarphoto"></div>'+targetname+'</div>';}
var divcentrecontent;
if (redirect === 0){divcentrecontent='<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;color:white;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else {divcentrecontent='<span id="centerholder" style="color:white;z-index:99999999999999999999999999999999;color:white;"></span>';}
var popupHTML = '<div class="popup chatpop">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'</div>'+
divcentrecontent+
' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+
' </a></div>'+
'</div>'+
'</div>'+
'<div class="pages" style="margin-top:-44px;">'+
'<div data-page="datepopup" class="page">'+
'<div class="toolbar messagebar datetoolbar" style="display:none;background-color:red;">'+
' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+
'<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+
'</div>'+
' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+
'</div>'+
' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:#2196f3;">'+
'<input id="datemessageq" placeholder="Message (optional)" style="width: calc(100% - 70px);margin-left:5px;background-color:white;max-height:44px;" type="text">'+
'<a href="#" style="z-index:99999999;height:44px;color:white;background-color:#2196f3;float:left;line-height:44px;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;padding-left:10px;">Send</span></a>'+
'</div>'+
' <div class="toolbar-inner message-inner" style="display:none;background-color:#2196f3;padding-left:0px;padding-right:0px;">'+
'<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:white;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;background-color:red;margin-top:-12px;margin-left:-50px;"><input id="messagearea" type="text" placeholder="Enter Message"><a href="#" class="link sendbutton" style="color:white;margin-right:10px;margin-left:10px;" onclick="sendMessage();">Send</a>'+
'</div>'+
'</div>'+
'<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+
'</div>'+
'<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+
'<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+
'<div class="datearea" style="text-align:center;"></div>'+
'<div class="messages scrolldetect" style="margin-top:100px;">'+
'</div></div></div>'+
'</div></div>';
myApp.popup(popupHTML);
var closedvar = $$('.chatpop').on('popup:close', function () {
clearchatHistory();
});
//existingDate();
//setDate();
$( "#centerholder" ).append(centerdiv);
myApp.sizeNavbars();
//$( "#centerholder" ).remove();
if (datealertvar === false) {
datealertvar = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_type = snapshot.child('type').val();
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
var newtonight = new Date();
newtonight.setHours(23,59,59,999);
var newtonight_timestamp = Math.round(newtonight/1000);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var chatdaystring;
var expiredateobject = new Date((d_chat_expire * 1000) - 86400);
var unixleft = d_chat_expire - newtonight_timestamp;
var daysleft = unixleft / 86400;
//console.log('daysleft' + daysleft);
var weekdaynamew = weekday[expiredateobject.getDay()];
if(daysleft <= 0){chatdaystring = 'Today';}
else if(daysleft === 1){chatdaystring = 'Tomorrow';}
else chatdaystring = weekdaynamew;
//console.log(unixleft);
//console.log(daysleft);
var hoursleft = unixleft / 3600;
var salut;
if (daysleft <=0){
salut='tonight';
}
else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';}
else{salut = 'in ' + daysleft+' days';}
var aftertag;
$( ".datedetailsdiv" ).empty();
$( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+
'<ul style="background-color:#4cd964">'+
'<li>'+
' <div class="item-content" style="padding-left:15px;">'+
'<div class="item-media">'+
'<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+
' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+
' </div>'+
'<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+
// '<div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div> ' );
if (d_time){
var lowertime = d_time.toLowerCase()
if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);}
else {
$( ".chatafternavbar").append(' ' + d_time);}
}
//if (d_interest && d_type =='duck'){
// if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';}
// if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';}
//}
//if (d_interest && d_type =='date'){
//for (i = 0; i < d_interest.length; i++) {
// $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
//}
//}
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_interest = false;
d_chat_expire = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_timestamp = false;
d_message = false;
d_dateseen = false;
d_dateseentime = false;
if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();}
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
//need to check if still matched
}
//alert('triggered');
// if (snapshot.val().response == 'W') {noMessages();
// setDate();dateConfirmationPage();}
// else {chatShow();}
//dateConfirmationPage();
keepopen = 0;
});
}
else {}
}
function scrollBottom(){
var objDiv = document.getElementById("messagediv");
objDiv.scrollTop = objDiv.scrollHeight;
//$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300);
}
function noMessages(){
$( ".messages" ).hide();
$( ".datearea" ).empty();
$( ".datearea" ).append(
'<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+
//'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:20px;color:white;font-family: \'Pacifico\', cursive;"></div>'+
'<div class="requesticon" style="padding-top:20px;"></div>'+
'<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+
'<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:10px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+
'<div class="waitingreply"></div>'+
'<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+
'<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+
' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+
'</div> '+
'<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+
'<div class="buttons-row" style="width:100%;padding-left:10px;padding-right:10px;">'+
' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+
'<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+
'</div>'+
'</div> '+
'<div class="profileyomain profileyo_'+ targetid+'" style="border-top:1px solid #c4c4c4;"></div>'+
'<span class="preloader preloader-white avail-loader" style="margin-top:20px;clear:both;margin-bottom:10px;"></span>'+
'</div>');
if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');}
if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');}
}
function setDate(){
var dateset = 'N';
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
var alldays_values = [];
var alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
alldays_values.push(tonight_timestamp - 1);
alldays_values.push(tonight_timestamp);
alldays_names.push('Now');
alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
alldays_values.push(tomorrow_timestamp);
alldays_names.push('Tomorrow');
for (i = 1; i < 6; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
n = weekday[datz.getDay()];
alldays_names.push(n);
}
pickerCustomToolbar = myApp.picker({
container: '#createdatepicker',
rotateEffect: true,
inputReadOnly: true,
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");},
toolbar:false,
onChange:function(p, value, displayValue){
setTimeout(function(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
}, 1000);
if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');}
},
cols: [
{
displayValues: alldays_names,
values: alldays_values,
},
{
textAlign: 'left',
values: (' Morning Afternoon Midday Evening').split(' ')
},
]
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(snapshot.child('time').val());
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(snapshot.child('chat_expire').val());
}
dateset = 'Y';
if (d_interest && d_type =='date') {
for (i = 0; i < d_interest.length; i++) {
$( "." + d_interest[i] +"_i" ).addClass('interestchosen');
}
}
if (d_interest && d_type =='duck') {
if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");}
if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}}
}
});
$( "#createdatepicker" ).hide();
}
function infoPopup(){
var popupHTML = '<div class="popup">'+
'<div class="content-block">'+
'<p>Popup created dynamically.</p>'+
'<p><a href="#" class="close-popup">Close me</a></p>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
}
function dateUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" );
$( ".notifback" ).show();
$( ".mainback" ).hide();
if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
removetoDate();
}
else{
if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();}
//clicked date
$( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" );
addtoDate();
}
}
function addtoDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialdate = f_date_me.indexOf(targetid);
if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}
}
}
//if button has blue border change the color
}
function removetoDate(){
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function duckUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" );
if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
$( ".notifback" ).show();
$( ".mainback" ).hide();
removetoDuck();
}
else{
if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();}
//clicked duck
$( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" );
addtoDuck();
}
}
function removetoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function markMe(){
var mearray = ["4"];
firebase.database().ref('users/' + f_uid).update({
//add this user to my list
date_me:mearray
});
}
function addtoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_number:first_number,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialduck = f_duck_me.indexOf(targetid);
if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}}
}
}
var singleuserarray = [];
function singleUser(idw,idname,origin){
if (singleuserarray[0] != null){
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="z-index:99999999999999;margin-top:0px;clear:both;margin-bottom:-40px;width:100%;">'+
'<ul style="background-color:transparent" style="width:100%;">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;width:100%;" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div></li>'
);
}
}
}
if (origin){photoBrowser(0,singleuserarray[0].age,1,1);}
else{photoBrowser(0,singleuserarray[0].age);}
}
else{
if (singlefxallowed === false){return false;}
singlefxallowed = false;
targetid = String(idw);
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
//console.log(data);
var result = JSON.parse(data);
var availarraystring='';
var availnotexpired = false;
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){
var availablearrayindividual = JSON.parse(result[0].availstring);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[0].availstring;}
}
var timestampyear = result[0].timestamp.substring(0,4);
var timestampmonth = result[0].timestamp.substring(5,7);
var timestampday = result[0].timestamp.substring(8,10);
var timestamphour = result[0].timestamp.substring(11,13);
var timestampminute = result[0].timestamp.substring(14,16);
var timestampsecond = result[0].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var photosstringarray =[];
var photocount;
var photostring;
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[0].largeurl){
var heightarray = result[0].heightslides.split(",");
var widtharray = result[0].widthslides.split(",");
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[0].largeurl.split(",").length;
photoarrayuserlarge = result[0].largeurl.split(",");
photoarrayusersmall = result[0].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
targetpicture = photoarrayuserlarge[0];
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\''+profilepicstringlarge+'\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368';
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
targetpicture = 'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100';
photocount = 1;
}
var distance = parseFloat(result[0].distance).toFixed(1);
var distancerounded = parseFloat(result[0].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var namescount = result[0].displayname.split(' ').length;
var matchname;
if(namescount === 1){matchname = result[0].displayname;}
else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));}
singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight});
// console.log(singleuserarray);
main_all = new_all;
new_all = singleuserarray;
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+
'<ul style="background-color:transparent">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;" class="item-link item-content" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
}
}
if (origin == 88){
//alert('88');
}
else if (origin == 1){
//alert('99');
photoBrowser(0,singleuserarray[0].age,1,1);
}
else if (!origin){
//alert('100');
photoBrowser(0,singleuserarray[0].age);
}
});
});
}
}
function request(dayw,timeq){
$( ".profileyomain" ).hide();
canloadchat = false;
$( '.picker-items-col-wrapper' ).css("width", "auto");
$( ".requesticon" ).hide();
$( ".dateheader" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
conversation_started = false;
if (d_response == 'Y') {
$( ".date-close" ).hide();
$( ".date2-close" ).show();
$( ".date1-close" ).hide();
}
if (d_response == 'W') {
$( ".date-close" ).hide();
$( ".date1-close" ).show();
$( ".date2-close" ).hide();
}
if(!d_response){
$( ".date-close" ).show();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
}
$( ".messages" ).hide();
$( ".date-button" ).hide();
$( "#createdatepicker" ).show();
$( ".dr" ).hide();
$( ".date-back" ).hide();
if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();}
if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();}
$( ".waitingreply" ).empty();
$( ".datetoolbar" ).slideDown();
$( ".message-inner" ).hide();
$( ".date-inner" ).show();
if (d_response=='Y'){$( "#datemessageq" ).val('');}
// $( ".center-date" ).empty();
// if (d_type=='date') {$( ".center-date" ).append('Date Details');}
// if (d_type=='duck') {$( ".center-date" ).append('Duck Details');}
myApp.sizeNavbars();
//$( "#createdatepicker" ).focus();
$( ".page-content" ).animate({ scrollTop: 0 }, "fast");
if (dayw){
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(dayw);
if (timeq != 'Anytime'){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(timeq);
}
}
}
function noChange(){
myApp.closeModal('.actions-modal');
canloadchat = true;
$( ".sender-inner" ).hide();
$( ".messages" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
$( "#createdatepicker" ).hide();
// $( ".center-date" ).append(targetname);
$( ".nomessages" ).hide();
$( ".date-back" ).show();
$( ".date-button" ).show();
scrollBottom();
myApp.sizeNavbars();
}
function reverseRequest(){
if ($('.availtitle').length > 0){$( ".datetoolbar" ).hide();}
myApp.closeModal('.actions-modal');
$( ".profileyomain" ).show();
$( ".dateheader" ).hide();
$( "#createdatepicker" ).hide();
$( ".dr" ).show();
$( ".date-back" ).show();
$( ".date-row" ).hide();
$( ".duck-row" ).hide();
$( ".date-close" ).hide();
$( ".requesticon" ).show();
$( ".date-inner" ).hide();
if (!d_day){
//$( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
}
}
var message_count = 0;
var messages_loaded = false;
var conversation_started = false;
var prevdatetitle;
function chatShow(){
//fcm();
prevdatetitle = false;
letsload = 20;
canloadchat = true;
additions = 0;
$( ".yes-inner" ).hide();
$( ".sender-inner" ).hide();
$( ".datedetailsdiv" ).show();
message_count = 1;
image_count = 0;
$( ".messages" ).show();
$( ".datearea" ).empty();
$( ".date-back" ).show();
$( ".date-button" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".datetoolbar" ).show();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
//myMessagebar = myApp.messagebar('.messagebar', {
// maxHeight: 200
//});
myMessages = myApp.messages('.messages', {
autoLayout: true,
scrollMessages:true
});
//if (myMessages) {myMessages.clean();}
if (message_history === true){}
if (message_history === false){
message_history = true;
//do the .on call here to keep receiving messages here
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
// $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>');
// $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
// if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');}
}).then(function(result) {
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) {
if (message_count ==1) {lastkey = snapshot.getKey();}
message_count ++;
var checkloaded;
if (existingmessages > 19){checkloaded = 20;}
else if (existingmessages < 20){checkloaded = existingmessages;}
if (message_count == checkloaded){messages_loaded = true;}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
//console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
//my messages
var unix = Math.round(+new Date()/1000);
if (obj.from_uid == f_uid) {
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list" style="margin-top:0px;">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Date Details</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
// Day
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (obj.photo_expiry){
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
// Day
});
image_count ++;
}
}
else {
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// ' and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
if (conversation_started === true) {
$( ".message" ).last().remove();
$( ".message" ).last().addClass("message-last");
$('#buzzer')[0].play();
}
}
//received messages
if (obj.to_uid == f_uid) {
if (messages_loaded === true) {
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
}
});
}
if (conversation_started === true) {
$('#buzzer')[0].play();
}
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Element title</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (!obj.photo_expiry){
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
var seentime = Math.round(+new Date()/1000);
var expirytime = Math.round(+new Date()/1000) + 86400;
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
}
else {
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
}
}
}, function (errorObject) {
});
});
}
//myMessages.layout();
//myMessages = myApp.messages('.messages', {
// autoLayout: true
//});
//myMessages.scrollMessages();
myApp.initPullToRefresh('.pull-to-refresh-content-9');
}
var notifadditions=0;
var notifletsload = 12;
function getmoreNotifs(){
notifadditions ++;
var notifsloaded = notifadditions * 12;
var notif2load = mynotifs.length - (notifadditions * 12);
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
var lasttoaddnotif = notifsloaded + notifletsload;
$(".loadnotifsloader").remove();
for (i = notifsloaded; i < lasttoaddnotif; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
canscrollnotif = true;
}
var letsload = 20;
function getPrevious(){
if (existingmessages === false){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
previousFunction();
})
}
else{previousFunction();}
function previousFunction(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var prevarray = [];
message_count = 0;
additions ++;
$(".previouschats").remove();
var left2load = existingmessages - (additions * 20);
if (left2load > 20) {letsload = 20;} else {letsload = left2load;}
//console.log('existingmessages' + existingmessages);
//console.log('letsload' + letsload);
//console.log('additions' + additions);
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) {
message_count ++;
if (message_count ==1) {lastkey = snapshot.getKey();}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){
//console.log($(".message").length);
if ((letsload < 20) && (message_count == 1) ){
if (messagedaytitle == todaystring){datechatstring = 'Today'}
if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {datechatstring='';}
}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
}
//my messages
if (obj.from_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
//received messages
if (obj.to_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
if (message_count == letsload) {
$(".loadmessagesloader").remove();
canloadchat = true;
myMessages.addMessages(prevarray.slice(0, -1), 'prepend');
//$(".scrollbutton").remove();
//$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
//if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");}
}
}, function (errorObject) {
// console.log("The read failed: " + errorObject.code);
});
}
}
var targetid;
var targetname;
var targetreported;
var targetdatearray,targetduckarray;
var targetdate,targetduck;
var match;
var targetdatelikes, targetducklikes;
var slideheight = $( window ).height();
function getMeta(url){
$("<img/>",{
load : function(){
if (this.height > this.width){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
}
},
src : url
});
}
function backtoProfile(){
myApp.closeModal('.infopopup') ;
$( ".toolbarq" ).hide();
//getMeta(new_all[myPhotoBrowser.activeIndex].url);
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
//$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
//put original image here
$( ".greytag" ).addClass('bluetext');
//$( ".photo-browser-slide img" ).css("height","100%");
$( ".datebutton" ).addClass('imagelibrary');
$( ".duckbutton" ).addClass('imagelibrary');
//$( ".swiper-container-vertical" ).css("height",slideheight + "px");
//$( ".swiper-container-vertical" ).css("margin-top","0px");
//$( ".swiper-slide-active" ).css("height", "600px");
$( ".toolbarq" ).css("background-color","transparent");
$( ".datefloat" ).hide();
$( ".duckfloat" ).hide();
$( ".vertical-pag" ).show();
//$( ".infopopup" ).css("z-index","-100");
$( ".onlineblock" ).hide();
//$( ".orlink" ).show();
//$( ".uplink" ).hide();
//$( ".nextlink" ).hide();
//$( ".prevlink" ).hide();
$( ".prevphoto" ).show();
$( ".nextphoto" ).show();
$( ".nexts" ).hide();
$( ".prevs" ).hide();
$( ".photo-browser-slide" ).css("opacity","1");
//$( ".datebutton" ).css("height","40px");
//$( ".duckbutton" ).css("height","40px");
//$( ".datebutton img" ).css("height","30px");
//$( ".duckbutton img" ).css("height","30px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
$( ".photobrowserbar" ).css("background-color","transparent");
}
var comingback;
function scrollQuestions(){
//console.log($( ".wrapper-questions" ).offset().top);
//console.log($( window ).height());
var offsetline = $( window ).height() - 88;
var offsetdiv = $( ".wrapper-questions" ).offset().top;
//if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);}
var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
//if
// if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");}
//var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
}
function delayYo(){
}
function scrolltoTop(){
$( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 });
}
function questions(origin){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".toolbarq" ).css("background-color","transparent");
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".greytag" ).removeClass('bluetext');
var targetplugin = new_all[myPhotoBrowser.activeIndex].id;
//may need to readd this
//checkMatch(targetplugin);
comingback = 0;
if (origin){comingback = 1;}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();
}
//alert($('.photo-browser-slide img').css('height'));
if ($('.infopopup').length > 0) {
myApp.alert('Something went wrong. Try restarting the app and please report this to us.', 'Oops');
myApp.closeModal('.infopopup');return false;
}
$( ".vertical-pag" ).hide();
$( ".datefloat" ).show();
$( ".duckfloat" ).show();
$( ".datebutton" ).removeClass('imagelibrary');
$( ".duckbutton" ).removeClass('imagelibrary');
//$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)");
//$( ".swiper-container-vertical" ).css("margin-top","-27px");
//$( ".swiper-slide-active" ).css("height","100%");
//$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)");
//$( ".orlink" ).hide();
//$( ".uplink" ).show();
//$( ".nextlink" ).show();
//$( ".prevlink" ).show();
$( ".onlineblock" ).show();
//$( ".datebutton" ).css("height","70px");
//$( ".duckbutton" ).css("height","70px");
//$( ".datebutton img" ).css("height","60px");
//$( ".duckbutton img" ).css("height","60px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
//$( ".nametag" ).removeClass('whitetext');
var photobrowserHTML =
'<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;z-index:12000;" >'+
// ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+
// ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
'<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;">'+
'<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+
'</div>'+
' <div class="swiper-wrapper wrapper-questions" style="">'+
' </div>'+
'</div>'+
'</div>'
myApp.popup(photobrowserHTML,true,false);
$( ".nexts" ).show();
$( ".prevs" ).show();
$( ".prevphoto" ).hide();
$( ".nextphoto" ).hide();
for (i = 0; i < new_all.length; i++) {
var boxcolor,displayavail,availabilityli,availabletext,iconavaill;
iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';
$( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+
//'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+
'<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+
'</h3>'+
'<div onclick="scrolltoTop()" style="z-index:12000;margin-top:15px;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;display:none;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+
'<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+
'<div class="list-block" style="margin-top:0px;clear:both;">'+
'<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Online</div>'+
' <div class="item-input">'+
'<div class="timetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Distance</div>'+
' <div class="item-input">'+
'<div class="distancetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' </ul></div>'+
'</div>'+
'</div>');
//put here
if (new_all[i].description){
$( ".profileul_"+new_all[i].id ).prepend(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].hometown){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input">'+
'<textarea class="resizable" style="min-height:60px;max-height:132px;" readonly>'+new_all[i].hometown+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].industry){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].zodiac){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].politics){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].religion){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].ethnicity){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].eyes){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye Color</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].body){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].height != 0){
if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';}
$(".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+heightset+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].weight != 0){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
var timestring;
var minutevalue;
if (new_all[i].minutes <= 0){timestring = 'Now';}
if (new_all[i].minutes == 1){timestring = '1 minute ago';}
if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';}
if (new_all[i].minutes == 60){timestring = '1 hour ago';}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){
minutevalue = Math.round((new_all[i].minutes / 60));
if (minutevalue == 1) {timestring = '1 hour ago';}
else {timestring = minutevalue + ' hours ago';}
}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';}
if (new_all[i].minutes == 1440){timestring = '1 day ago';}
if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){
minutevalue = Math.round((new_all[i].minutes / 1440));
if (minutevalue == 1) {timestring = '1 day ago';}
else {timestring = minutevalue + ' days ago';}
}
if (new_all[i].minutes >= 10080){timestring = '1 week';}
if (new_all[i].minutes >= 20160){timestring = '2 weeks';}
if (new_all[i].minutes >= 30240){timestring = '3 weeks';}
$( ".timetag_" + new_all[i].id ).html(timestring);
$( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring);
}
swiperQuestions = myApp.swiper('.swiper-questions', {
nextButton:'.nexts',
prevButton:'.prevs',
onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));},
onInit:function(swiper){
myPhotoBrowser.swiper.setWrapperTranslate(0);
$( ".infoprofile").hide();
$( ".adown" ).css( "opacity","1" );
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
$( ".availyope").hide();
//$( ".availyo_"+ new_all[0].id ).show();
if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();}
//checkmatchwashere
//checkMatch(targetid);
},
onSlideChangeStart:function(swiper){
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
if(comingback === 1){
if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();}
if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();}
}
// if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
//}
// else{$( ".prevs" ).removeClass( "disabled" );}
// if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );}
// else{$( ".nexts" ).removeClass( "disabled" );}
//if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
// $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show();
// }
//else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//$( ".adown" ).css( "opacity","1" );
$( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount);
$( ".infoprofile").hide();
$( ".availyope").hide();
//$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%");
//$(".swiper-questions".css("background", "transparent");
$( ".swiper-questions" ).scrollTop( 0 );
if ($('.toolbarq').css('display') == 'block')
{
if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){
//alert(swiper.activeIndex - swiper.previousIndex);
//myPhotoBrowser.swiper.slideTo(0);
myPhotoBrowser.swiper.slideTo(swiper.activeIndex);
//swiper.slideTo(myPhotoBrowser.swiper.activeIndex);
}
}
//checkmatchwashere
//checkMatch(targetid);
}
});
//console.log(myPhotoBrowser.swiper.activeIndex);
swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0);
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".toolbarq" ).show();
comingback = 1;
$( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount);
$( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring);
//if (myPhotoBrowser.swiper.activeIndex === 0){
//myPhotoBrowser.swiper.slideNext();
//myPhotoBrowser.swiper.slidePrev();
//}
//else {
//}
//swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex);
}
function checkMatch(targetid){
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');}
else{$( ".indivnotifcount" ).remove();}
}
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;}
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;}
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function unmatchDate(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
dateUser();
});
}
function unmatchDuck(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
duckUser();
});
}
function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){
allowedchange = true;
photoresize = false;
if ($('.photo-browser').length > 0){return false;}
myApp.closeModal('.picker-sub');
//firebase.database().ref("users/" + f_uid).off('value', userpref);
var photobrowserclass="";
var duckfunction = ""
var datefunction = ""
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";}
else{duckfunction = "createDuck()";datefunction = "createDate1()";}
var to_open = 0;
if ($('.chatpop').length > 0 || chatorigin) {}
else {
to_open = openprofile;
}
var hiddendivheight = $( window ).height() - 40;
//alert(JSON.stringify(new_all));
myPhotoBrowser = myApp.photoBrowser({
zoom: false,
expositionHideCaptions:true,
lazyLoading:true,
lazyLoadingInPrevNext:true,
lazyPhotoTemplate:
'<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide" style="background-color:transparent;">'+
'<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+
'<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px;background-color:transparent;">'+
'<div class="swiper-wrapper vertical-wrapper-swiper">'+
'{{js "this.photos"}}'+
'</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+
'</div>',
exposition:false,
photos: new_all,
captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>',
toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+
' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDate();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDuck()" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-left:15px;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+
'<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+
' <div style="width:50px;overflow-x:hidden;position:absolute;right:1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;margin-left:-1px;">'+
'</div>'+
' </a>'+
' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+
' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-51px;"></div>'+
'</a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
' </div>'+
'</div>',
onClose:function(photobrowser){myApp.closeModal('.actions-modal');hideProfile();
singlefxallowed = true;
viewphotos = false;
viewscroll = false;
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();swiperQuestions = false;}
}
else{myApp.closeModal(); }
if (mainchange){new_all = main_all;singleuserarray = [];}
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
nextButton:'.nextphoto',
prevButton:'.prevphoto',
onSlideChangeStart:function(swiper){
if (allowedchange){
if (photoresize){
if ($('.infopopup').length > 0){}
else{
//getMeta(new_all[swiper.activeIndex].url);
}
}
if (swiper.activeIndex != openprofile){ photoresize = true;}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myApp.closeModal('.actions-modal');
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".duckbutton" ).hide();
$( ".datebutton" ).hide();
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
targetid = new_all[myPhotoBrowser.activeIndex].id;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
checkMatch(targetid);
},
backLinkText: '',
//expositionHideCaptions:true,
navbarTemplate:
// ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+
// ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
// '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+
'<div class="navbar photobrowserbar" style="background-color:#ccc">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
'<i class="pe-7s-angle-left pe-3x matchcolor greytag"></i>'+
'<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor greytag">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" onclick="actionSheet()">' +
//'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor greytag"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
myPhotoBrowser.open();
targetid = new_all[myPhotoBrowser.activeIndex].id;
var mySwiperVertical = myApp.swiper('.swiper-vertical', {
direction: 'vertical',
zoom:'true',
pagination:'.swiper-pagination',
paginationType:'progress',
onSlideChangeStart:function(swiper){
var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(",");
var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(",");
var trueh = verticalheightarray[swiper.activeIndex];
var truew = verticalwidtharray[swiper.activeIndex];;
if (trueh > truew){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else if (trueh == trueh){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else{
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
}
},
onImagesReady:function(swiper){
},
onInit:function(swiper){
//console.log(new_all[myPhotoBrowser.activeIndex]);
//
if (viewphotos){
setTimeout(function(){ backtoProfile();viewphotos = false; }, 100);
}
if (viewscroll){
setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100);
}
},
onClick:function(swiper, event){
questions();
//if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");}
//else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");}
}
});
//var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myPhotoBrowser.swiper.slideTo(to_open,100);
checkMatch(targetid);
questions();
if (openprofile ===0){
if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );}
else{$( ".prevphoto" ).removeClass( "disabled" );}
if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );}
else{$( ".nextphoto" ).removeClass( "disabled" );}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
var target = new_all[myPhotoBrowser.activeIndex].url;
var pretarget = target.replace("https://graph.facebook.com/", "");
targetid = String(pretarget.replace("/picture?width=828", ""));
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
//may need to readd
}
}
function showProfile(){
$( ".profile-info" ).show();
}
function hideProfile(){
$( ".profile-info" ).hide();
}
function dateRequest(){
$( ".dateheader" ).hide();
$( ".date-close" ).hide();
$( ".date-button" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
sendNotification(targetid,2);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck request'}
if (d_type=='date'){smessage = 'Date request'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'daterequest',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
if(d_response=='Y') {chatShow();}
else {reverseRequest();}
});
}
}
var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted;
function existingDate(){
$( ".datearea" ).empty();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Test if user exists
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_type = snapshot.child('type').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
//$( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_message = false;
d_timeaccepted;
d_dateseen = false;
d_dateseentime = false;
d_timestamp = false;
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
});
}
function interests(id){
$( "." + id + "_i" ).toggleClass( "interestchosen" );
}
function sendMessage(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var newmessage = $( "#messagearea" ).val();
if (newmessage === ''){return false;}
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:newmessage,
seen:'N',
timestamp: t_unix,
type: d_type,
param:'message',
authcheck:f_uid
});
myMessages.addMessage({
// Message text
text: newmessage,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
//myMessagebar.clear();
var messageq;
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
//alert('yo3');
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
//alert(obj.param);
// alert(obj.received);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
// alert('param'+obj.param);
// alert('new_message_count'+obj.new_message_count);
if (obj.param =='message'){
messageq = obj.new_message_count;
messageq ++;}
else{
messageq = 1;
}
}
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
}
});
}
newNotification(messageq);
});
function newNotification(messagenum){
//alert('messagenum'+messagenum);
if (!messagenum) {messagenum = 1;}
//alert(messagenum);
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:newmessage,
timestamp: t_unix,
type:d_type,
param:'message',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
$( "#messagearea" ).val('');
$( ".sendbutton" ).removeClass('disabled');
$( ".sendbutton" ).css('color','white');
sendNotification(targetid,4);
}
function clearchatHistory(){
singlefxallowed = true;
messages_loaded = false;
if (main_all[0] != null){
new_all = main_all;
}
singleuserarray = [];
letsload = 20;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if (message_history){
//firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications);
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon);
if(additions>0){
for (i = 0; i < additions.length; i++) {
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history);
}
}
message_history = false;
message_count = 0;
additions = 0;
existingmessages = false;
conversation_started = false;
myMessages.clean();
myMessages.destroy();
}
if (datealertvar === true){
firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert);
}
datealertvar = false;
if ($$('body').hasClass('with-panel-left-reveal')) {
$(".timeline").empty();
rightPanel();
}
if ($$('body').hasClass('with-panel-right-reveal')) {
myList.deleteAllItems();
myList.clearCache();
leftPanel();
}
}
function dateConfirmationPage(details){
$( ".datetoolbar" ).show();
canloadchat = false;
var g = new Date(d_chat_expire*1000 - 3600);
$( ".profileyomain" ).hide();
$( ".avail-loader" ).hide();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var gday = weekday[g.getDay()];
var proposeddate = g.getDate();
var month = [];
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var messageclass;
if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";}
else{messageclass = "message-received";messagestyle="margin-left:70px;";}
var proposedmonth = month[g.getMonth()];
var proposedyear = g.getFullYear();
var dending;
if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'}
else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'}
else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'}
else {dending = 'th'}
$( ".dateheader" ).hide();
$( ".profileroundpic" ).show();
$( ".date1-close" ).hide();
$( ".date2-close" ).hide();
$( ".message-inner" ).hide();
$( ".date-inner" ).hide();
$( ".date-back" ).show();
var timedisplay;
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname.capitalize());
var titleblock;
var namefromdate;
var nametodate;
if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;}
else{nametodate = f_first;namefromdate = targetname;}
var whatrow;
var dateseentitle;
var timestamptitle;
var capitalD;
if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';}
if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';}
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - d_timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (d_dateseen){
var unixago = unixnow - d_dateseentime;
var unixminago = unixago / 60;
if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';}
else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';}
else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 62) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';}
else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';}
}
else{dateseentitle = 'Request not seen yet';}
myApp.sizeNavbars();
var messagedateblock;
if (d_message){
messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>';
}
else {messagedateblock='';}
if (d_time) {timedisplay = ', ' + d_time}
else {timedisplay='';}
if (details){
var junixago = unixnow - d_timeaccepted;
var junixminago = junixago / 60;
var acceptedtitle;
if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';}
else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';}
else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 62) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';}
else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';}
$( ".date1-close" ).hide();
$( ".date2-close" ).show();
$( ".date-close" ).hide();
$( ".date-back" ).hide();
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".waitingreply" ).append(
'<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(capitalD + ' confirmed');
$( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type);
}
else if (d_created_uid == f_uid) {
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html('Waiting for '+targetname+' to respond');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
else{
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
$( ".datetoolbar" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).show();
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(targetname+' is waiting for your response');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
if (d_interest && d_type =='duck'){
$( ".interestli").show();
if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
}
if (d_interest && d_type =='date'){
for (i = 0; i < d_interest.length; i++) {
$( ".interestli").show();
$( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
}
}
}
function acceptDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
sendNotification(targetid,3);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
//console.log(messageq);
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:'Date scheduled',
timestamp: t_unix,
type:d_type,
param:'dateconfirmed',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {chatShow();});
}
}
function cancelDate(){
// Create a reference to the file to delete
$( ".dateheader" ).hide();
$( ".sender-inner" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Delete the file
firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() {
// File deleted successfully
$( ".datearea" ).empty();
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_created_uid = false;
d_timestamp = false;
d_dateseen = false;
d_dateseentime = false;
d_message = false;
noMessages();
setDate();
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
// Delete the file
firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() {
// File deleted successfully
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
sendNotification(targetid,6);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck cancelled'}
if (d_type=='date'){smessage = 'Date cancelled'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'datedeleted',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
}
function getPicture(key){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var t_unix = Math.round(+new Date()/1000);
var returned = 0;
var postkeyarray = [];
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var eventy = document.getElementById('takePictureField_').files[0];
// var number_of_pictures = $(".imageli").length + 1;
if (eventy == 'undefined') {}
if (eventy !== 'undefined') {
for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) {
var photoname = t_unix + i;
var newValue = firebase.database().ref().push().key;
postkeyarray.push(newValue);
myMessages.addMessage({
// Message text
text: '<img class="disabled image_'+newValue+'" src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup(\''+newValue+'\');" style="display:none;-webkit-filter: blur(50px);">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
//$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy));
image_count ++;
//$('.image_' + t_unix).onclick = function(){
// openPhoto(url);};
//var randomstring = (Math.random() +1).toString(36).substr(2, 30);
var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname;
var photostorage = 'images/' + f_auth_id + '/' + photoname;
var photochatsRef = storageRef.child(photostorage);
photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) {
var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name;
var photodownloadRef = storageRef.child(photodownloadstorage);
photodownloadRef.getDownloadURL().then(function(url) {
returned ++;
var newPostKey = postkeyarray[(returned-1)];
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var chatvar = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >',
seen:'N',
timestamp: snapshot.metadata.name,
type:d_type,
param:'image',
downloadurl:url,
first_number:first_number,
second_number:second_number
};
var photovar1 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
photo_name:photostorage,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number,
folder:f_auth_id
};
var photovar2 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number
};
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar);
firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1);
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2);
$(".image_"+newPostKey).attr("src", url);
$('.image_'+ newPostKey).removeClass("disabled");
$('.image_'+ newPostKey).css("-webkit-filter","none");
});
});
}
sendNotification(targetid,5);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
//console.log(obj.received);
//console.log(obj.from_uid);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newpictureNotification(messageq);
});
}
function newpictureNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:'Image ',
timestamp: t_unix,
type:d_type,
param:'image',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
}
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
var photoarray;
function showPhotos(){
photoarray= [];
myApp.pickerModal(
'<div class="picker-modal photo-picker" style="height:132px;">' +
'<div class="toolbar" style="background-color:#2196f3">' +
'<div class="toolbar-inner">' +
'<div class="left"></div>' +
'<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' +
'</div>' +
'</div>' +
'<div class="picker-modal-inner" style="background-color:#2196f3">' +
'<div class="content-block" style="margin:0px;padding:0px;">' +
'<div class="swiper-container swiper-photos">'+
'<div class="swiper-wrapper wrapper-photos">'+
' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+
'<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+
' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;background-color:red;height:88px;margin-top:-44px;" multiple="multiple"> '+
'</div>'+
'</div>'+
'</div>'+
'</div>' +
'</div>' +
'</div>'
);
var photosswiper = myApp.swiper('.swiper-photos', {
slidesPerView:3,
freeMode:true,
preloadImages: false,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true
//pagination:'.swiper-pagination'
});
firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) {
var childcount = 0;
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
//var key = childSnapshot.key;
// childData will be the actual contents of the child
childcount ++;
var childData = childSnapshot.val();
photoarray.push(childSnapshot.val());
$( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+
' <div class="swiper-lazy-preloader"></div>'+
'</div>');
if (childcount == snapshot.numChildren()){
photosswiper.updateSlidesSize();
photosswiper.slideTo(snapshot.numChildren());
// photosswiper.slideTo(0);
}
});
});
}
function sendphotoExisting(oldurl,filenamez){
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
myMessages.addMessage({
// Message text
text: '<img src="'+oldurl+'" onload="scrollBottom();">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first
// Day
// day: !conversationStarted ? 'Today' : false,
// time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
});
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+oldurl+'" onload="scrollBottom();">',
seen:'N',
timestamp: t_unix,
type:d_type,
param:'image',
filename:filenamez
});
myApp.closeModal('.photo-picker');
}
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
var xcountdown;
function imagesPopup(go){
if ($('.gallery-popupz').length > 0) {return false;}
var goz;
var popupHTML = '<div class="popup gallery-popupz">'+
'<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+
' <div class="center gallerytitle"></div>'+
' <div class="right photo-count"></div>'+
'</div>'+
'</div>'+
'<div class="pages">'+
'<div data-page="gallerypopup" class="page">'+
'<div class="page-content" style="background-color:white;">'+
'<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+
'<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+
'<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+
' <div class="swiper-wrapper gallery-wrapper">'+
' </div>'+
'</div>'+
'<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+
'</div></div></div>'+
'</div>';
myApp.popup(popupHTML);
var first_number,second_number;
var gallerycount;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var galleryimagecount = 0;
var photodeletetime;
var phototo;
var photofrom;
var photochatid;
var touid;
firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value")
.then(function(snapshot) {
gallerycount = snapshot.numChildren();
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if (obj.id == go){goz = galleryimagecount;}
var expiryval;
if (obj.photo_expiry == null){expiryval = i;}
else {expiryval = obj.photo_expiry;}
$( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+
'<div class="swiper-zoom-container">'+
'<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+
' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>');
galleryimagecount ++;
});
var galleryswiper = myApp.swiper('.swiper-gallery', {
preloadImages: false,
lazyLoadingInPrevNext:true,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true,
zoom:true,
onInit:function(swiper){var slidenum = swiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
},
onSlideChangeStart:function(swiper){clearInterval(xcountdown);
var slidenum = galleryswiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();deletePhotochat();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
myApp.sizeNavbars();
},
pagination:'.swiper-pagination-gallery',
paginationType:'progress'
});
galleryswiper.slideTo(goz,0);
myApp.sizeNavbars();
});
function deletePhotochat(){
if (photodeletetime < (new Date().getTime() / 1000)){
$( ".photochat_"+ photodeletetime).remove();
galleryswiper.update();
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
}
}
function photodeletecount(){
var countDownDate = new Date(photodeletetime * 1000);
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h "
+ minutes + "m " ;
// Update the count down every 1 second
xcountdown = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(xcountdown);
deletePhotochat();
}
else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h "
+ minutes + "m " ;myApp.sizeNavbars();}
}, 60000);
}
}
function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();}
function closeGallery(){
myApp.closeModal('.gallery-popupz');
clearInterval(xcountdown);
}
function updateOnce(){
var uids = ["1381063698874268","1394352877264527","393790024114307","4"];
firebase.database().ref('users/' + f_uid).update({
date_me:uids
});
}
function updatePhotos(){
$( ".pp" ).each(function() {
var classList = $(this).attr("class").split(' ');
var idofphoto = classList[2].replace("photo_", "");
var index1 = f_date_match.indexOf(idofphoto);
var index2 = f_duck_match.indexOf(idofphoto);
var u_date_me = f_date_me.indexOf(idofphoto);
var u_to_date = f_to_date.indexOf(idofphoto);
var u_duck_me = f_duck_me.indexOf(idofphoto);
var u_to_duck = f_to_duck.indexOf(idofphoto);
if (index2 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='duck';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else if (index1 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='date';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" );
$( ".iconpos_" + idofphoto ).empty();
$( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" );
if (u_date_me > -1){
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if (u_duck_me > -1) {
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if ($( '.rr').hasClass('r_' + idofphoto)) {
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
// alert(u_date_me);
// alert(u_duck_me);
if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" );
}
else {$( ".datebutton" ).removeClass( "likesme" );}
if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" );
}
else {$( ".duckbutton" ).removeClass( "likesme" );}
}
}
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
function singleBrowser(idw,idname,origin){
//firebase.database().ref("users/" + f_uid).off('value', userpref);
//targetid = idw;
targetid = String(idw);
targetname = idname;
var dbuttons;
if (origin){
dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
else {
dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
singlePhotoBrowser = myApp.photoBrowser({
zoom: 400,
lazyLoading:true,
lazyLoadingInPrevNext:true,
//exposition:false,
photos: [{
url: 'https://graph.facebook.com/'+targetid+'/picture?type=large',
caption: '...'
}],
toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+
dbuttons+
' <div class="toolbar-inner toolbardecide">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+
' <a href="#" class="link orlink">'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+
' </a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+
' </div>'+
'</div>',
onOpen:function(photobrowser){
$( ".chatpop" ).css( "z-index","10000" );},
onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" );
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
backLinkText: '',
navbarTemplate: '<div class="navbar photobrowserbar">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
// ' <i class="icon icon-back {{iconsColorClass}}"></i> '+
'<i class="pe-7s-angle-left pe-3x"></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
' <i class="pe-7s-angle-left pe-3x "></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" >' +
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
singlePhotoBrowser.open();
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>');
var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "width", windowwidth + "px" );
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} )
.done(function( data ) {
var result = JSON.parse(data);
var targetdescription= result[0].description;
//var targetname = result[0].name.substr(0,result[0].name.indexOf(' '));
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
});
}).catch(function(error) {
// Handle error
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function deletePhotos(){
var unix = Math.round(+new Date()/1000);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
$.each(objs, function(i, obj) {
$.each(obj, function(i, obk) {
if(obk.photo_expiry){
if (obk.photo_expiry < Number(unix)){
//alert('a photo to delete exists');
firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
}).catch(function(error) {
});
//blocking out
}
}
});
});
}
});
}
function createDuck(idq,nameq,redirect){
keepopen = 1;
d_type = 'duck';
if (idq) {createDate(idq,nameq,redirect)}
else{createDate();}
}
function createDate1(idz,name,redirect){
d_type = 'date';
keepopen = 1;
if (idz) {createDate(idz,name,redirect)}
else{createDate();}
}
function duckClass(place){
if (place ==1) {
if ($( ".button-my" ).hasClass( "active" )){
$('.button-my').removeClass("active");$('.button-your').removeClass("active");
}
else {$('.button-my').addClass("active");$('.button-your').removeClass("active");}
}
if (place ==2) {
if ($( ".button-your" ).hasClass( "active" )){
$('.button-your').removeClass("active");$('.button-my').removeClass("active");
}
else {$('.button-your').addClass("active");$('.button-my').removeClass("active");}
}
}
function matchNotif(){
function newNotificationm(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'New match'}
if (d_type=='date'){smessage = 'New match'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'newmatch',
new_message_count:0,
received:'N',
expire:'',
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
sendNotification(targetid,1);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq = 0;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotificationm(messageq);
});
}
function unmatchNotif(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref('dates/' + f_uid +'/' + targetid).remove();
firebase.database().ref('dates/' + targetid +'/' + f_uid).remove();
firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove();
firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove();
myApp.closePanel();
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
function insertAfterNthChild($parent, index, content){
$(content).insertBefore($parent.children().eq(index));
}
//function changeRadius(number){
//$('.radiusbutton').removeClass('active');
//$('#distance_'+ number).addClass('active');
//processUpdate();
//}
function sortBy(number){
var relevanticon;
var relevanttext;
//if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.sortbutton').removeClass('active');
$('.sortby_'+ number).addClass('active');
if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';}
if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';}
if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';}
firebase.database().ref('users/' + f_uid).update({
sort:sortby
});
}
function addcreateDate(){
$('.left-title').text(f_duck_match_data.length + 'want to date you');
myApp.sizeNavbars();
$('.timeline-upcoming').empty();
for (i = 0; i < f_date_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fdateicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
for (i = 0; i < f_duck_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fduckicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){
$('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>');
}
}
function unblock(){
myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () {
var iblockedfirst = [];
var iblockedsecond = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)}
if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)}
});
}
if (iblockedfirst.length){
for (i = 0; i < iblockedfirst.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
}
}
if (iblockedsecond.length){
for (i = 0; i < iblockedsecond.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
}
}
getWifilocation();
$( ".blockbutton" ).addClass('disabled');
})
});
}
function deleteAccount(){
//users
//photos2delete -> photos in storage
//chats
//matches
myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () {
var matchesarray = [];
var firstnumberarray = [];
var secondnumberarray = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);});
for (i = 0; i < matchesarray.length; i++) {
var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]);
mymatches.remove().then(function() {
//console.log("My matches Remove succeeded.")
})
.catch(function(error) {
//console.log("My matches Remove failed: " + error.message)
});
var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid);
theirmatches.remove().then(function() {
//console.log("Their matches Remove succeeded.")
})
.catch(function(error) {
//console.log("Their matches Remove failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]);
mydates.remove().then(function() {
//console.log("My dates Remove succeeded.")
})
.catch(function(error) {
//console.log("My dates Remove failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("Their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("Their dates Remove failed: " + error.message)
});
var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
}
}
firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//console.log(objs);
if (snapshot.val()){
$.each(objs, function(i, obj) {
var targetdeleteid;
if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;}
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
});
}
firebase.database().ref('users/' + f_uid).set({
auth_id : f_auth_id,
deleted:'Y'
});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
//console.log(data);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objr = snapshot.val();
if (snapshot.val()){
$.each(objr, function(i, obj) {
$.each(obj, function(i, obk) {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
}).catch(function(error) {
//console.log(error);
});
});
});
}
FCMPlugin.unsubscribeFromTopic(f_uid);
cordova.plugins.notification.badge.set(0);
var loginmethod = window.localStorage.getItem("loginmethod");
if (loginmethod == '1'){logoutPlugin();}
else{logoutOpen();}
});
});
}).catch(function(error) {
// Handle error
});
});
});
});
}
function matchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#2196f3");
$( ".matchcolor" ).addClass('whitetext');
}
else {$( ".toolbarq" ).hide();}
}
function unmatchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".matchcolor" ).removeClass('whitetext');
$( ".toolbarq" ).css("background-color","transparent");
}
else {$( ".toolbarq" ).hide();}
}
var notifloaded = false;
function establishNotif(){
if(notifcount) {firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) {
var notificationscount = 0;
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if (obj.to_uid == f_uid) {
if (obj.received =='Y') {
if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();}
}
if (obj.received =='N') {
var addnumber;
if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;}
else {addnumber = obj.new_message_count}
notificationscount = notificationscount + addnumber;
if (notifloaded){
if (obj.new_message_count > 0){
//alert('Not received, greater than 0 = ' +obj.new_message_count);
$( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');
$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');
cordova.plugins.notification.badge.set(notificationscount);
}
}
}
}
});
notifloaded = true;
//Update SQL notifcount
if (notificationscount !=0){
if (offsounds == 'Y'){}else{
$('#buzzer')[0].play();
//if ($('.chatpop').length > 0) {}
//else {$('#buzzer')[0].play();}
}
return false;
}
else{}
//$( ".notifspan" ).empty();
//$( ".notifspan" ).append(notificationscount);
}
});
}
function showPloader(){
$( ".ploader" ).css("z-index","9999999");myApp.closeModal();
}
function hidePloader(tabb){
var popupHTML = '<div class="popup prefpop">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab1" class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Terms and Conditions of Use</div>'+
' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-1" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner terms-inner" >'+
' </div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div id="tab2" class="view tab">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Privacy Policy</div>'+
' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-2" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner privacy-inner">'+
' </div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
'<div class="toolbar tabbar" style="padding:0px;background-color:#ccc;">'+
' <div class="toolbar-inner" style="padding:0px;">'+
' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+
' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-look pe-lg"></i></a>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
$( ".ploader" ).css("z-index","10000");
if (tabb) {
tabTwo();
}
else {tabOne();}
}
function tabOne(){
$( "#tab1" ).addClass('active');
$( "#tab2" ).removeClass('active');
myApp.sizeNavbars();
$( ".tab1" ).addClass('active');
$( ".tab2" ).removeClass('active');
$.get( "http://www.dateorduck.com/terms.html", function( data ) {
$( ".terms-inner" ).html(data);
});
}
function tabTwo(){
$( "#tab1" ).removeClass('active');
$( "#tab2" ).addClass('active');
myApp.sizeNavbars();
$( ".tab1" ).removeClass('active');
$( ".tab2" ).addClass('active');
$.get( "http://www.dateorduck.com/privacy.html", function( data ) {
$( ".privacy-inner" ).html(data);
});
}
//check if on mobile
//}
var pagingalbumurl;
var pagingurl;
var photonumber;
var albumend;
var addedsmallarray;
var addedlargearray;
var addedheight = [];
var addedwidth = [];
function getPhotos(albumid){
$( ".photoloader").show();
$( ".loadmorebuttonphotos").hide();
var retrieveurl;
if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/v2.4/'+albumid+'/photos?limit=8&fields=id,source,width,height&access_token=' + f_token}
else {retrieveurl = pagingurl}
$.getJSON(retrieveurl,
function(response) {
$( ".swipebuttondone").addClass("disabled");
$( ".photoloader").hide();
if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;}
//console.log(response);
pagingurl = response.paging.next;
for (i = 0; i < response.data.length; i++) {
var alreadyselected = addedsmallarray.indexOf(response.data[i].source);
//console.log(response.data[i]);
if (alreadyselected == -1) {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>');
}
else {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>');
}
photonumber ++;
}
if (response.data.length > 0 && response.data.length < 8) {
$( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();}
else{$( ".loadmorebuttonphotos").show();}
});
}
function closePhotos(){
$( ".albumblock").show();
$( ".leftalbum").show();
$( ".leftphoto").hide();
$( "#nomorephotos").hide();
$( "#nophotosfound").hide();
$( ".loadmorebuttonphotos").hide();
if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();}
else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();}
swiperPhotos.removeAllSlides();
swiperPhotos.destroy();
photonumber = 0;
pagingurl = false;
}
function closeAlbums(){
myApp.closeModal('.photopopup');
addedsmallarray = [];
addedlargearray = [];
pagingalbumurl = false;
albumend = false;
$( ".swipebuttondone").removeClass("disabled");
}
function photosPopup(){
photosliderupdated = false;
addedsmallarray = f_smallurls;
addedlargearray = f_largeurls;
var popupHTML = '<div class="popup photopopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" onclick="closeAlbums()" style="margin-left:-10px;"></i>'+
'<i class="pe-7s-angle-left pe-3x leftphoto" onclick="closePhotos()" style="display:none;margin-left:-10px;"></i>'+
' </div>'+
' <div class="center photocount">'+
'0 photos selected'+
'</div>'+
' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="photospage" class="page">'+
' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+
'<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="list-block media-list albumblock" style="margin:0px;z-index:999999;"><ul class="albumul" style="z-index:99999999999;"></ul></div>'+
'<div class="swiper-container swiper-photos">'+
' <div class="swiper-wrapper" >'+
'</div>'+
'</div>'+
'<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more albums</a>'+
'<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more photos</a>'+
'<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+
'<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+
'<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
photoPermissions();
}
function loadAlbums(){
$( ".photoloader").show();
$( ".loadmorebuttonalbums").hide();
var retrievealbumurl;
if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/v2.4/'+f_uid+'/albums?limit=20&fields=id,count,name&access_token=' + f_token}
else {retrievealbumurl = pagingalbumurl}
$.getJSON(retrievealbumurl,
function(response) {
if(response.data.length == 0){
myApp.alert('Upload photos to Facebook to make them available to use in this app.', 'No photos are available');myApp.closeModal('.photopopup');return false;
}
pagingalbumurl = response.paging.next;
if (response.data.length > 0){
for (i = 0; i < response.data.length; i++) {
$( ".albumul" ).append(
' <li onclick="getAlbum('+response.data[i].id+')">'+
' <div class="item-content">'+
' <div class="item-media">'+
' <i class="pe-7s-photo-gallery pe-lg"></i>'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">'+response.data[i].name+'</div>'+
' <div class="item-after">'+response.data[i].count+'</div>'+
'</div>'+
'</div>'+
' </div>'+
' </li>'
);
}
}
if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();$( ".photoloader").hide();albumend = true;}
else{$( ".loadmorebuttonalbums").show();}
});
}
function getAlbum(albumid){
$( ".albumblock").hide();
$( ".loadmorebuttonalbums").hide();
$( "#nomorealbums").hide();
$( ".leftalbum").hide();
$( ".leftphoto").show();
swiperPhotos = myApp.swiper('.swiper-photos', {
slidesPerView:2,
slidesPerColumn:1000,
virtualTranslate:true,
slidesPerColumnFill:'row',
spaceBetween: 3,
onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$( ".noparray").hide();
$( ".yesparray").show();
if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
var indexdeletedsm = addedsmallarray.indexOf(smallurl);
addedsmallarray.splice(indexdeletedsm, 1);
var indexdeletedsl = addedlargearray.indexOf(smallurl);
addedlargearray.splice(indexdeletedsl, 1);
addedheight.splice(indexdeletedsl, 1);
addedwidth.splice(indexdeletedsl, 1);
//console.log(addedheight);
}
else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
addedsmallarray.push(smallurl);
addedlargearray.push(largeurl);
var widthselected = $( ".width_"+photoselectedid).val();
var heightselected = $( ".height_"+photoselectedid).val();
addedheight.push(heightselected);
addedwidth.push(widthselected);
}
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
}
});
getPhotos(albumid);
swiperPhotos.updateContainerSize();
swiperPhotos.updateSlidesSize();
}
function getPhotoURL(){
photonumber = 0;
pagingurl = false;
pagingalbumurl = false;
albumend = false;
var newsmall = addedsmallarray.toString();
var newlarge = addedlargearray.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
$( ".swipebuttondone").removeClass("disabled");
if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');}
}
if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');}
}
updatephotoslider();
//swiperPhotos.removeAllSlides();
//swiperPhotos.destroy();
myApp.closeModal('.photopopup');
});
}).catch(function(error) {
// Handle error
});
}
var photosliderupdated;
function updatephotoslider(){
$( ".yesparray").addClass("disabled");
if (photosliderupdated){return false;}
photosliderupdated = true;
myswiperphotos.removeAllSlides();
if (addedlargearray.length > 0){
myswiperphotos.removeAllSlides();
for (i = 0; i < addedlargearray.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (addedlargearray.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
addedsmallarray = [];
addedlargearray = [];
}
else {
myswiperphotos.removeAllSlides();
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
}
}
function reorderPhotos(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var popupHTML = '<div class="popup redorderpopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" style="margin-left:-10px;" onclick="closeReorder()"></i>'+
' </div>'+
' <div class="center">'+
'Order Photos'+
'</div>'+
' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="redorderpage" class="page">'+
' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+
' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+
' <ul class="numbersul" style="background-color:transparent;">'+
' </ul>'+
'</div>'+
' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+
' <ul class="sortableul">'+
' </ul>'+
'</div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
for (i = 0; i < f_largeurls.length; i++) {
$( ".numbersul" ).append(
'<li style="margin-top:10px;">'+
' <div class="item-content" style="height:80px;">'+
'<div class="item-inner reorderinner">'+
' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+
'</div>'+
' </div>'+
'</li>'
);
$( ".sortableul" ).append(
' <li style="margin-top:10px;">'+
' <div class="item-content sortdivb" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+
' </div>'+
' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+
' </li>'
);
}
myApp.sortableOpen();
}
function closeReorder(){
myApp.closeModal('.redorderpopup');
}
function changeOrder(){
var newurl = [];
$( ".sortdivb" ).each(function() {
var bg = $(this).css("background-image");
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
newurl.push(bg);
});
myswiperphotos.removeAllSlides();
for (i = 0; i < newurl.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Remove</div></div>');
}
myApp.closeModal('.redorderpopup');
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
var newsmall = newurl.toString();
var newlarge = newurl.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
f_largeurls = newurl;
}
function deleteAllPhotos(){
myApp.confirm('Are you sure?', 'Remove all photos', function () {
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
deletedphoto = false;
myswiperphotos.removeAllSlides();
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.update();
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
f_largeurls = [];
f_smallurls = [];
var newsmall = "";
var newlarge = "";
var newwidth = "";
var newheight = "";
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
//console.log('deleted all');
});
}).catch(function(error) {
// Handle error
});
});
}
var f_smallurls = [];
var f_largeurls = [];
var photosloaded;
function swipePopup(chosen){
$( '.picker-sub' ).hide();
myApp.closeModal('.picker-sub');
photosloaded = false;
var sliderwidth = $( document ).width();
var sliderheight = $( document ).height();
var popupHTML = '<div class="popup prefpop" style="z-index:11000">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab99" class="view-99 view tab active">'+
//
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left" style="color:white;"></div>'+
' <div class="center swipetext" style="color:white;">Availability'+
//'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+
'</div>'+
' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange swipebuttondone">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange swipebuttondone">Done</a></div>'+
'</div>'+
'</div>'+
' <div class="pages">'+
' <div data-page="home-3" class="page">'+
'<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;z-index:9999999999;position:absolute;bottom:0px;">'+
' <div class="toolbar-inner" style="padding:0;">'+
// ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan0 " onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan1" onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>'+
'</div>'+
' <div class="page-content" style="height: calc(100% - 44px);background-color:white;">'+
'<div class="swiper-container swiper-prefer" style="padding-top:54px;margin-bottom:-44px;">'+
'<div class="swiper-wrapper">'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-0">'+
'<div class="list-block media-list availblock" style="margin-bottom:0px;margin-top:0px;">'+
' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+
' </ul>'+
'<div class="list-block-label hiderowpref" style="margin-top:10px;">Make it easier for your matches to organise a time to meet you.</div>'+
'</div> '+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-1">'+
'<div style="background-color:transparent;width:100%;padding-bottom:10px;" class="registerdiv">'+
'<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul class="aboutul">'+
'<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+
'<li class="newam" style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">I am</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="newme">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">Preference</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe2">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="align-top hiderowpref">'+
' <div class="item-content">'+
//'<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="item-inner">'+
'<div class="item-title label">About Me</div>'+
' <div class="item-input">'+
' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="width: calc(100% - 40px);min-height:88px;max-height:176px;" placeholder="Hide"></textarea>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:12px;margin-top:-20px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+
' <li class="hiderowpref hometownli" style="clear:both;margin-top:0px;">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input hometown-input">'+
' <textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Status</div>'+
' <div class="item-input status-div">'+
' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input industry-div">'+
' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input zodiac-div">'+
' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input politics-div">'+
' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input religion-div">'+
' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input ethnicity-div">'+
' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye color</div>'+
' <div class="item-input eyes-div">'+
' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input body-div">'+
' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input height-div">'+
' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input weight-div">'+
' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">All fields are optional and will be hidden on your profile unless completed.</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-2">'+
'<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;top:50%;position: absolute;left: 50%;margin-left: -28.7px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+
'<div class="swiper-wrapper wrapper-photos">'+
'</div>'+
'<div class="swiper-pagination"></div>'+
'</div>'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+
' <div class="buttons-row">'+
'<a href="#" class="button active" onclick="photosPopup();" style="font-size:17px;border:0;border-radius:0px;background-color:#4cd964;margin-left:5px;margin-right:5px;">Add</a>'+
'<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;">Re-order</a>'+
'<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;background-color:#ff3b30;color:white">Clear</a>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul">'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">Photos can be uploaded from your Facebook account.</div>'+
'</ul></div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-3">'+
'<div class="content-block-title" style="margin-top:20px;">Search options</div>'+
// '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+
// '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+
// '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+
// '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+
// '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+
//'</p>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;">Search radius</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="distance-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;"></div>'+
' <div class="item-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>'+
'<div class="content-block-title" style="margin-top:-54px;">Sounds</div>'+
' <div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner" style="float:left;">'+
'<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:17px;font-weight:normal;">Turn off sounds</div>'+
' <div class="item-input" style="width:52px;float:left;">'+
'<label class="label-switch">'+
' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+
'<div class="checkbox" ></div>'+
' </label>'+
' </div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="font-size:17px;border:0;border-radius:0px;">Unblock all </div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">My Account</div>'+
'<li onclick="logout()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title active button" style="border:0;border-radius:0px;font-size:17px;">Logout</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
' <li onclick="deleteAccount()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button" style="font-size:17px;border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'</ul>'+
'</div> '+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
//tabs
'</div>'+
'</div>'+
//tabs
'</div>';
myApp.popup(popupHTML);
if (blocklist){
if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');}
}
if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');}
if(!sexuality){
$( ".swipetoolbar" ).hide();
}
//if (radiussize) {distancepicker.cols[0].setValue(radiussize);}
distancepicker = myApp.picker({
input: '#distance-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + ($( document ).width()/2) + "px");distancepicker.cols[0].setValue(radiussize);distancepicker.cols[1].setValue(radiusunit);if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onClose:function (p, values, displayValues){radiussize = distancepicker.value[0];
radiusunit = distancepicker.value[1];},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Search Distance'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100').split(' ')
},
{
textAlign: 'left',
values: ('Kilometres Miles').split(' ')
},
]
});
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var findustrypicker = myApp.picker({
input: '#f-industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (f_industry_u) {findustrypicker.cols[0].setValue(f_industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#f-industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'f_industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
$( ".slide-pref" ).hide();
mySwiper = myApp.swiper('.swiper-prefer', {
onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );},
onInit:function(swiper){$( ".swipetoolbar" ).show();$( ".pan" + swiper.activeIndex ).addClass('active');},
onSlideChangeStart:function(swiper){
$( ".page-content" ).scrollTop( 0 );
$( ".tab-swipe").removeClass('active');
$( ".pan" + swiper.activeIndex ).addClass('active');
if (swiper.activeIndex == 0){$( ".swipetext" ).text('Availability');
$( ".slide-pref" ).hide();$( ".pref-0").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 1){$( ".swipetext" ).text('Profile');
$( ".slide-pref" ).hide();$( ".pref-1").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 2){$( ".swipetext" ).text('Photos');getData();
$( ".slide-pref" ).hide();$( ".pref-2").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 3){$( ".swipetext" ).text('Settings');
$( ".slide-pref" ).hide();$( ".pref-3").show();$( ".swipetoolbar" ).show();
}
if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();}
}
});
swipePref(chosen);
setTimeout(function(){ $( ".swipetoolbar" ).show(); }, 3000);
myApp.sizeNavbars();
var dateinfo = [];
var s_namesonly = [];
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var daynumber;
var todayday = weekday[d.getDay()];
//console.log(todayday);
s_namesonly.push(todayday);
var f_available_array;
var s_alldays_values = [];
var s_alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
daynumber;
daynumber = d.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear());
s_alldays_values.push(tonight_timestamp);
s_alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
var tomorrowdate = new Date(Date.now() + 86400);
var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000);
var tomorrowday = weekday[tomorroww.getDay()];
daynumber = tomorroww.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear());
//console.log('tomorrow is' + tomorrowday);
s_namesonly.push(tomorrowday);
s_alldays_values.push(tomorrow_timestamp);
s_alldays_names.push('Tomorrow');
for (i = 1; i < 7; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
s_alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
daynumber = datz.getDate();
var dending;
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
n = weekday[datz.getDay()];
qqq = weekday[datz.getDay() - 1];
//console.log(n);
s_alldays_names.push(n + ' ' + daynumber + dending);
dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear());
s_namesonly.push(n);
}
s_namesonly.push(n);
//console.log(s_namesonly);
//console.log(s_alldays_values);
for (i = 0; i < s_alldays_names.length; i++) {
if (i==0 | i==2 || i==4 || i==6){
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
else if (i==1 || i==3 || i==5 || i==7) {
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
'<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
var alreadyavailchosen = 0;
var columnone;
var columntwo;
var idtochange;
for(var k = 0; k < availarray.length; k++) {
if (availarray[k].id == s_alldays_values[i]){
alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day;
idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); }
else{
alreadyavailchosen = 0;
}
}
function setPicker(){
var myavailpicker = myApp.picker({
input: '#picker' + s_alldays_values[i],
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (s_namesonly[i] + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
}
if (myphotosarray){
}
else {
}
if (f_description){
$( "#userdescription" ).val(f_description);
var inputlengthd = $( "#userdescription" ).val().length;
$( "#maxdescription" ).text(inputlengthd + ' / 100 ');
}
if (radiussize){
$( ".radiusbutton" ).removeClass( "active" );
$( "#distance_" + radiussize ).addClass( "active" );
}
if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);}
else{$('#soundnotif').prop('checked', false);}
if (f_age) {$( ".savebutton" ).removeClass('disabled');}
if (!sexuality){$( "#distance-input" ).val( '100 Kilometres');}
else {$( "#distance-input" ).val( radiussize + ' ' +radiusunit);
}
if(hometown_u){$( "#homesearch" ).val( hometown_u );}
if(industry_u){$( "#industry-input" ).val( industry_u );}
if(status_u){$( "#status-input" ).val( status_u );}
if(politics_u){$( "#politics-input" ).val( politics_u );}
if(eyes_u){$( "#eyes-input" ).val( eyes_u );}
if(body_u){$( "#body-input" ).val( body_u );}
if(religion_u){$( "#religion-input" ).val( religion_u );}
if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );}
if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );}
if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );}
if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
$( "#height-input" ).val( heightset );
}
if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );}
if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );}
pickerDescribe = myApp.picker({
input: '#picker-describe',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onOpen: function (p){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.picker-items-col').eq(0).css('width','50%');
$('.picker-items-col').eq(1).css('width','50%');
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
var gendercol = pickerDescribe.cols[0];
var agecol = pickerDescribe.cols[1];
if (f_age) {agecol.setValue(f_age);}
if (f_gender) {gendercol.setValue(f_gender);}
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
formatValue: function (p, values, displayValues) {
return displayValues[0] + ', ' + values[1];
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'I Am'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Male Female').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
pickerDescribe2 = myApp.picker({
input: '#picker-describe2',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
$('.picker-items-col').eq(0).css('width','33%');
$('.picker-items-col').eq(1).css('width','33%');
$('.picker-items-col').eq(2).css('width','33%');
var interestedcol = pickerDescribe2.cols[0];
var lowercol = pickerDescribe2.cols[1];
var uppercol = pickerDescribe2.cols[2];
if (f_interested) {interestedcol.setValue(f_interested);}
if (f_lower) {lowercol.setValue(f_lower);}
if (f_upper) {uppercol.setValue(f_upper);}
},
formatValue: function (p, values, displayValues) {
if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];}
else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2];
}
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Preference'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Men Women').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
}
function swipePref(index){$( ".swipetoolbar" ).show();$( ".pref-" + index).show();mySwiper.slideTo(index); $( ".swipetoolbar" ).show();
}
function navPicker(){
myApp.pickerModal(
'<div class="picker-modal picker-sub" style="height:88px;">' +
'<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' +
'<div class="toolbar-inner" style="padding:0;">' +
' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>' +
'</div>' +
'<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' +
'<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+
'</div>' +
'</div>'
);
}
function removeProfileSet(pickertype){
$( "#" + pickertype + "-input").remove();
$( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' );
if (pickertype=='industry'){
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);}
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
}
if (pickertype=='status'){
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
}
if (pickertype=='politics'){
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
}
if (pickertype=='zodiac'){
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
}
if (pickertype=='religion'){
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
}
if (pickertype=='ethnicity'){
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
}
if (pickertype=='height'){
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
}
if (pickertype=='weight'){
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
}
if (pickertype=='eyes'){var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
}
if (pickertype=='body'){
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
}
}
function actionSheet(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}
},
{
text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
myApp.closeModal() ;backtoProfile();
}
else{}
}
},
{
text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
else {
var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid);
//var elementPos = new_all.findIndex(x => x.id==targetid);
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}else{viewscroll = true;singleUser(targetid,targetname);}
}
},
{
text: 'View Profile Photos ('+new_all[elementPos].photocount+')',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
backtoProfile();
}else{viewphotos = true;singleUser(targetid,targetname);}
}
},
{ text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
myApp.actions(buttons);
var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number);
photobombsheet.once('value', function(snapshot) {
if(snapshot.val()){$(".color-green").removeClass('disabled');
$(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')');
}
});
}
| www/js/app.js | var refreshIntervalId;
var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png']
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function sendNotification(targetto,param){
firebase.auth().currentUser.getToken().then(function(idToken) {
var titlestring;
var bodystring;
if (param == 1){titlestring = 'New match created';bodystring='With ' + f_first;}
if (param == 2){titlestring = 'New date request received';bodystring='From ' + f_first;}
if (param == 3){titlestring = 'New date confirmed';bodystring='By ' + f_first;}
if (param == 4){titlestring = 'New message received';bodystring='From ' + f_first;}
if (param == 5){titlestring = 'New photo received';bodystring='From ' + f_first;}
if (param == 6){titlestring = 'Date cancelled';bodystring='With ' + f_first;}
var typesend;
if (d_type){typesend = d_type;}
else {typesend = 'date';}
$.post( "http://www.dateorduck.com/sendnotification.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,target:targetto,titlestring:titlestring,bodystring:bodystring,param:param,type:typesend,firstname:f_first} )
.done(function( data ) {
//alert(JSON.stringify(data));
});
});
}
function sharePop(){
facebookConnectPlugin.showDialog({
method: "share",
href: "http://www.dateorduck.com/",
hashtag: "#dateorduck"
//share_feedWeb: true, // iOS only
}, function (response) {}, function (response) {})
}
function appLink(){
facebookConnectPlugin.appInvite(
{
url: "https://fb.me/1554148374659639",
picture: "https://www.google.com.au/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
},
function(obj){
if(obj) {
if(obj.completionGesture == "cancel") {
// user canceled, bad guy
} else {
// user really invited someone :)
}
} else {
// user just pressed done, bad guy
}
},
function(obj){
// error
// alert(JSON.stringify(obj));
}
);
}
function fcm(){
NativeKeyboard.showMessenger({
onSubmit: function(text) {
console.log("The user typed: " + text);
}
});
}
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
myApp.alert('Could not confirm your hometown.', 'Error');
clearHometown();
} else{
var predictionsarray = [];
$('.hometownprediction').remove();
predictions.forEach(function(prediction) {
predictionsarray.push(prediction.description);
});
}
var hometownpicker = myApp.picker({
input: '#homesearch',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } },
onChange:function (p, values, displayValues){$( '#homesearch' ).addClass("profilevaluechosen");},
onClose:function (p){hometownpicker.destroy();},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'hometown\')">' +
'<a href="#" class="link close-picker" onclick="clearHometown();" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: predictionsarray
}
]
});
hometownpicker.open();
};
function checkHometown(){
var hometownquery = $('#homesearch').val();
if (hometownquery == ''){
return false;}
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: hometownquery,types: ['(cities)'] }, displaySuggestions);
}
function clearHometown(){
$('#homesearch').val('');
}
function newHometown(){
$('#homesearch').remove();
$('.hometown-input').append('<textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>');
$('#homesearch').focus();
}
function fQuery(){
$.ajax({
url: "https://graph.facebook.com/v2.4/784956164912201?fields=context.fields(friends_using_app)",
type: "get",
data: { access_token: f_token},
success: function (response, textStatus, jqXHR) {
$.ajax({
url: "https://graph.facebook.com/v2.4/"+response.context.id+"/friends_using_app?summary=1",
type: "get",
data: { access_token: f_token},
success: function (response1, textStatus, jqXHR) {
try {
response1.summary.total_count;
var friendstring;
if (response1.summary.total_count ==0) {friendstring = 'No friends use this app'}
if (response1.summary.total_count ==1) {friendstring = '1 friend uses this app' }
if (response1.summary.total_count >1) {friendstring = response1.summary.total_count + ' friends use this app' }
if (response1.summary.total_count > 9){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
firebase.database().ref('users/' + f_uid).update({
recentfriends:'Y'
}).then(function() {});
}
if ((response1.summary.total_count > 4) && (response1.summary.total_count <10)){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = true;
$('.nearby-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.nearby-title').html('Nearby First');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
recentshare = false;
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').show();
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">'+friendstring+'</p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
if (response1.summary.total_count < 5){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = false;
recentshare = false;
$('.nearby-helper').show();
$('.recent-helper').show();
$('.nearby-title').html('<i class="pe-7s-lock pe-lg"></i> Nearby First (Locked)');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
$('.nearby-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.nearby-helper').html('<p style=margin-top:-10px;"padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.summary-helper').html('<p style="font-weight:bold;"></p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
} catch(err) {
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
// $('.recent-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to unlock this feature.</p>');
// $('.nearby-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">Invite friends to unlock features</p><div class="row"><div class="col-100"><a class="button active" href="#" onclick="getFriends">Unlock</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">Features are locked based on how many friends you invite to use the app.</p>');
// caught the reference error
// code here will execute **only** if variable was never declared
}
$( ".summary-helper" ).show();
},
error: function (jqXHR, textStatus, errorThrown) {console.log(errorThrown);
},
complete: function () {
}
});
},
error: function (jqXHR, textStatus, errorThrown) {console.log(errorThrown);
},
complete: function () {
}
});
}
function setWant(val){
$( ".homedate" ).addClass("disabled");
$( ".homeduck" ).addClass("disabled");
if (val == 0){
if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant();
}else {homewant = 'offline';updateWant();
}
}
else{$( ".homedate" ).addClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); }
}
}
if (val == 1){
if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); }
}
else{$( ".homeduck" ).addClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); }
}
}
}
function updateWant(){
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
if (homewant == 'offline'){
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
firebase.database().ref('users/' + f_uid).update({
homewant:homewant
}).then(function() {});
//Will update firebase user homewant
//Check if updateuser function is in go daddy file
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} )
.done(function( data ) {
//getMatches();
});
}).catch(function(error) {
// Handle error
});
}
function startCamera(){
navigator.camera.getPicture(conSuccess, conFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY});
}
function conSuccess(imageURI) {
//var image = document.getElementById('myImage');
//image.src = imageURI;
}
function conFail(message) {
// alert('Failed because: ' + message);
}
function doSomething() {
var i = Math.floor(Math.random() * 4) + 0;
$(".desktopimage").attr("src", desktoparray[i]);
}
var myFunction = function() {
doSomething();
var rand = Math.round(Math.random() * (1000 - 700)) + 700;
refreshIntervalId = setTimeout(myFunction, rand);
}
myFunction();
var mobile = 0;
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;}
else{
mobile = 0;
$('.login-loader').hide();
$('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>');
}
//if (mobile===1){
try {
// try to use localStorage
localStorage.test = 2;
} catch (e) {
// there was an error so...
myApp.alert('You are in Privacy Mode\.<br/>Please deactivate Privacy Mode in your browser', 'Error');
}
function directUser(id,type,firstname){
if ($('.chatpop').length > 0) {myApp.closeModal('.chatpop');}
if (type =='date'){createDate1(id,firstname,0);}
else {createDuck(id,firstname,0);}
}
// Initialize your app
var myApp = new Framework7({dynamicNavbar: true,modalActionsCloseByOutside:true,init: false});
// Export selectors engine
var $$ = Dom7;
var datatap, tapid, taptype, tapname;
var view1, view2, view3, view4;
var updatecontinuously = false;
var initialload = false;
var allowedchange = true;
var view3 = myApp.addView('#view-3');
var view4 = myApp.addView('#view-4');
var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,f_image,f_token, f_upper, f_lower, f_interested,sexuality;
var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
var f_auth_id;
var blocklist;
var lastkey;
var distancepicker;
var pickerDescribe,pickerDescribe2, pickerCustomToolbar;
var existingmessages;
var additions = 0;
var myPhotoBrowser;
var singlePhotoBrowser;
var calendarInline;
var keepopen;
var userpref;
var loadpref= false;
var loadpref2= false;
var loaded = false;
var myList;
var myphotosarray;
var matcheslistener;
var noresultstimeout;
var timeoutactive = false;
var radiussize = '100';
var radiusunit = 'Kilometres';
var sortby,offsounds;
var industry_u,hometown_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u,recentfriends;
var descriptionslist = [];
var nameslist = [];
var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">';
var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">';
var notifcount;
var swiperPhotos;
var swiperQuestions;
var myswiperphotos;
var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">';
var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">';
var mySwiper;
myApp.init();
var f_projectid;
var canloadchat;
var viewphotos = false;
var viewscroll = false;
var homewant;
var singlefxallowed = true;
var photoresponse;
var targetpicture;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var firebaseinit;
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
//soNow();
FCMPlugin.onNotification(function(data){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
cordova.plugins.notification.badge.set(data.ev4);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
if (latitudep){directUser(data.ev1,data.ev2,data.ev3);}
else{
datatap = true;
tapid = data.ev1;
taptype = data.ev2;
tapname = data.ev3;
}
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
myApp.addNotification({
title: 'Date or Duck',
subtitle:data.aps.alert.title,
message: data.aps.alert.body,
hold:2000,
closeOnClick:true,
onClick:function(){directUser(data.ev1,data.ev2,data.ev3);},
media: '<img width="44" height="44" style="border-radius:100%" src="media/icon-76.png">'
});
// alert( JSON.stringify(data) );
}
});
// Add views
view1 = myApp.addView('#view-1');
view2 = myApp.addView('#view-2', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
});
view3 = myApp.addView('#view-3');
view4 = myApp.addView('#view-4');
//setTimeout(function(){ alert("Hello");
//FCMPlugin.onTokenRefresh(function(token){
// alert( token );
//});
//alert("Hello2");
// }, 10000);
//authstatechanged user only
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var checkbadge = false;
if (f_projectid){checkbadge = false;}
else{checkbadge = true;}
cordova.plugins.notification.badge.get(function (badge) {
if (badge >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.'))
f_uid = user.providerData[0].uid;
f_auth_id = user.uid;
f_name = user.providerData[0].displayName;
f_first = f_name.substr(0,f_name.indexOf(' '));
f_email = user.providerData[0].email;
f_image = user.providerData[0].photoURL;
// if (subscribeset){}
// else{
// FCMPlugin.subscribeToTopic( f_uid, function(msg){
// alert( msg );
//}, function(err){
// alert( err );
//} );
//}
//subscribeset = true;
if (checkbadge){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/setbadge.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data1 ) {
var result1 = JSON.parse(data1);
cordova.plugins.notification.badge.set(result1[0].notificationcount);
if (result1[0].notificationcount >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
});
}
var originalid = window.localStorage.getItem("originalid");
if (!originalid) {window.localStorage.setItem("originalid", f_uid);}
// $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')");
// $( "#profilepic" ).empty();
// $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>');
firebase.database().ref('users/' + f_uid).update({
auth_id : f_auth_id
}).then(function() {getPreferences();});
} else {
$( ".ploader" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
var originalid = window.localStorage.getItem("originalid");
if (originalid) {$( ".secondlogin" ).show();}
else {$( ".loginbutton" ).show();}
// No user is signed in.
}
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
function clearBadge(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/clearnotifications.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
});
});
$( ".notifspan" ).hide();
cordova.plugins.notification.badge.set(0);
}
function startApp(){
firebaseinit = localStorage.getItem('tokenStore');
if (firebaseinit){
var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
if (error){
myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')');
}
});
}
else {
//alert('no tokenStore');
}
}
//document.addEventListener("screenshot", function() {
// alert("Screenshot");
//}, false);
$$('.panel-right').on('panel:opened', function () {
leftPanel();
});
$$('.panel-right').on('panel:open', function () {
$( ".upgradeli" ).slideDown();
clearBadge();
});
$$('.panel-right').on('panel:closed', function () {
myList.deleteAllItems();
myList.clearCache();
clearBadge();
//firebase.database().ref('notifications/' + f_uid).off('value', notificationlist);
});
function compare(a,b) {
if (a.chat_expire < b.chat_expire)
return -1;
if (a.chat_expire > b.chat_expire)
return 1;
return 0;
}
$$('.panel-left').on('panel:closed', function () {
$(".timeline").empty();
});
$$('.panel-left').on('panel:open', function () {
rightPanel();
});
$$('.panel-right').on('panel:closed', function () {
$( ".upgradeli" ).hide();
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-1');
var geoupdate = Math.round(+new Date()/1000);
var firstupdate = false;
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
// Emulate 2s loading
//loaded = false;
if ($('.no-results-div').length > 0) {myApp.pullToRefreshDone();return false;}
var timesincelastupdate = Math.round(+new Date()/1000) - geoupdate;
if (firstupdate === false){getPreferences();firstupdate = true;}
else{
if (timesincelastupdate > 10){getPreferences();geoupdate = Math.round(+new Date()/1000);}
else {
random_all = shuffle(random_all);
randomswiper.removeAllSlides();
for (i = 0; i < random_all.length; i++) {
var index1 = f_date_match.indexOf(random_all[i].id);
var index2 = f_duck_match.indexOf(random_all[i].id);
var index3 = f_duck_me.indexOf(random_all[i].id);
var index4 = f_date_me.indexOf(random_all[i].id);
var slidewidth = $( document ).width() / 2.5;
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" class="swiper-lazy pp photo_'+random_all[i].id+' photo_'+randomid+'" data-src="'+random_all[i].profilepicstringsmall+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
randomswiper.appendSlide(slidecontent);
if (i == 0 || i==1 || i==2){
$(".photo_"+random_all[i].id).attr("src", random_all[i].profilepicstringsmall);
}
}
$( ".results-loader" ).show();
$( ".swiper-random" ).hide();
$( ".swiper-nearby" ).hide();
$( ".swiper-recent" ).hide();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
setTimeout(function(){
$( ".results-loader" ).hide();
$( ".swiper-random" ).show();
$( ".swiper-nearby" ).show();
$( ".swiper-recent" ).show();
$( ".home-title" ).show();
$( ".nearby-helper" ).show();
$( ".recent-helper" ).show();
$( ".summary-helper" ).show();
}, 2000);
}
}
setTimeout(function () {
// Random image
myApp.pullToRefreshDone();
}, 1000);
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-2');
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
myList.deleteAllItems();
myList.clearCache();
setTimeout(function () {
// Random image
leftPanel();
myApp.pullToRefreshDone();
}, 1000);
});
var onSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function onError(error) {
if (error.code == '1'){
myApp.alert('we are using your approximate location, to improve accuracy go to location settings', 'Oops we cannot find you');
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('You must share your location on date or duck', 'Oops we cannot find you');
});
}
if ((error.code == '2') || (error.code == '3')){
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('There has been an error.', 'Oops we cannot find you');
});
}
}
function showtext(){
$( ".showtext" ).show();
}
function getWifilocation(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var apiGeolocationSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function mainLoaded(id,pid){
$( ".iconpos_" + id ).show();
$( ".default_" + pid).hide();
$( ".photo_"+ pid ).show();
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".maindivhome_" + pid).html('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');}
else{$( ".maindivhome_" + pid ).empty();}
}
});
}
var all_matches_photos=[];
var new_all = [];
var main_all = [];
var random_all = [];
var nearby_all = [];
var recent_all = [];
var nearbyshare = false, recentshare = false;
var randomswiper = myApp.swiper('.swiper-random', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = random_all;
photoBrowser(randomswiper.clickedIndex);}
});
var nearbyswiper = myApp.swiper('.swiper-nearby', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = nearby_all;
if (nearbyshare){
photoBrowser(nearbyswiper.clickedIndex);
}
else{}
}
});
var recentswiper = myApp.swiper('.swiper-recent', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = recent_all;
if (recentshare){
photoBrowser(recentswiper.clickedIndex);
}
else{}
}
});
function getMatches(){
$( ".content-here" ).empty();
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
$( ".results-loader" ).show();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
//alert('getmatch trigger' + homewant);
//can put any ads here
if ((initialload === false) && (availarray.length === 0)){
}
if (!homewant || homewant =='offline'){
$('.content-here').empty();
$( ".statusbar-overlay" ).css("background-color","#ccc");
$( ".buttons-home" ).hide();
$( ".toolbar" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
var swiperheight = $( window ).height() - 378;
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+
'<div class="topdiv">'+
// '<h3>Get Quacking!</h3>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">Get Quacking, It\'s Easy</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">date</span> if you want to find something more serious like a relationship.</div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">date</span> to find love <br/>(or at least try)</div>'+
'</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;margin-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">duck</span> if you want to get down to...ahem...business (replace the D with another letter). </div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">duck</span> to find fun <br/>(replace the D with another letter)</div>'+
'</div>'+
'</div>'+
'<div class="list-block-label" style="color:#666;margin-bottom:10px;">Choose one, or both. Your profile is hidden until you decide.</div>'+
'<div class="swiper-container swiper-helper-info" style="z-index:99999999999999;background-color:#ccc;color:#6d6d72;margin-left:-10px;margin-right:-10px;padding-top:10px;">'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">How this App Works</div>'+
' <div class="swiper-wrapper">'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px;"><i class="twa twa-4x twa-coffee" style="margin-top:5px;"></i><h2>Find your next<br/> coffee date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-wave" style="margin-top:5px;"></i><h2>Or invite someone over<br/> tonight...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-heart-eyes" style="margin-top:5px;"></i><h2>When you like someone, <br/>they can see...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-calendar" style="margin-top:5px;"></i><h2>Once you both agree on</br> a time to meet...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-clock12" style="margin-top:5px;"></i><h2>Chat is enabled until <br/>midnight of your date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-bomb" style="margin-top:5px;"></i><h2>You can send photos that delete after 24 hours...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-watch" style="margin-top:5px;"></i><h2>You can share availability<br/> to easily schedule dates</h2></div></div>'+
' </div>'+
'<div class="swiper-pagination-p" style="margin-top:-20px;margin-bottom:20px;"></div>'+
'</div>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:20px;margin-bottom:10px;margin-left:0px;">Support this app</div>'+
'<a href="#" class="button-big button active" style="margin-bottom:10px;" onclick="appLink()">Invite Friends</a>'+
'<a href="#" class="button-big button" style="margin-bottom:10px;" onclick="sharePop()">Share</a>'+
'<a class="button-big button external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? " style="margin-bottom:10px;">Send SMS</a>'+
'</div>');
$( ".ploader" ).hide();
var homeswiperhelper = myApp.swiper('.swiper-helper-info', {
pagination:'.swiper-pagination-p'
});
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
return false;
}
$( ".statusbar-overlay" ).css("background-color","#2196f3");
initialload = true;
if (recentfriends){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
}
else{
//check permission first
readPermissions();
}
if (updatecontinuously){}
else {setInterval(function(){ justGeo(); }, 599000);updatecontinuously=true;}
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
if (timeoutactive === true) {clearTimeout(noresultstimeout);}
timeoutactive = true;
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/locations.php", { want:homewant,projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,radiusunit:radiusunit,sexuality:sexuality,sortby:'random',latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
dbCall('random');
dbCall('distance');
dbCall('activity');
function dbCall(fetch){
var resultall = JSON.parse(data);
var result;
if (fetch == 'random'){result = resultall[2];}
if (fetch == 'distance'){result = resultall[1];}
if (fetch == 'activity'){result = resultall[0];}
var slidewidth = $( document ).width() / 2.5;
var halfwidth = -Math.abs(slidewidth / 2.23);
$( ".swiper-recent" ).css("height",slidewidth + "px");
$( ".swiper-nearby" ).css("height",slidewidth + "px");
$( ".swiper-random" ).css("height",slidewidth + "px");
var slide_number = 0;
descriptionslist = [];
nameslist = [];
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){
$( ".home-title" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
else {
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (i = 0; i < result.length; i++) {
var photosstringarray =[];
var photocount;
var photostring;
var blocked = 0;
var subtract = result[i].age;
var laston = result[i].timestamp;
var hometown_d = result[i].hometown;
var industry_d = result[i].industry;
var status_d = result[i].status;
var politics_d = result[i].politics;
var eyes_d = result[i].eyes;
var body_d = result[i].body;
var religion_d = result[i].religion;
var zodiac_d = result[i].zodiac;
var ethnicity_d = result[i].ethnicity;
var height_d = result[i].height;
var weight_d = result[i].weight;
var namescount = result[i].displayname.split(' ').length;
var matchname;
var minphotowidth = $( document ).width();
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var availarraystring='';
var availnotexpired = false;
if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){
console.log(result[i].availstring);
var availablearrayindividual = JSON.parse(result[i].availstring);
console.log(availablearrayindividual);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[i].availstring;}
}
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[i].largeurl){
var heightarray = result[i].heightslides.split(",");
var widtharray = result[i].widthslides.split(",");
console.log(heightarray[0]);
console.log(widtharray[0]);
if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'}
if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'}
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[i].largeurl.split(",").length;
photoarrayuserlarge = result[i].largeurl.split(",");
photoarrayusersmall = result[i].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368';
photocount = 1;
}
//console.log(photostring);
if(namescount === 1){matchname = result[i].displayname;}
else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));}
var matchdescription = result[i].description;
var swipernumber = subtract - f_lower;
var graphid = result[i].uid;
var distance = parseFloat(result[i].distance).toFixed(1);
var distancerounded = parseFloat(result[i].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var zz = new Date();
var mmn = zz.getTimezoneOffset();
console.log(result[i].timestamp);
var timestampyear = result[i].timestamp.substring(0,4);
var timestampmonth = result[i].timestamp.substring(5,7);
var timestampday = result[i].timestamp.substring(8,10);
var timestamphour = result[i].timestamp.substring(11,13);
var timestampminute = result[i].timestamp.substring(14,16);
var timestampsecond = result[i].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var activecircle='';
//if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';}
//else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';}
if ($('.slide_' + graphid).length){
}
if (graphid != f_uid){
$('.swiper-' + subtract).show();
$('.header_' + subtract).show();
}
var blockedid = blocklist.indexOf(graphid);
//Do not show the users profile to themselves, and do not show profiles older than 1 month
if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){
var index1 = f_date_match.indexOf(graphid);
var index2 = f_duck_match.indexOf(graphid);
var index3 = f_duck_me.indexOf(graphid);
var index4 = f_date_me.indexOf(graphid);
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+' photo_'+randomid+'" data-src="'+profilepicstringsmall+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
if (fetch == 'random'){randomswiper.appendSlide(slidecontent);
random_all.push({profilepicstringsmall:profilepicstringsmall,hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (random_all[0].id == graphid || random_all[1].id == graphid || random_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'distance'){nearbyswiper.appendSlide(slidecontent);
nearby_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (nearby_all[0].id == graphid || nearby_all[1].id == graphid || nearby_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'activity'){recentswiper.appendSlide(slidecontent);
recent_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (recent_all[0].id == graphid || recent_all[1].id == graphid || recent_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
}
}
}
//if (nearbyshare){
//remove blur, unlock swiper
//}
//else{ $( ".nearby-helper" ).show();}
//if (recentshare){
//remove blur, unlock swiper
//}
//else{ $( ".recent-helper" ).show();}
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
if (random_all.length === 0){
if ($('.no-results-div').length > 0) {}
else{
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
}
else {$( ".home-title" ).show(); $('.content-here').empty();}
}
});
//here is the id token call
}).catch(function(error) {
// Handle error
});
$( ".ploader" ).hide();
$( ".toolbar" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
//$('.no-results-div').empty();
clearInterval(refreshIntervalId);
deletePhotos();
}
function justGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
console.log('updatedtimestamp');
});
}).catch(function(error) {
// Handle error
});
}
function updateGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
getMatches();
});
}).catch(function(error) {
// alert('error' + error);
});
}
function getPreferences(){
// Test if user exists
if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);}
userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) {
var userexists = snapshot.child('lower').exists(); // true
if (userexists) {
// var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) {
// if (!snapshot.child("to_date").val()) {f_to_date = [];}
// else{f_to_date = snapshot.child("to_date").val();}
// if (!snapshot.child("to_duck").val()) {f_to_duck = [];}
// else{f_to_duck = snapshot.child("to_duck").val();}
// if (!snapshot.child("date_me").val()) {f_date_me = [];}
// else{f_date_me = snapshot.child("date_me").val();}
// if (!snapshot.child("duck_me").val()) {f_duck_me=[];}
// else{f_duck_me = snapshot.child("duck_me").val();}
// incommondate = f_to_date.filter(function(n) {
// return f_date_me.indexOf(n) != -1;
//});
//incommonduck = f_to_duck.filter(function(n) {
// return f_duck_me.indexOf(n) != -1;
//});
// });
hometown_u = snapshot.child("hometown").val();
industry_u = snapshot.child("industry").val();
status_u = snapshot.child("status").val();
politics_u = snapshot.child("politics").val();
eyes_u = snapshot.child("eyes").val();
body_u = snapshot.child("body").val();
religion_u = snapshot.child("religion").val();
zodiac_u = snapshot.child("zodiac").val();
ethnicity_u = snapshot.child("ethnicity").val();
height_u = snapshot.child("height").val();
weight_u = snapshot.child("weight").val();
homewant = snapshot.child("homewant").val();
recentfriends = snapshot.child("recentfriends").val();
if (snapshot.child("photoresponse").val()){
if (snapshot.child("photoresponse").val() == 'Y'){photoresponse = 'Y';f_image = snapshot.child("uploadurl").val();}
}
else{
photoresponse = 'N';
f_image = 'https://graph.facebook.com/'+f_uid+'/picture?width=100&height=100';
}
sortby = snapshot.child("sort").val();
if (sortby){
if (sortby == 'random'){sortBy(1);}
if (sortby == 'distance'){sortBy(2);}
if (sortby == 'activity'){sortBy(3);}
$( ".sortbutton" ).removeClass( "active" );
$( "#sort" + sortby ).addClass( "active" );
}
if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();}
if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());}
f_description = snapshot.child("description").val();
f_lower = snapshot.child("lower").val();
radiussize = snapshot.child("radius").val();
if(snapshot.child("radiusunit").val()){radiusunit = snapshot.child("radiusunit").val();}
else{radiusunit = "Kilometres";}
f_token = snapshot.child("token").val();
f_upper = snapshot.child("upper").val();
f_interested = snapshot.child("interested").val();
f_gender = snapshot.child("gender").val();
f_age = snapshot.child("age").val();
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
if (loadpref=== false){
if(homewant){
if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); }
if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active');}
}
loadpref = true;
establishNotif();
}
matchesListener();
}
else if (!userexists) {
addUser();
if (loadpref=== false){
firebase.database().ref('users/' + f_uid).once("value",function(snapshot) {
f_token = snapshot.child("token").val();
swipePopup(1);
});
//preferencesPopup();
}
loadpref = true;
}
});
}
function matchesListener(){
if (loaded === true){
firebase.database().ref("matches/" + f_uid).off('value', matcheslistener);
}
matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) {
f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
blocklist = [];
if (snapshot.val()){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);}
if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);}
if(obj.firstnumberdate){
//f_to_date
if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);}
//f_date_me
if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);}
}
if(obj.firstnumberduck){
//f_duck_me
if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);}
//f_to_duck
if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);}
}
if(obj.secondnumberdate){
//f_to_date
if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);}
//f_date_me
if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);}
}
if(obj.secondnumberduck){
//f_to_duck
if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);}
//f_duck_me
if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);}
}
if(obj.firstnumberdate && obj.secondnumberdate){
//f_date_match
if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
if(obj.firstnumberduck && obj.secondnumberduck){
//f_duck_match
if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
});
updatePhotos();
loaded = true;
}
else{
updatePhotos();
loaded = true;
}
});
getWifilocation();
}
function addUser() {
if (f_token){firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
token:f_token,
auth_id : f_auth_id
});}
else{
firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
auth_id : f_auth_id
});
}
}
function clickMe() {
pickerDescribe.open();
}
function keyUp(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var inputlength = $( "#userdescription" ).val().length;
$( "#maxdescription" ).empty();
$( "#maxdescription" ).append(inputlength + " / 100");
}
function updateUser(){
if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) {
myApp.alert('Please complete more profile information.', 'Missing Information');
return false;}
if (myswiperphotos){
myswiperphotos.destroy();
myswiperphotos = false;
}
var newage,newinterested,newgender;
if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;}
else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === false) {newinterested = f_interested;}
else {newinterested = pickerDescribe2.value[0];}
var userzdescription;
if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();}
else {userzdescription = '';}
//Need to delete old reference
if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];}
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
var lowerage,upperage;
if (pickerDescribe2.initialized === true) {
if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];}
else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];}
}
else {lowerage = f_lower;upperage = f_upper;}
//if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';}
//if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';}
//if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';}
//if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';}
availarray = [];
$( ".availrec" ).each(function() {
if ($( this ).hasClass( "selecrec" )){
var availinputid = $(this).attr('id').replace('aa_', '');
var valueinputted = $( "#picker"+availinputid ).val();
var supdate = $( ".suppdate_"+availinputid ).val();
if (valueinputted == 'Now'){daysaved ='Now';timesaved='';}
else{
valueinputted = valueinputted.split(' ');
var daysaved = valueinputted[0];
var timesaved = valueinputted[1];
}
availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate});
}
});
var availstring = JSON.stringify(availarray);
var availstringn = availstring.toString();
if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'}
//User Profile details
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
var uploadurl = '';
photoresponse = 'N';
if (f_largeurls.length > 0){photoresponse = 'Y';uploadurl = f_largeurls[0];}
else{photoresponse='N';uploadurl = '';}
firebase.database().ref('users/' + f_uid).update({
gender: newgender,
industry:industry_u,
hometown:hometown_u,
status:status_u,
politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u,
height: height_u,
weight: weight_u,
age: newage,
interested: newinterested,
lower: lowerage,
upper: upperage,
description:userzdescription,
radius:radiussize,
radiusunit:radiusunit,
availstring:availstring,
offsounds:offsounds,
photoresponse:photoresponse,
uploadurl:uploadurl
});
if (deletedphoto){
var newsmall = f_smallurls.toString();
var newlarge = f_largeurls.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
}
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,hometown:hometown_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} )
.done(function( data ) {
//if (f_gender && (f_gender != newgender)){
//deleteDatabase();
//}
//if (f_interested && (f_interested != newinterested)){
//deleteDatabase();
//}
});
}).catch(function(error) {
// Handle error
});
f_lower = lowerage;
f_upper = upperage;
//if (loadpref2===true){getWifilocation();}
loadpref2 = true;
myApp.closeModal();
$( ".popup-overlay" ).remove();
}
function processUpdate(){
$( '.donechange' ).show();
$( '.doneunchange' ).hide();
}
function processDupdate(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if (d_chat_expire){
var datemessageq = $( '#datemessageq' ).val();
var interestnewarray = [];
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestnewarray.push(interestadd);
}
});
var comparedinterest;
var compareninterest;
if (d_interest != null) {
comparedinterest = d_interest.toString();
}
else {comparedinterest = '';}
if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();}
if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest))
{
if (d_response=='Y'){noChange();}
else if (d_response=="W"){reverseRequest();dateConfirmationPage();}
}
else{dateRequest();}
}
else {dateRequest();}
}
var mynotifs = [];
function leftPanel(){
canscrollnotif = true;
mynotifs = [];
notifadditions=0;
if(!myList){
myList = myApp.virtualList('.virtual-notifications', {
// Array with plain HTML items
items: [],
height:89,
renderItem: function (index, item) {
var backgroundnotifcolor;
if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';}
if(item.from_uid == f_uid){
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
else{
//onclick="singleBrowser('+item.targetid+')"
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
}
});
}
var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) {
if (snapshot.val() === null){
// $('.title-notify').remove();
// $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>');
$('.nonefound').remove();
$('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$('.nonefound').remove();
var objs = snapshot.val();
var obg = [];
$.each(objs, function(i, obk) {obg.push (obk)});
console.log(obg);
function compare(a,b) {
if (a.timestamp > b.timestamp)
return -1;
if (a.timestamp < b.timestamp)
return 1;
return 0;
}
obg.sort(compare);
$.each(obg, function(i, obj) {
var typetype = obj.type.substring(0, 4);
var correctimage;
var correctname;
var iconhtml;
var colordot;
var message_text;
var func;
var picturesrc;
var mediaicon;
var dateseenresponse;
if (typetype == 'date') {mediaicon = fdateicon;}
if (typetype == 'duck') {mediaicon = fduckicon;}
//need to see if a match still and then create function based on tha
var timestamptitle;
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - obj.timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = '1 minute ago';}
else if (tunixminago == 1) {timestamptitle = '1 minute ago';}
else if (tunixminago < 2) {timestamptitle = '1 minute ago';}
else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = '1 hour ago';}
else if (tunixminago < 62) {timestamptitle = '1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = '1 day ago';}
else if (tunixminago < 2880) {timestamptitle = '1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';}
else if (tunixminago == 10080) {timestamptitle = '1 week ago';}
else if (tunixminago < 20160) {timestamptitle = '1 week ago';}
else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';}
else if (tunixminago == 525600) {timestamptitle = '1 week ago';}
else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';}
else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';}
// onclick="singleBrowser('+targetid+')"
if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'}
if (obj.param=='image'){
if (obj.from_uid == f_uid){message_text = obj.message + 'sent';}
else {message_text = obj.message + 'received';}
iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';}
if (obj.param=='daterequest'){
if (obj.from_uid == f_uid){message_text = obj.message + ' sent';}
else {message_text = obj.message + ' received';}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='datedeleted'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='newmatch'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='dateconfirmed'){
message_text = obj.message;
iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
// if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';}
// if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';}
if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';}
else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';}
else{colordot = '';}
if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';}
else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';}
datemeinarray=0;
duckmeinarray=0;
datetoinarray=0;
ducktoinarray=0;
if (obj.from_uid == f_uid){picturesrc = obj.to_picture;}
else{picturesrc = obj.from_picture;}
var datesto = f_to_date.indexOf(correctimage);
if (datesto > -1) {
datetoinarray=1;
}
var datesme = f_date_me.indexOf(correctimage);
if (datesme > -1) {
datemeinarray=1;
}
var duckto = f_to_duck.indexOf(correctimage);
if (duckto > -1) {
ducktoinarray=1;
}
var duckme = f_duck_me.indexOf(correctimage);
if (duckme > -1) {
duckmeinarray=1;
}
if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) {
if (typetype == 'date') {func = 'createDate1';}
if (typetype == 'duck') {func = 'createDuck';}
}
else{func = 'singleUser'}
mynotifs.push({
title: message_text,
targetid:correctimage,
targetname:correctname,
picture:picturesrc,
from_name: obj.from_name,
to_name: obj.to_name,
from_uid: obj.from_uid,
to_uid: obj.to_uid,
icon:iconhtml,
colordot:colordot,
func:func,
type:typetype,
timestamptitle:timestamptitle
});
});
var notif2load = mynotifs.length;
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
for (i = 0; i < notifletsload; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
}
});
}
function rightPanel(){
$('.timeline-upcoming').empty();
myApp.sizeNavbars();
var rightdates = [];
var month = [];
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUN";
month[6] = "JUL";
month[7] = "AUG";
month[8] = "SEP";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var weekday = [];
weekday[0] = "SUN";
weekday[1] = "MON";
weekday[2] = "TUE";
weekday[3] = "WED";
weekday[4] = "THU";
weekday[5] = "FRI";
weekday[6] = "SAT";
var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
$('.timeline-upcoming').empty();
if (snapshot.val() === null){
$('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
rightdates.push(obj);
});
rightdates.sort(compare);
for (i = 0; i < rightdates.length; i++) {
var correctname;
var correctid;
var picturesrc;
if (rightdates[i].created_uid == f_uid) {picturesrc = rightdates[i].to_picture;correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;}
if (rightdates[i].created_uid != f_uid) {picturesrc = rightdates[i].from_picture;correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;}
var unix = Math.round(+new Date()/1000);
var c = new Date(rightdates[i].chat_expire*1000);
var cday = weekday[c.getDay()];
if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){
var d = new Date(rightdates[i].chat_expire*1000 - 3600);
var timehere;
if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;}
else {timehere='';}
var timestamptitle;
var datetype = rightdates[i].type.capitalize();
var datesidetitle;
var dayday = d.getDate();
var monthmonth = month[d.getMonth()];
var subtitletext,confirmtext;
if (rightdates[i].response =='Y') {
if (rightdates[i].type=='date' ){datesidetitle = 'Date';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';}
timestamptitle = datesidetitle + ' Confirmed';
var name_accepted;
if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';}
else {name_accepted = rightdates[i].received_name;}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>';
confirmtext='Date confirmed by '+name_accepted+' on '+cday;
}
if (rightdates[i].response =='W') {
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - rightdates[i].timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent now';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';}
if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';}
if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';}
if ($(".time_line_" + dayday)[0]){
} else {
$('.timeline').append('<div class="timeline-item" style="margin-bottom">'+
'<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+
//'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content time_line_'+dayday+'">'+
'</div>'+
'</div>');
}
$('.time_line_'+dayday).append(
'<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+
subtitletext+
// '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+
'<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+
'<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\''+picturesrc+'\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+
// '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+
'<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+
'</div>'+
'</a>'
);
if(rightdates[i].type=='date'){
//for (k = 0; k < rightdates[i].interest.length; k++) {
// $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>');
// }
}
}
}
}
});
}
function newAm(){
$( ".originalam" ).hide();
$( ".newam" ).show();
pickerDescribe.open();
}
function newMe(){
$( ".originalme" ).hide();
$( ".newme" ).show();
pickerDescribe2.open();
}
var deletedphoto;
function getData(){
deletedphoto = false;
if(photosloaded === false){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
var result = JSON.parse(data);
console.log(result);
if (result!='77' && result[0].largeurl){
$( ".reorderbutton" ).removeClass('disabled');
$( ".deleteallbutton" ).removeClass('disabled');
f_smallurls = result[0].smallurl.split(',');
f_largeurls = result[0].largeurl.split(',');
console.log(result[0].widthslides);
console.log(result[0].heightslides);
addedwidth = result[0].widthslides.split(',');
addedheight = result[0].heightslides.split(',');
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
for (i = 0; i < f_largeurls.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
direction:'vertical',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
onClick:function(swiper, event){
}
});
}
else {
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
direction:'vertical'
});
}
});
}).catch(function(error) {
// Handle error
});
}
if (photosloaded === true){myswiperphotos.update();}
photosloaded = true;
}
function deleteIndividual(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
if ($( ".photosliderinfo" ).hasClass('pictures')){
myApp.confirm('Are you sure?', 'Delete Photo', function () {
myswiperphotos.removeSlide(myswiperphotos.clickedIndex);
f_largeurls.splice(myswiperphotos.clickedIndex, 1);
f_smallurls.splice(myswiperphotos.clickedIndex, 1);
addedwidth.splice(myswiperphotos.clickedIndex, 1);
addedheight.splice(myswiperphotos.clickedIndex, 1);
console.log(addedwidth);
console.log(addedheight);
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
deletedphoto = true;
myswiperphotos.update();
if (myswiperphotos.slides.length === 0){
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.updatePagination();
myswiperphotos.update();
}
});
}
else {
photosPopup();
}
}
function openAvaill(availtime){
if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');}
else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');}
}
function openAvail(availtime){
$( '.li_'+ availtime ).addClass('selecrec');
}
function removeAvail(availtime,availname,availnameonly){
$( '.li_'+ availtime ).removeClass('selecrec');
$('#picker'+availtime ).remove();
$('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>');
myApp.picker({
input: '#picker' + availtime,
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (availnameonly + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
var availarray = [];
function report(){
myApp.prompt('What is the problem?', 'Report '+targetname, function (value) {
if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;}
targetreported = true;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:value,
response:'N',
timestamp: t_unix,
};
var updates = {};
updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData;
if (f_uid == first_number){
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
}
else{
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
}
return firebase.database().ref().update(updates).then(function() {
myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');});
});
$(".modal-text-input").prop('maxlength','50');
}
function more(){
var swiperno = 0;
myApp.confirm('Are you sure?', 'Block '+targetname, function () {
var blockindex = myPhotoBrowser.swiper.activeIndex;
targetid = new_all[blockindex].id;
myPhotoBrowser.swiper.removeSlide(blockindex);
myPhotoBrowser.swiper.updateSlidesSize();
swiperQuestions.removeSlide(blockindex);
swiperQuestions.updateSlidesSize();
new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1));
if (new_all.length>0){
for (var i = 0; i < random_all.length; i++) {
if (random_all[i].id == targetid){
randomswiper.removeSlide(i);
randomswiper.updateSlidesSize();
random_all = random_all.slice(0,i).concat(random_all.slice(i+1));
}
}
for (var i = 0; i < nearby_all.length; i++) {
if (nearby_all[i].id == targetid){
nearbyswiper.removeSlide(i);
nearbyswiper.updateSlidesSize();
nearby_all = nearby_all.slice(0,i).concat(nearby_all.slice(i+1));
}
}
for (var i = 0; i < recent_all.length; i++) {
if (recent_all[i].id == targetid){
recentswiper.removeSlide(i);
recentswiper.updateSlidesSize();
recent_all = recent_all.slice(0,i).concat(recent_all.slice(i+1));
}
}
}
else {
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.destroy();
nearbyswiper.destroy();
recentswiper.destroy();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
var firstpos;
var lastpos;
myApp.closeModal('.actions-modal');
allowedchange = false;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid);
theirnotifs.remove().then(function() {
console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
console.log("their notifs failed: " + error.message)
});
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
mynotifs.remove().then(function() {
console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
console.log("my notifs failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid);
theirdates.remove().then(function() {
console.log("their dates Remove succeeded.")
})
.catch(function(error) {
console.log("their dates failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid);
mydates.remove().then(function() {
console.log("my dates Remove succeeded.")
})
.catch(function(error) {
console.log("my dates failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number);
ourchats.remove().then(function() {
console.log("Chats Remove succeeded.")
})
.catch(function(error) {
console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number);
ourphotochats.remove().then(function() {
console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
console.log("PhotoChats Remove failed: " + error.message)
});
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
if (new_all.length>1){
if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';}
if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';}
if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext();swiperQuestions.slidePrev();swiperQuestions.slideNext(); }
else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
}
//myPhotoBrowser.swiper.slideTo(blockindex);
// console.log(all_matches_photos[swipertarget]);
// console.log(new_all);
if (new_all.length === 0){
myPhotoBrowser.close();myApp.closeModal();
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
// myPhotoBrowser.swiper.slideTo(blockindex);
if (new_all.length===1){
$( ".availyo_"+ new_all[0].id ).show();
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var targetdescription= new_all[0].description;
targetname = new_all[0].name;
var targetage = new_all[0].age;
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
if (new_all.length>0){
checkMatch(targetid);
}
});
}
var canscrollnotif = true;
function scrollNotifications(){
//console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top);
if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) {
if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;
setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000);
}
else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);}
}
}
function scrollMessages(){
if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20 || existingmessages < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}}
}
function showDecide(){
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
$( ".toolbardecide" ).show();
}
function closeCreate(){
myApp.closeModal('.actions-modal');
myApp.closeModal('.chatpop');
singlefxallowed = true;
}
function createDate(messageid,messagename,redirect){
if (redirect===0) {}
else { if ($('.chatpop').length > 0){return false;}}
var centerdiv;
if (messageid) {targetid = messageid;}
if (messagename) {targetname = messagename;}
singleUser(targetid,targetname,88);
existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){
cordova.plugins.notification.badge.get(function (badge) {
var newcount = badge-obj.new_message_count;
if (newcount < 1){
$( ".notifspan" ).hide();
}
else {
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
}
});
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
});
}
});
if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div class="navbarphoto"></div>'+targetname+'</div>';}
var divcentrecontent;
if (redirect === 0){divcentrecontent='<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;color:white;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else {divcentrecontent='<span id="centerholder" style="color:white;z-index:99999999999999999999999999999999;color:white;"></span>';}
var popupHTML = '<div class="popup chatpop">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'</div>'+
divcentrecontent+
' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+
' </a></div>'+
'</div>'+
'</div>'+
'<div class="pages" style="margin-top:-44px;">'+
'<div data-page="datepopup" class="page">'+
'<div class="toolbar messagebar datetoolbar" style="display:none;background-color:red;">'+
' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+
'<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+
'</div>'+
' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+
'</div>'+
' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:#2196f3;">'+
'<input id="datemessageq" placeholder="Message (optional)" style="width: calc(100% - 70px);margin-left:5px;background-color:white;max-height:44px;" type="text">'+
'<a href="#" style="z-index:99999999;height:44px;color:white;background-color:#2196f3;float:left;line-height:44px;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;padding-left:10px;">Send</span></a>'+
'</div>'+
' <div class="toolbar-inner message-inner" style="display:none;background-color:#2196f3;padding-left:0px;padding-right:0px;">'+
'<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:white;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;background-color:red;margin-top:-12px;margin-left:-50px;"><input id="messagearea" type="text" placeholder="Enter Message"><a href="#" class="link sendbutton" style="color:white;margin-right:10px;margin-left:10px;" onclick="sendMessage();">Send</a>'+
'</div>'+
'</div>'+
'<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+
'</div>'+
'<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+
'<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+
'<div class="datearea" style="text-align:center;"></div>'+
'<div class="messages scrolldetect" style="margin-top:100px;">'+
'</div></div></div>'+
'</div></div>';
myApp.popup(popupHTML);
var closedvar = $$('.chatpop').on('popup:close', function () {
clearchatHistory();
});
//existingDate();
//setDate();
$( "#centerholder" ).append(centerdiv);
myApp.sizeNavbars();
//$( "#centerholder" ).remove();
if (datealertvar === false) {
datealertvar = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_type = snapshot.child('type').val();
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
var newtonight = new Date();
newtonight.setHours(23,59,59,999);
var newtonight_timestamp = Math.round(newtonight/1000);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var chatdaystring;
var expiredateobject = new Date((d_chat_expire * 1000) - 86400);
var unixleft = d_chat_expire - newtonight_timestamp;
var daysleft = unixleft / 86400;
console.log('daysleft' + daysleft);
var weekdaynamew = weekday[expiredateobject.getDay()];
if(daysleft <= 0){chatdaystring = 'Today';}
else if(daysleft === 1){chatdaystring = 'Tomorrow';}
else chatdaystring = weekdaynamew;
console.log(unixleft);
console.log(daysleft);
var hoursleft = unixleft / 3600;
var salut;
if (daysleft <=0){
salut='tonight';
}
else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';}
else{salut = 'in ' + daysleft+' days';}
var aftertag;
$( ".datedetailsdiv" ).empty();
$( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+
'<ul style="background-color:#4cd964">'+
'<li>'+
' <div class="item-content" style="padding-left:15px;">'+
'<div class="item-media">'+
'<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+
' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+
' </div>'+
'<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+
// '<div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div> ' );
if (d_time){
var lowertime = d_time.toLowerCase()
if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);}
else {
$( ".chatafternavbar").append(' ' + d_time);}
}
//if (d_interest && d_type =='duck'){
// if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';}
// if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';}
//}
//if (d_interest && d_type =='date'){
//for (i = 0; i < d_interest.length; i++) {
// $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
//}
//}
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_interest = false;
d_chat_expire = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_timestamp = false;
d_message = false;
d_dateseen = false;
d_dateseentime = false;
if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();}
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
//need to check if still matched
}
//alert('triggered');
// if (snapshot.val().response == 'W') {noMessages();
// setDate();dateConfirmationPage();}
// else {chatShow();}
//dateConfirmationPage();
keepopen = 0;
});
}
else {}
}
function scrollBottom(){
var objDiv = document.getElementById("messagediv");
objDiv.scrollTop = objDiv.scrollHeight;
//$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300);
}
function noMessages(){
$( ".messages" ).hide();
$( ".datearea" ).empty();
$( ".datearea" ).append(
'<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+
//'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:20px;color:white;font-family: \'Pacifico\', cursive;"></div>'+
'<div class="requesticon" style="padding-top:20px;"></div>'+
'<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+
'<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:10px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+
'<div class="waitingreply"></div>'+
'<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+
'<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+
' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+
'</div> '+
'<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+
'<div class="buttons-row" style="width:100%;padding-left:10px;padding-right:10px;">'+
' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+
'<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+
'</div>'+
'</div> '+
'<div class="profileyomain profileyo_'+ targetid+'" style="border-top:1px solid #c4c4c4;"></div>'+
'<span class="preloader preloader-white avail-loader" style="margin-top:20px;clear:both;margin-bottom:10px;"></span>'+
'</div>');
if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');}
if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');}
}
function setDate(){
var dateset = 'N';
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
var alldays_values = [];
var alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
alldays_values.push(tonight_timestamp - 1);
alldays_values.push(tonight_timestamp);
alldays_names.push('Now');
alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
alldays_values.push(tomorrow_timestamp);
alldays_names.push('Tomorrow');
for (i = 1; i < 6; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
n = weekday[datz.getDay()];
alldays_names.push(n);
}
pickerCustomToolbar = myApp.picker({
container: '#createdatepicker',
rotateEffect: true,
inputReadOnly: true,
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");},
toolbar:false,
onChange:function(p, value, displayValue){
setTimeout(function(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
}, 1000);
if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');}
},
cols: [
{
displayValues: alldays_names,
values: alldays_values,
},
{
textAlign: 'left',
values: (' Morning Afternoon Midday Evening').split(' ')
},
]
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(snapshot.child('time').val());
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(snapshot.child('chat_expire').val());
}
dateset = 'Y';
if (d_interest && d_type =='date') {
for (i = 0; i < d_interest.length; i++) {
$( "." + d_interest[i] +"_i" ).addClass('interestchosen');
}
}
if (d_interest && d_type =='duck') {
if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");}
if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}}
}
});
$( "#createdatepicker" ).hide();
}
function infoPopup(){
var popupHTML = '<div class="popup">'+
'<div class="content-block">'+
'<p>Popup created dynamically.</p>'+
'<p><a href="#" class="close-popup">Close me</a></p>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
}
function dateUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" );
$( ".notifback" ).show();
$( ".mainback" ).hide();
if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
removetoDate();
}
else{
if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();}
//clicked date
$( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" );
addtoDate();
}
}
function addtoDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialdate = f_date_me.indexOf(targetid);
if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}
}
}
//if button has blue border change the color
}
function removetoDate(){
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function duckUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" );
if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
$( ".notifback" ).show();
$( ".mainback" ).hide();
removetoDuck();
}
else{
if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();}
//clicked duck
$( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" );
addtoDuck();
}
}
function removetoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function markMe(){
var mearray = ["4"];
firebase.database().ref('users/' + f_uid).update({
//add this user to my list
date_me:mearray
});
}
function addtoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_number:first_number,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialduck = f_duck_me.indexOf(targetid);
if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}}
}
}
var singleuserarray = [];
function singleUser(idw,idname,origin){
if (singleuserarray[0] != null){
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="z-index:99999999999999;margin-top:0px;clear:both;margin-bottom:-40px;width:100%;">'+
'<ul style="background-color:transparent" style="width:100%;">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;width:100%;" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div></li>'
);
}
}
}
if (origin){photoBrowser(0,singleuserarray[0].age,1,1);}
else{photoBrowser(0,singleuserarray[0].age);}
}
else{
if (singlefxallowed === false){return false;}
singlefxallowed = false;
targetid = String(idw);
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
console.log(data);
var result = JSON.parse(data);
var availarraystring='';
var availnotexpired = false;
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){
var availablearrayindividual = JSON.parse(result[0].availstring);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[0].availstring;}
}
var timestampyear = result[0].timestamp.substring(0,4);
var timestampmonth = result[0].timestamp.substring(5,7);
var timestampday = result[0].timestamp.substring(8,10);
var timestamphour = result[0].timestamp.substring(11,13);
var timestampminute = result[0].timestamp.substring(14,16);
var timestampsecond = result[0].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var photosstringarray =[];
var photocount;
var photostring;
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[0].largeurl){
var heightarray = result[0].heightslides.split(",");
var widtharray = result[0].widthslides.split(",");
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[0].largeurl.split(",").length;
photoarrayuserlarge = result[0].largeurl.split(",");
photoarrayusersmall = result[0].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
targetpicture = photoarrayuserlarge[0];
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\''+profilepicstringlarge+'\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368';
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
targetpicture = 'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100';
photocount = 1;
}
var distance = parseFloat(result[0].distance).toFixed(1);
var distancerounded = parseFloat(result[0].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var namescount = result[0].displayname.split(' ').length;
var matchname;
if(namescount === 1){matchname = result[0].displayname;}
else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));}
singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight});
// console.log(singleuserarray);
main_all = new_all;
new_all = singleuserarray;
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+
'<ul style="background-color:transparent">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;" class="item-link item-content" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
}
}
if (origin == 88){
//alert('88');
}
else if (origin == 1){
//alert('99');
photoBrowser(0,singleuserarray[0].age,1,1);
}
else if (!origin){
//alert('100');
photoBrowser(0,singleuserarray[0].age);
}
});
});
}
}
function request(dayw,timeq){
$( ".profileyomain" ).hide();
canloadchat = false;
$( '.picker-items-col-wrapper' ).css("width", "auto");
$( ".requesticon" ).hide();
$( ".dateheader" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
conversation_started = false;
if (d_response == 'Y') {
$( ".date-close" ).hide();
$( ".date2-close" ).show();
$( ".date1-close" ).hide();
}
if (d_response == 'W') {
$( ".date-close" ).hide();
$( ".date1-close" ).show();
$( ".date2-close" ).hide();
}
if(!d_response){
$( ".date-close" ).show();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
}
$( ".messages" ).hide();
$( ".date-button" ).hide();
$( "#createdatepicker" ).show();
$( ".dr" ).hide();
$( ".date-back" ).hide();
if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();}
if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();}
$( ".waitingreply" ).empty();
$( ".datetoolbar" ).slideDown();
$( ".message-inner" ).hide();
$( ".date-inner" ).show();
if (d_response=='Y'){$( "#datemessageq" ).val('');}
// $( ".center-date" ).empty();
// if (d_type=='date') {$( ".center-date" ).append('Date Details');}
// if (d_type=='duck') {$( ".center-date" ).append('Duck Details');}
myApp.sizeNavbars();
//$( "#createdatepicker" ).focus();
$( ".page-content" ).animate({ scrollTop: 0 }, "fast");
if (dayw){
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(dayw);
if (timeq != 'Anytime'){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(timeq);
}
}
}
function noChange(){
myApp.closeModal('.actions-modal');
canloadchat = true;
$( ".sender-inner" ).hide();
$( ".messages" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
$( "#createdatepicker" ).hide();
// $( ".center-date" ).append(targetname);
$( ".nomessages" ).hide();
$( ".date-back" ).show();
$( ".date-button" ).show();
scrollBottom();
myApp.sizeNavbars();
}
function reverseRequest(){
if ($('.availtitle').length > 0){$( ".datetoolbar" ).hide();}
myApp.closeModal('.actions-modal');
$( ".profileyomain" ).show();
$( ".dateheader" ).hide();
$( "#createdatepicker" ).hide();
$( ".dr" ).show();
$( ".date-back" ).show();
$( ".date-row" ).hide();
$( ".duck-row" ).hide();
$( ".date-close" ).hide();
$( ".requesticon" ).show();
$( ".date-inner" ).hide();
if (!d_day){
//$( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
}
}
var message_count = 0;
var messages_loaded = false;
var conversation_started = false;
var prevdatetitle;
function chatShow(){
//fcm();
prevdatetitle = false;
letsload = 20;
canloadchat = true;
additions = 0;
$( ".yes-inner" ).hide();
$( ".sender-inner" ).hide();
$( ".datedetailsdiv" ).show();
message_count = 1;
image_count = 0;
$( ".messages" ).show();
$( ".datearea" ).empty();
$( ".date-back" ).show();
$( ".date-button" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".datetoolbar" ).show();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
//myMessagebar = myApp.messagebar('.messagebar', {
// maxHeight: 200
//});
myMessages = myApp.messages('.messages', {
autoLayout: true,
scrollMessages:true
});
//if (myMessages) {myMessages.clean();}
if (message_history === true){}
if (message_history === false){
message_history = true;
//do the .on call here to keep receiving messages here
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
// $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>');
// $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
// if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');}
}).then(function(result) {
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) {
if (message_count ==1) {lastkey = snapshot.getKey();}
message_count ++;
var checkloaded;
if (existingmessages > 19){checkloaded = 20;}
else if (existingmessages < 20){checkloaded = existingmessages;}
if (message_count == checkloaded){messages_loaded = true;}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
else{console.log('it is a different day');prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
//my messages
var unix = Math.round(+new Date()/1000);
if (obj.from_uid == f_uid) {
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list" style="margin-top:0px;">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Date Details</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
// Day
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (obj.photo_expiry){
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
// Day
});
image_count ++;
}
}
else {
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// ' and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
if (conversation_started === true) {
$( ".message" ).last().remove();
$( ".message" ).last().addClass("message-last");
$('#buzzer')[0].play();
}
}
//received messages
if (obj.to_uid == f_uid) {
if (messages_loaded === true) {
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
}
});
}
if (conversation_started === true) {
$('#buzzer')[0].play();
}
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Element title</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (!obj.photo_expiry){
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
var seentime = Math.round(+new Date()/1000);
var expirytime = Math.round(+new Date()/1000) + 86400;
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
}
else {
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
}
}
}, function (errorObject) {
});
});
}
//myMessages.layout();
//myMessages = myApp.messages('.messages', {
// autoLayout: true
//});
//myMessages.scrollMessages();
myApp.initPullToRefresh('.pull-to-refresh-content-9');
}
var notifadditions=0;
var notifletsload = 12;
function getmoreNotifs(){
notifadditions ++;
var notifsloaded = notifadditions * 12;
var notif2load = mynotifs.length - (notifadditions * 12);
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
var lasttoaddnotif = notifsloaded + notifletsload;
$(".loadnotifsloader").remove();
for (i = notifsloaded; i < lasttoaddnotif; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
canscrollnotif = true;
}
var letsload = 20;
function getPrevious(){
if (existingmessages === false){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
previousFunction();
})
}
else{previousFunction();}
function previousFunction(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var prevarray = [];
message_count = 0;
additions ++;
$(".previouschats").remove();
var left2load = existingmessages - (additions * 20);
if (left2load > 20) {letsload = 20;} else {letsload = left2load;}
console.log('existingmessages' + existingmessages);
console.log('letsload' + letsload);
console.log('additions' + additions);
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) {
message_count ++;
if (message_count ==1) {lastkey = snapshot.getKey();}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){console.log('it is the same day');
//console.log($(".message").length);
if ((letsload < 20) && (message_count == 1) ){
if (messagedaytitle == todaystring){datechatstring = 'Today'}
if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {datechatstring='';}
}
else{console.log('it is a different day');prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
}
//my messages
if (obj.from_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
//received messages
if (obj.to_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
if (message_count == letsload) {
$(".loadmessagesloader").remove();
canloadchat = true;
myMessages.addMessages(prevarray.slice(0, -1), 'prepend');
//$(".scrollbutton").remove();
//$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
//if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");}
}
}, function (errorObject) {
// console.log("The read failed: " + errorObject.code);
});
}
}
var targetid;
var targetname;
var targetreported;
var targetdatearray,targetduckarray;
var targetdate,targetduck;
var match;
var targetdatelikes, targetducklikes;
var slideheight = $( window ).height();
function getMeta(url){
$("<img/>",{
load : function(){
if (this.height > this.width){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
}
},
src : url
});
}
function backtoProfile(){
myApp.closeModal('.infopopup') ;
$( ".toolbarq" ).hide();
//getMeta(new_all[myPhotoBrowser.activeIndex].url);
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
//$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
//put original image here
$( ".greytag" ).addClass('bluetext');
//$( ".photo-browser-slide img" ).css("height","100%");
$( ".datebutton" ).addClass('imagelibrary');
$( ".duckbutton" ).addClass('imagelibrary');
//$( ".swiper-container-vertical" ).css("height",slideheight + "px");
//$( ".swiper-container-vertical" ).css("margin-top","0px");
//$( ".swiper-slide-active" ).css("height", "600px");
$( ".toolbarq" ).css("background-color","transparent");
$( ".datefloat" ).hide();
$( ".duckfloat" ).hide();
$( ".vertical-pag" ).show();
//$( ".infopopup" ).css("z-index","-100");
$( ".onlineblock" ).hide();
//$( ".orlink" ).show();
//$( ".uplink" ).hide();
//$( ".nextlink" ).hide();
//$( ".prevlink" ).hide();
$( ".prevphoto" ).show();
$( ".nextphoto" ).show();
$( ".nexts" ).hide();
$( ".prevs" ).hide();
$( ".photo-browser-slide" ).css("opacity","1");
//$( ".datebutton" ).css("height","40px");
//$( ".duckbutton" ).css("height","40px");
//$( ".datebutton img" ).css("height","30px");
//$( ".duckbutton img" ).css("height","30px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
$( ".photobrowserbar" ).css("background-color","transparent");
}
var comingback;
function scrollQuestions(){
//console.log($( ".wrapper-questions" ).offset().top);
//console.log($( window ).height());
var offsetline = $( window ).height() - 88;
var offsetdiv = $( ".wrapper-questions" ).offset().top;
//if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);}
var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
//if
// if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");}
//var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
}
function delayYo(){
}
function scrolltoTop(){
$( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 });
}
function questions(origin){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".toolbarq" ).css("background-color","transparent");
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".greytag" ).removeClass('bluetext');
var targetplugin = new_all[myPhotoBrowser.activeIndex].id;
//may need to readd this
//checkMatch(targetplugin);
comingback = 0;
if (origin){comingback = 1;}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();
}
//alert($('.photo-browser-slide img').css('height'));
if ($('.infopopup').length > 0) {
myApp.alert('Something went wrong. Try restarting the app and please report this to us.', 'Oops');
myApp.closeModal('.infopopup');return false;
}
$( ".vertical-pag" ).hide();
$( ".datefloat" ).show();
$( ".duckfloat" ).show();
$( ".datebutton" ).removeClass('imagelibrary');
$( ".duckbutton" ).removeClass('imagelibrary');
//$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)");
//$( ".swiper-container-vertical" ).css("margin-top","-27px");
//$( ".swiper-slide-active" ).css("height","100%");
//$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)");
//$( ".orlink" ).hide();
//$( ".uplink" ).show();
//$( ".nextlink" ).show();
//$( ".prevlink" ).show();
$( ".onlineblock" ).show();
//$( ".datebutton" ).css("height","70px");
//$( ".duckbutton" ).css("height","70px");
//$( ".datebutton img" ).css("height","60px");
//$( ".duckbutton img" ).css("height","60px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
//$( ".nametag" ).removeClass('whitetext');
var photobrowserHTML =
'<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;z-index:12000;" >'+
// ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+
// ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
'<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;">'+
'<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+
'</div>'+
' <div class="swiper-wrapper wrapper-questions" style="">'+
' </div>'+
'</div>'+
'</div>'
myApp.popup(photobrowserHTML,true,false);
$( ".nexts" ).show();
$( ".prevs" ).show();
$( ".prevphoto" ).hide();
$( ".nextphoto" ).hide();
for (i = 0; i < new_all.length; i++) {
var boxcolor,displayavail,availabilityli,availabletext,iconavaill;
iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';
$( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+
//'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+
'<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+
'</h3>'+
'<div onclick="scrolltoTop()" style="z-index:12000;margin-top:15px;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;display:none;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+
'<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+
'<div class="list-block" style="margin-top:0px;clear:both;">'+
'<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Online</div>'+
' <div class="item-input">'+
'<div class="timetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Distance</div>'+
' <div class="item-input">'+
'<div class="distancetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' </ul></div>'+
'</div>'+
'</div>');
//put here
if (new_all[i].description){
$( ".profileul_"+new_all[i].id ).prepend(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].hometown){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input">'+
'<textarea class="resizable" style="min-height:60px;max-height:132px;" readonly>'+new_all[i].hometown+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].industry){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].zodiac){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].politics){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].religion){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].ethnicity){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].eyes){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye Color</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].body){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].height != 0){
if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';}
$(".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+heightset+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].weight != 0){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
var timestring;
var minutevalue;
if (new_all[i].minutes <= 0){timestring = 'Now';}
if (new_all[i].minutes == 1){timestring = '1 minute ago';}
if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';}
if (new_all[i].minutes == 60){timestring = '1 hour ago';}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){
minutevalue = Math.round((new_all[i].minutes / 60));
if (minutevalue == 1) {timestring = '1 hour ago';}
else {timestring = minutevalue + ' hours ago';}
}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';}
if (new_all[i].minutes == 1440){timestring = '1 day ago';}
if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){
minutevalue = Math.round((new_all[i].minutes / 1440));
if (minutevalue == 1) {timestring = '1 day ago';}
else {timestring = minutevalue + ' days ago';}
}
if (new_all[i].minutes >= 10080){timestring = '1 week';}
if (new_all[i].minutes >= 20160){timestring = '2 weeks';}
if (new_all[i].minutes >= 30240){timestring = '3 weeks';}
$( ".timetag_" + new_all[i].id ).html(timestring);
$( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring);
}
swiperQuestions = myApp.swiper('.swiper-questions', {
nextButton:'.nexts',
prevButton:'.prevs',
onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));},
onInit:function(swiper){
myPhotoBrowser.swiper.setWrapperTranslate(0);
$( ".infoprofile").hide();
$( ".adown" ).css( "opacity","1" );
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
$( ".availyope").hide();
//$( ".availyo_"+ new_all[0].id ).show();
if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();}
//checkmatchwashere
//checkMatch(targetid);
},
onSlideChangeStart:function(swiper){
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
if(comingback === 1){
if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();}
if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();}
}
// if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
//}
// else{$( ".prevs" ).removeClass( "disabled" );}
// if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );}
// else{$( ".nexts" ).removeClass( "disabled" );}
//if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
// $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show();
// }
//else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//$( ".adown" ).css( "opacity","1" );
$( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount);
$( ".infoprofile").hide();
$( ".availyope").hide();
//$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%");
//$(".swiper-questions".css("background", "transparent");
$( ".swiper-questions" ).scrollTop( 0 );
if ($('.toolbarq').css('display') == 'block')
{
if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){
//alert(swiper.activeIndex - swiper.previousIndex);
//myPhotoBrowser.swiper.slideTo(0);
myPhotoBrowser.swiper.slideTo(swiper.activeIndex);
//swiper.slideTo(myPhotoBrowser.swiper.activeIndex);
}
}
//checkmatchwashere
//checkMatch(targetid);
}
});
//console.log(myPhotoBrowser.swiper.activeIndex);
swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0);
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".toolbarq" ).show();
comingback = 1;
$( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount);
$( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring);
//if (myPhotoBrowser.swiper.activeIndex === 0){
//myPhotoBrowser.swiper.slideNext();
//myPhotoBrowser.swiper.slidePrev();
//}
//else {
//}
//swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex);
}
function checkMatch(targetid){
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');}
else{$( ".indivnotifcount" ).remove();}
}
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;}
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;}
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function unmatchDate(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
dateUser();
});
}
function unmatchDuck(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
duckUser();
});
}
function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){
allowedchange = true;
photoresize = false;
if ($('.photo-browser').length > 0){return false;}
myApp.closeModal('.picker-sub');
//firebase.database().ref("users/" + f_uid).off('value', userpref);
var photobrowserclass="";
var duckfunction = ""
var datefunction = ""
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";}
else{duckfunction = "createDuck()";datefunction = "createDate1()";}
var to_open = 0;
if ($('.chatpop').length > 0 || chatorigin) {}
else {
to_open = openprofile;
}
var hiddendivheight = $( window ).height() - 40;
//alert(JSON.stringify(new_all));
myPhotoBrowser = myApp.photoBrowser({
zoom: false,
expositionHideCaptions:true,
lazyLoading:true,
lazyLoadingInPrevNext:true,
lazyPhotoTemplate:
'<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide" style="background-color:transparent;">'+
'<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+
'<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px;background-color:transparent;">'+
'<div class="swiper-wrapper vertical-wrapper-swiper">'+
'{{js "this.photos"}}'+
'</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+
'</div>',
exposition:false,
photos: new_all,
captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>',
toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+
' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDate();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDuck()" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-left:15px;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+
'<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+
' <div style="width:50px;overflow-x:hidden;position:absolute;right:1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;margin-left:-1px;">'+
'</div>'+
' </a>'+
' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+
' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-51px;"></div>'+
'</a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
' </div>'+
'</div>',
onClose:function(photobrowser){myApp.closeModal('.actions-modal');hideProfile();
singlefxallowed = true;
viewphotos = false;
viewscroll = false;
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();swiperQuestions = false;}
}
else{myApp.closeModal(); }
if (mainchange){new_all = main_all;singleuserarray = [];}
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
nextButton:'.nextphoto',
prevButton:'.prevphoto',
onSlideChangeStart:function(swiper){
if (allowedchange){
if (photoresize){
if ($('.infopopup').length > 0){}
else{
//getMeta(new_all[swiper.activeIndex].url);
}
}
if (swiper.activeIndex != openprofile){ photoresize = true;}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myApp.closeModal('.actions-modal');
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".duckbutton" ).hide();
$( ".datebutton" ).hide();
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
targetid = new_all[myPhotoBrowser.activeIndex].id;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
checkMatch(targetid);
},
backLinkText: '',
//expositionHideCaptions:true,
navbarTemplate:
// ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+
// ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
// '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+
'<div class="navbar photobrowserbar" style="background-color:#ccc">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
'<i class="pe-7s-angle-left pe-3x matchcolor greytag"></i>'+
'<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor greytag">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" onclick="actionSheet()">' +
//'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor greytag"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
myPhotoBrowser.open();
targetid = new_all[myPhotoBrowser.activeIndex].id;
var mySwiperVertical = myApp.swiper('.swiper-vertical', {
direction: 'vertical',
zoom:'true',
pagination:'.swiper-pagination',
paginationType:'progress',
onSlideChangeStart:function(swiper){
var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(",");
var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(",");
var trueh = verticalheightarray[swiper.activeIndex];
var truew = verticalwidtharray[swiper.activeIndex];;
if (trueh > truew){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else if (trueh == trueh){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else{
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
}
console.log(new_all[myPhotoBrowser.activeIndex]);},
onImagesReady:function(swiper){
console.log(swiper);},
onInit:function(swiper){
//console.log(new_all[myPhotoBrowser.activeIndex]);
//
if (viewphotos){
setTimeout(function(){ backtoProfile();viewphotos = false; }, 100);
}
if (viewscroll){
setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100);
}
},
onClick:function(swiper, event){
questions();
//if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");}
//else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");}
}
});
//var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myPhotoBrowser.swiper.slideTo(to_open,100);
checkMatch(targetid);
questions();
if (openprofile ===0){
if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );}
else{$( ".prevphoto" ).removeClass( "disabled" );}
if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );}
else{$( ".nextphoto" ).removeClass( "disabled" );}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
var target = new_all[myPhotoBrowser.activeIndex].url;
var pretarget = target.replace("https://graph.facebook.com/", "");
targetid = String(pretarget.replace("/picture?width=828", ""));
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
//may need to readd
}
}
function showProfile(){
$( ".profile-info" ).show();
}
function hideProfile(){
$( ".profile-info" ).hide();
}
function dateRequest(){
$( ".dateheader" ).hide();
$( ".date-close" ).hide();
$( ".date-button" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
sendNotification(targetid,2);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck request'}
if (d_type=='date'){smessage = 'Date request'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'daterequest',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
if(d_response=='Y') {chatShow();}
else {reverseRequest();}
});
}
}
var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted;
function existingDate(){
$( ".datearea" ).empty();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Test if user exists
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_type = snapshot.child('type').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
//$( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_message = false;
d_timeaccepted;
d_dateseen = false;
d_dateseentime = false;
d_timestamp = false;
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
});
}
function interests(id){
$( "." + id + "_i" ).toggleClass( "interestchosen" );
}
function sendMessage(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
else{console.log('it is a different day');prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var newmessage = $( "#messagearea" ).val();
if (newmessage === ''){return false;}
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:newmessage,
seen:'N',
timestamp: t_unix,
type: d_type,
param:'message',
authcheck:f_uid
});
myMessages.addMessage({
// Message text
text: newmessage,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
//myMessagebar.clear();
var messageq;
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
//alert('yo3');
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
//alert(obj.param);
// alert(obj.received);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
// alert('param'+obj.param);
// alert('new_message_count'+obj.new_message_count);
if (obj.param =='message'){
messageq = obj.new_message_count;
messageq ++;}
else{
messageq = 1;
}
}
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
}
});
}
newNotification(messageq);
});
function newNotification(messagenum){
//alert('messagenum'+messagenum);
if (!messagenum) {messagenum = 1;}
//alert(messagenum);
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:newmessage,
timestamp: t_unix,
type:d_type,
param:'message',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
$( "#messagearea" ).val('');
$( ".sendbutton" ).removeClass('disabled');
$( ".sendbutton" ).css('color','white');
sendNotification(targetid,4);
}
function clearchatHistory(){
singlefxallowed = true;
messages_loaded = false;
if (main_all[0] != null){
new_all = main_all;
}
singleuserarray = [];
letsload = 20;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if (message_history){
//firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications);
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon);
if(additions>0){
for (i = 0; i < additions.length; i++) {
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history);
}
}
message_history = false;
message_count = 0;
additions = 0;
existingmessages = false;
conversation_started = false;
myMessages.clean();
myMessages.destroy();
}
if (datealertvar === true){
firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert);
}
datealertvar = false;
if ($$('body').hasClass('with-panel-left-reveal')) {
$(".timeline").empty();
rightPanel();
}
if ($$('body').hasClass('with-panel-right-reveal')) {
myList.deleteAllItems();
myList.clearCache();
leftPanel();
}
}
function dateConfirmationPage(details){
$( ".datetoolbar" ).show();
canloadchat = false;
var g = new Date(d_chat_expire*1000 - 3600);
$( ".profileyomain" ).hide();
$( ".avail-loader" ).hide();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var gday = weekday[g.getDay()];
var proposeddate = g.getDate();
var month = [];
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var messageclass;
if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";}
else{messageclass = "message-received";messagestyle="margin-left:70px;";}
var proposedmonth = month[g.getMonth()];
var proposedyear = g.getFullYear();
var dending;
if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'}
else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'}
else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'}
else {dending = 'th'}
$( ".dateheader" ).hide();
$( ".profileroundpic" ).show();
$( ".date1-close" ).hide();
$( ".date2-close" ).hide();
$( ".message-inner" ).hide();
$( ".date-inner" ).hide();
$( ".date-back" ).show();
var timedisplay;
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname.capitalize());
var titleblock;
var namefromdate;
var nametodate;
if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;}
else{nametodate = f_first;namefromdate = targetname;}
var whatrow;
var dateseentitle;
var timestamptitle;
var capitalD;
if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';}
if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';}
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - d_timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 62) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (d_dateseen){
var unixago = unixnow - d_dateseentime;
var unixminago = unixago / 60;
if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';}
else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';}
else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 62) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';}
else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';}
}
else{dateseentitle = 'Request not seen yet';}
myApp.sizeNavbars();
var messagedateblock;
if (d_message){
messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>';
}
else {messagedateblock='';}
if (d_time) {timedisplay = ', ' + d_time}
else {timedisplay='';}
if (details){
var junixago = unixnow - d_timeaccepted;
var junixminago = junixago / 60;
var acceptedtitle;
if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';}
else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';}
else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 62) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';}
else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';}
$( ".date1-close" ).hide();
$( ".date2-close" ).show();
$( ".date-close" ).hide();
$( ".date-back" ).hide();
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".waitingreply" ).append(
'<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(capitalD + ' confirmed');
$( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type);
}
else if (d_created_uid == f_uid) {
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html('Waiting for '+targetname+' to respond');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
else{
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
$( ".datetoolbar" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).show();
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(targetname+' is waiting for your response');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
if (d_interest && d_type =='duck'){
$( ".interestli").show();
if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
}
if (d_interest && d_type =='date'){
for (i = 0; i < d_interest.length; i++) {
$( ".interestli").show();
$( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
}
}
}
function acceptDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
sendNotification(targetid,3);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
console.log(messageq);
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:'Date scheduled',
timestamp: t_unix,
type:d_type,
param:'dateconfirmed',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {chatShow();});
}
}
function cancelDate(){
// Create a reference to the file to delete
$( ".dateheader" ).hide();
$( ".sender-inner" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Delete the file
firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() {
// File deleted successfully
$( ".datearea" ).empty();
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_created_uid = false;
d_timestamp = false;
d_dateseen = false;
d_dateseentime = false;
d_message = false;
noMessages();
setDate();
console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
// Delete the file
firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() {
// File deleted successfully
console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
sendNotification(targetid,6);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck cancelled'}
if (d_type=='date'){smessage = 'Date cancelled'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'datedeleted',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
console.log('delete notification sent');
});
}
}
function getPicture(key){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
else{console.log('it is a different day');prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var t_unix = Math.round(+new Date()/1000);
var returned = 0;
var postkeyarray = [];
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var eventy = document.getElementById('takePictureField_').files[0];
// var number_of_pictures = $(".imageli").length + 1;
if (eventy == 'undefined') {console.log('undefined');}
if (eventy !== 'undefined') {
for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) {
var photoname = t_unix + i;
var newValue = firebase.database().ref().push().key;
postkeyarray.push(newValue);
myMessages.addMessage({
// Message text
text: '<img class="disabled image_'+newValue+'" src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup(\''+newValue+'\');" style="display:none;-webkit-filter: blur(50px);">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
//$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy));
image_count ++;
//$('.image_' + t_unix).onclick = function(){
// openPhoto(url);};
//var randomstring = (Math.random() +1).toString(36).substr(2, 30);
var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname;
var photostorage = 'images/' + f_auth_id + '/' + photoname;
var photochatsRef = storageRef.child(photostorage);
photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) {
var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name;
var photodownloadRef = storageRef.child(photodownloadstorage);
photodownloadRef.getDownloadURL().then(function(url) {
returned ++;
var newPostKey = postkeyarray[(returned-1)];
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var chatvar = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >',
seen:'N',
timestamp: snapshot.metadata.name,
type:d_type,
param:'image',
downloadurl:url,
first_number:first_number,
second_number:second_number
};
var photovar1 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
photo_name:photostorage,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number,
folder:f_auth_id
};
var photovar2 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number
};
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar);
firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1);
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2);
$(".image_"+newPostKey).attr("src", url);
$('.image_'+ newPostKey).removeClass("disabled");
$('.image_'+ newPostKey).css("-webkit-filter","none");
});
});
}
sendNotification(targetid,5);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
console.log(obj.received);
console.log(obj.from_uid);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newpictureNotification(messageq);
});
}
function newpictureNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:'Image ',
timestamp: t_unix,
type:d_type,
param:'image',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
}
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
var photoarray;
function showPhotos(){
photoarray= [];
myApp.pickerModal(
'<div class="picker-modal photo-picker" style="height:132px;">' +
'<div class="toolbar" style="background-color:#2196f3">' +
'<div class="toolbar-inner">' +
'<div class="left"></div>' +
'<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' +
'</div>' +
'</div>' +
'<div class="picker-modal-inner" style="background-color:#2196f3">' +
'<div class="content-block" style="margin:0px;padding:0px;">' +
'<div class="swiper-container swiper-photos">'+
'<div class="swiper-wrapper wrapper-photos">'+
' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+
'<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+
' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;background-color:red;height:88px;margin-top:-44px;" multiple="multiple"> '+
'</div>'+
'</div>'+
'</div>'+
'</div>' +
'</div>' +
'</div>'
);
var photosswiper = myApp.swiper('.swiper-photos', {
slidesPerView:3,
freeMode:true,
preloadImages: false,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true
//pagination:'.swiper-pagination'
});
firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) {
var childcount = 0;
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
//var key = childSnapshot.key;
// childData will be the actual contents of the child
childcount ++;
var childData = childSnapshot.val();
photoarray.push(childSnapshot.val());
$( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+
' <div class="swiper-lazy-preloader"></div>'+
'</div>');
if (childcount == snapshot.numChildren()){
photosswiper.updateSlidesSize();
photosswiper.slideTo(snapshot.numChildren());
// photosswiper.slideTo(0);
}
});
});
}
function sendphotoExisting(oldurl,filenamez){
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
myMessages.addMessage({
// Message text
text: '<img src="'+oldurl+'" onload="scrollBottom();">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first
// Day
// day: !conversationStarted ? 'Today' : false,
// time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
});
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+oldurl+'" onload="scrollBottom();">',
seen:'N',
timestamp: t_unix,
type:d_type,
param:'image',
filename:filenamez
});
myApp.closeModal('.photo-picker');
}
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
var xcountdown;
function imagesPopup(go){
if ($('.gallery-popupz').length > 0) {return false;}
var goz;
var popupHTML = '<div class="popup gallery-popupz">'+
'<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+
' <div class="center gallerytitle"></div>'+
' <div class="right photo-count"></div>'+
'</div>'+
'</div>'+
'<div class="pages">'+
'<div data-page="gallerypopup" class="page">'+
'<div class="page-content" style="background-color:white;">'+
'<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+
'<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+
'<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+
' <div class="swiper-wrapper gallery-wrapper">'+
' </div>'+
'</div>'+
'<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+
'</div></div></div>'+
'</div>';
myApp.popup(popupHTML);
var first_number,second_number;
var gallerycount;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var galleryimagecount = 0;
var photodeletetime;
var phototo;
var photofrom;
var photochatid;
var touid;
firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value")
.then(function(snapshot) {
gallerycount = snapshot.numChildren();
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if (obj.id == go){goz = galleryimagecount;}
var expiryval;
if (obj.photo_expiry == null){expiryval = i;}
else {expiryval = obj.photo_expiry;}
$( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+
'<div class="swiper-zoom-container">'+
'<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+
' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>');
galleryimagecount ++;
});
var galleryswiper = myApp.swiper('.swiper-gallery', {
preloadImages: false,
lazyLoadingInPrevNext:true,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true,
zoom:true,
onInit:function(swiper){var slidenum = swiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
},
onSlideChangeStart:function(swiper){clearInterval(xcountdown);
var slidenum = galleryswiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();deletePhotochat();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
myApp.sizeNavbars();
},
pagination:'.swiper-pagination-gallery',
paginationType:'progress'
});
galleryswiper.slideTo(goz,0);
myApp.sizeNavbars();
});
function deletePhotochat(){
if (photodeletetime < (new Date().getTime() / 1000)){
$( ".photochat_"+ photodeletetime).remove();
galleryswiper.update();
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
}
}
function photodeletecount(){
var countDownDate = new Date(photodeletetime * 1000);
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h "
+ minutes + "m " ;
// Update the count down every 1 second
xcountdown = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(xcountdown);
deletePhotochat();
}
else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h "
+ minutes + "m " ;myApp.sizeNavbars();}
}, 60000);
}
}
function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();}
function closeGallery(){
myApp.closeModal('.gallery-popupz');
clearInterval(xcountdown);
}
function updateOnce(){
var uids = ["1381063698874268","1394352877264527","393790024114307","4"];
firebase.database().ref('users/' + f_uid).update({
date_me:uids
});
}
function updatePhotos(){
$( ".pp" ).each(function() {
var classList = $(this).attr("class").split(' ');
var idofphoto = classList[2].replace("photo_", "");
var index1 = f_date_match.indexOf(idofphoto);
var index2 = f_duck_match.indexOf(idofphoto);
var u_date_me = f_date_me.indexOf(idofphoto);
var u_to_date = f_to_date.indexOf(idofphoto);
var u_duck_me = f_duck_me.indexOf(idofphoto);
var u_to_duck = f_to_duck.indexOf(idofphoto);
if (index2 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='duck';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else if (index1 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='date';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" );
$( ".iconpos_" + idofphoto ).empty();
$( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" );
if (u_date_me > -1){
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if (u_duck_me > -1) {
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if ($( '.rr').hasClass('r_' + idofphoto)) {
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
// alert(u_date_me);
// alert(u_duck_me);
if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" );
}
else {$( ".datebutton" ).removeClass( "likesme" );}
if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" );
}
else {$( ".duckbutton" ).removeClass( "likesme" );}
}
}
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
function singleBrowser(idw,idname,origin){
//firebase.database().ref("users/" + f_uid).off('value', userpref);
//targetid = idw;
targetid = String(idw);
targetname = idname;
var dbuttons;
if (origin){
dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
else {
dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
singlePhotoBrowser = myApp.photoBrowser({
zoom: 400,
lazyLoading:true,
lazyLoadingInPrevNext:true,
//exposition:false,
photos: [{
url: 'https://graph.facebook.com/'+targetid+'/picture?type=large',
caption: '...'
}],
toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+
dbuttons+
' <div class="toolbar-inner toolbardecide">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+
' <a href="#" class="link orlink">'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+
' </a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+
' </div>'+
'</div>',
onOpen:function(photobrowser){
$( ".chatpop" ).css( "z-index","10000" );},
onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" );
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
backLinkText: '',
navbarTemplate: '<div class="navbar photobrowserbar">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
// ' <i class="icon icon-back {{iconsColorClass}}"></i> '+
'<i class="pe-7s-angle-left pe-3x"></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
' <i class="pe-7s-angle-left pe-3x "></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" >' +
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
singlePhotoBrowser.open();
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>');
var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "width", windowwidth + "px" );
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} )
.done(function( data ) {
var result = JSON.parse(data);
var targetdescription= result[0].description;
//var targetname = result[0].name.substr(0,result[0].name.indexOf(' '));
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
});
}).catch(function(error) {
// Handle error
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function deletePhotos(){
var unix = Math.round(+new Date()/1000);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
$.each(objs, function(i, obj) {
$.each(obj, function(i, obk) {
if(obk.photo_expiry){
if (obk.photo_expiry < Number(unix)){
//alert('a photo to delete exists');
firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
}).catch(function(error) {
});
//blocking out
}
}
});
});
}
});
}
function createDuck(idq,nameq,redirect){
keepopen = 1;
d_type = 'duck';
if (idq) {createDate(idq,nameq,redirect)}
else{createDate();}
}
function createDate1(idz,name,redirect){
d_type = 'date';
keepopen = 1;
if (idz) {createDate(idz,name,redirect)}
else{createDate();}
}
function duckClass(place){
if (place ==1) {
if ($( ".button-my" ).hasClass( "active" )){
$('.button-my').removeClass("active");$('.button-your').removeClass("active");
}
else {$('.button-my').addClass("active");$('.button-your').removeClass("active");}
}
if (place ==2) {
if ($( ".button-your" ).hasClass( "active" )){
$('.button-your').removeClass("active");$('.button-my').removeClass("active");
}
else {$('.button-your').addClass("active");$('.button-my').removeClass("active");}
}
}
function matchNotif(){
function newNotificationm(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'New match'}
if (d_type=='date'){smessage = 'New match'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:f_image,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'newmatch',
new_message_count:0,
received:'N',
expire:'',
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
console.log('delete notification sent');
});
}
sendNotification(targetid,1);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq = 0;
//If existing notifications, get number of unseen messages, delete old notifications
console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotificationm(messageq);
});
}
function unmatchNotif(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref('dates/' + f_uid +'/' + targetid).remove();
firebase.database().ref('dates/' + targetid +'/' + f_uid).remove();
firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove();
firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove();
myApp.closePanel();
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
function insertAfterNthChild($parent, index, content){
$(content).insertBefore($parent.children().eq(index));
}
//function changeRadius(number){
//$('.radiusbutton').removeClass('active');
//$('#distance_'+ number).addClass('active');
//processUpdate();
//}
function sortBy(number){
var relevanticon;
var relevanttext;
//if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.sortbutton').removeClass('active');
$('.sortby_'+ number).addClass('active');
if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';}
if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';}
if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';}
firebase.database().ref('users/' + f_uid).update({
sort:sortby
});
}
function addcreateDate(){
$('.left-title').text(f_duck_match_data.length + 'want to date you');
myApp.sizeNavbars();
$('.timeline-upcoming').empty();
for (i = 0; i < f_date_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fdateicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
for (i = 0; i < f_duck_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fduckicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){
$('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>');
}
}
function unblock(){
myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () {
var iblockedfirst = [];
var iblockedsecond = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)}
if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)}
});
}
if (iblockedfirst.length){
for (i = 0; i < iblockedfirst.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
}
}
if (iblockedsecond.length){
for (i = 0; i < iblockedsecond.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
}
}
getWifilocation();
$( ".blockbutton" ).addClass('disabled');
})
});
}
function deleteAccount(){
//users
//photos2delete -> photos in storage
//chats
//matches
myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () {
var matchesarray = [];
var firstnumberarray = [];
var secondnumberarray = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);});
for (i = 0; i < matchesarray.length; i++) {
var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]);
mymatches.remove().then(function() {
console.log("My matches Remove succeeded.")
})
.catch(function(error) {
console.log("My matches Remove failed: " + error.message)
});
var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid);
theirmatches.remove().then(function() {
console.log("Their matches Remove succeeded.")
})
.catch(function(error) {
console.log("Their matches Remove failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]);
mydates.remove().then(function() {
console.log("My dates Remove succeeded.")
})
.catch(function(error) {
console.log("My dates Remove failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid);
theirdates.remove().then(function() {
console.log("Their dates Remove succeeded.")
})
.catch(function(error) {
console.log("Their dates Remove failed: " + error.message)
});
var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid);
theirnotifs.remove().then(function() {
console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
console.log("their notifs failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourchats.remove().then(function() {
console.log("Chats Remove succeeded.")
})
.catch(function(error) {
console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourphotochats.remove().then(function() {
console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
console.log("PhotoChats Remove failed: " + error.message)
});
}
}
firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
console.log(objs);
if (snapshot.val()){
$.each(objs, function(i, obj) {
var targetdeleteid;
if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;}
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid);
mynotifs.remove().then(function() {
console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
console.log("my notifs failed: " + error.message)
});
});
}
firebase.database().ref('users/' + f_uid).set({
auth_id : f_auth_id,
deleted:'Y'
});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
console.log(data);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objr = snapshot.val();
if (snapshot.val()){
$.each(objr, function(i, obj) {
$.each(obj, function(i, obk) {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
}).catch(function(error) {
console.log(error);
});
});
});
}
FCMPlugin.unsubscribeFromTopic(f_uid);
cordova.plugins.notification.badge.set(0);
var loginmethod = window.localStorage.getItem("loginmethod");
if (loginmethod == '1'){logoutPlugin();}
else{logoutOpen();}
});
});
}).catch(function(error) {
// Handle error
});
});
});
});
}
function matchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#2196f3");
$( ".matchcolor" ).addClass('whitetext');
}
else {$( ".toolbarq" ).hide();}
}
function unmatchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".matchcolor" ).removeClass('whitetext');
$( ".toolbarq" ).css("background-color","transparent");
}
else {$( ".toolbarq" ).hide();}
}
var notifloaded = false;
function establishNotif(){
if(notifcount) {alert('removing old notifs');firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) {
var notificationscount = 0;
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if (obj.to_uid == f_uid) {
if (obj.received =='Y') {
if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();}
}
if (obj.received =='N') {
var addnumber;
if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;}
else {addnumber = obj.new_message_count}
notificationscount = notificationscount + addnumber;
if (notifloaded){
if (obj.new_message_count > 0){
//alert('Not received, greater than 0 = ' +obj.new_message_count);
$( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');
$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');
cordova.plugins.notification.badge.set(notificationscount);
}
}
}
}
});
notifloaded = true;
//Update SQL notifcount
if (notificationscount !=0){
if (offsounds == 'Y'){}else{
$('#buzzer')[0].play();
//if ($('.chatpop').length > 0) {}
//else {$('#buzzer')[0].play();}
}
return false;
}
else{}
//$( ".notifspan" ).empty();
//$( ".notifspan" ).append(notificationscount);
}
});
}
function showPloader(){
$( ".ploader" ).css("z-index","9999999");myApp.closeModal();
}
function hidePloader(tabb){
var popupHTML = '<div class="popup prefpop">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab1" class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Terms and Conditions of Use</div>'+
' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-1" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner terms-inner" >'+
' </div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div id="tab2" class="view tab">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Privacy Policy</div>'+
' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-2" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner privacy-inner">'+
' </div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
'<div class="toolbar tabbar" style="padding:0px;background-color:#ccc;">'+
' <div class="toolbar-inner" style="padding:0px;">'+
' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+
' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-look pe-lg"></i></a>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
$( ".ploader" ).css("z-index","10000");
if (tabb) {
tabTwo();
}
else {tabOne();}
}
function tabOne(){
$( "#tab1" ).addClass('active');
$( "#tab2" ).removeClass('active');
myApp.sizeNavbars();
$( ".tab1" ).addClass('active');
$( ".tab2" ).removeClass('active');
$.get( "http://www.dateorduck.com/terms.html", function( data ) {
$( ".terms-inner" ).html(data);
});
}
function tabTwo(){
$( "#tab1" ).removeClass('active');
$( "#tab2" ).addClass('active');
myApp.sizeNavbars();
$( ".tab1" ).removeClass('active');
$( ".tab2" ).addClass('active');
$.get( "http://www.dateorduck.com/privacy.html", function( data ) {
$( ".privacy-inner" ).html(data);
});
}
//check if on mobile
//}
var pagingalbumurl;
var pagingurl;
var photonumber;
var albumend;
var addedsmallarray;
var addedlargearray;
var addedheight = [];
var addedwidth = [];
function getPhotos(albumid){
$( ".photoloader").show();
$( ".loadmorebuttonphotos").hide();
var retrieveurl;
if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/v2.4/'+albumid+'/photos?limit=8&fields=id,source,width,height&access_token=' + f_token}
else {retrieveurl = pagingurl}
$.getJSON(retrieveurl,
function(response) {
$( ".swipebuttondone").addClass("disabled");
$( ".photoloader").hide();
if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;}
console.log(response);
pagingurl = response.paging.next;
for (i = 0; i < response.data.length; i++) {
var alreadyselected = addedsmallarray.indexOf(response.data[i].source);
console.log(response.data[i]);
if (alreadyselected == -1) {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>');
}
else {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>');
}
photonumber ++;
}
if (response.data.length > 0 && response.data.length < 8) {
$( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();}
else{$( ".loadmorebuttonphotos").show();}
});
}
function closePhotos(){
$( ".albumblock").show();
$( ".leftalbum").show();
$( ".leftphoto").hide();
$( "#nomorephotos").hide();
$( "#nophotosfound").hide();
$( ".loadmorebuttonphotos").hide();
if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();}
else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();}
swiperPhotos.removeAllSlides();
swiperPhotos.destroy();
photonumber = 0;
pagingurl = false;
}
function closeAlbums(){
myApp.closeModal('.photopopup');
addedsmallarray = [];
addedlargearray = [];
pagingalbumurl = false;
albumend = false;
$( ".swipebuttondone").removeClass("disabled");
}
function photosPopup(){
photosliderupdated = false;
addedsmallarray = f_smallurls;
addedlargearray = f_largeurls;
var popupHTML = '<div class="popup photopopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" onclick="closeAlbums()" style="margin-left:-10px;"></i>'+
'<i class="pe-7s-angle-left pe-3x leftphoto" onclick="closePhotos()" style="display:none;margin-left:-10px;"></i>'+
' </div>'+
' <div class="center photocount">'+
'0 photos selected'+
'</div>'+
' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="photospage" class="page">'+
' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+
'<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="list-block media-list albumblock" style="margin:0px;z-index:999999;"><ul class="albumul" style="z-index:99999999999;"></ul></div>'+
'<div class="swiper-container swiper-photos">'+
' <div class="swiper-wrapper" >'+
'</div>'+
'</div>'+
'<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more albums</a>'+
'<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more photos</a>'+
'<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+
'<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+
'<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
photoPermissions();
}
function loadAlbums(){
$( ".photoloader").show();
$( ".loadmorebuttonalbums").hide();
var retrievealbumurl;
if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/v2.4/'+f_uid+'/albums?limit=20&fields=id,count,name&access_token=' + f_token}
else {retrievealbumurl = pagingalbumurl}
$.getJSON(retrievealbumurl,
function(response) {
if(response.data.length == 0){
myApp.alert('Upload photos to Facebook to make them available to use in this app.', 'No photos are available');myApp.closeModal('.photopopup');return false;
}
pagingalbumurl = response.paging.next;
if (response.data.length > 0){
for (i = 0; i < response.data.length; i++) {
$( ".albumul" ).append(
' <li onclick="getAlbum('+response.data[i].id+')">'+
' <div class="item-content">'+
' <div class="item-media">'+
' <i class="pe-7s-photo-gallery pe-lg"></i>'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">'+response.data[i].name+'</div>'+
' <div class="item-after">'+response.data[i].count+'</div>'+
'</div>'+
'</div>'+
' </div>'+
' </li>'
);
}
}
if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();$( ".photoloader").hide();albumend = true;}
else{$( ".loadmorebuttonalbums").show();}
});
}
function getAlbum(albumid){
$( ".albumblock").hide();
$( ".loadmorebuttonalbums").hide();
$( "#nomorealbums").hide();
$( ".leftalbum").hide();
$( ".leftphoto").show();
swiperPhotos = myApp.swiper('.swiper-photos', {
slidesPerView:2,
slidesPerColumn:1000,
virtualTranslate:true,
slidesPerColumnFill:'row',
spaceBetween: 3,
onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$( ".noparray").hide();
$( ".yesparray").show();
if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
var indexdeletedsm = addedsmallarray.indexOf(smallurl);
addedsmallarray.splice(indexdeletedsm, 1);
var indexdeletedsl = addedlargearray.indexOf(smallurl);
addedlargearray.splice(indexdeletedsl, 1);
addedheight.splice(indexdeletedsl, 1);
addedwidth.splice(indexdeletedsl, 1);
console.log(addedheight);
}
else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
addedsmallarray.push(smallurl);
addedlargearray.push(largeurl);
var widthselected = $( ".width_"+photoselectedid).val();
var heightselected = $( ".height_"+photoselectedid).val();
addedheight.push(heightselected);
addedwidth.push(widthselected);
}
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
}
});
getPhotos(albumid);
swiperPhotos.updateContainerSize();
swiperPhotos.updateSlidesSize();
}
function getPhotoURL(){
photonumber = 0;
pagingurl = false;
pagingalbumurl = false;
albumend = false;
var newsmall = addedsmallarray.toString();
var newlarge = addedlargearray.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
$( ".swipebuttondone").removeClass("disabled");
if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');}
}
if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');}
}
updatephotoslider();
//swiperPhotos.removeAllSlides();
//swiperPhotos.destroy();
myApp.closeModal('.photopopup');
});
}).catch(function(error) {
// Handle error
});
}
var photosliderupdated;
function updatephotoslider(){
$( ".yesparray").addClass("disabled");
if (photosliderupdated){return false;}
photosliderupdated = true;
myswiperphotos.removeAllSlides();
if (addedlargearray.length > 0){
myswiperphotos.removeAllSlides();
for (i = 0; i < addedlargearray.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (addedlargearray.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
addedsmallarray = [];
addedlargearray = [];
}
else {
myswiperphotos.removeAllSlides();
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
}
}
function reorderPhotos(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var popupHTML = '<div class="popup redorderpopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" style="margin-left:-10px;" onclick="closeReorder()"></i>'+
' </div>'+
' <div class="center">'+
'Order Photos'+
'</div>'+
' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="redorderpage" class="page">'+
' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+
' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+
' <ul class="numbersul" style="background-color:transparent;">'+
' </ul>'+
'</div>'+
' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+
' <ul class="sortableul">'+
' </ul>'+
'</div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
for (i = 0; i < f_largeurls.length; i++) {
$( ".numbersul" ).append(
'<li style="margin-top:10px;">'+
' <div class="item-content" style="height:80px;">'+
'<div class="item-inner reorderinner">'+
' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+
'</div>'+
' </div>'+
'</li>'
);
$( ".sortableul" ).append(
' <li style="margin-top:10px;">'+
' <div class="item-content sortdivb" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+
' </div>'+
' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+
' </li>'
);
}
myApp.sortableOpen();
}
function closeReorder(){
myApp.closeModal('.redorderpopup');
}
function changeOrder(){
var newurl = [];
$( ".sortdivb" ).each(function() {
var bg = $(this).css("background-image");
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
newurl.push(bg);
});
myswiperphotos.removeAllSlides();
for (i = 0; i < newurl.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Remove</div></div>');
}
myApp.closeModal('.redorderpopup');
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
var newsmall = newurl.toString();
var newlarge = newurl.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
f_largeurls = newurl;
}
function deleteAllPhotos(){
myApp.confirm('Are you sure?', 'Remove all photos', function () {
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
deletedphoto = false;
myswiperphotos.removeAllSlides();
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.update();
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
f_largeurls = [];
f_smallurls = [];
var newsmall = "";
var newlarge = "";
var newwidth = "";
var newheight = "";
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
console.log('deleted all');
});
}).catch(function(error) {
// Handle error
});
});
}
var f_smallurls = [];
var f_largeurls = [];
var photosloaded;
function swipePopup(chosen){
$( '.picker-sub' ).hide();
myApp.closeModal('.picker-sub');
photosloaded = false;
var sliderwidth = $( document ).width();
var sliderheight = $( document ).height();
var popupHTML = '<div class="popup prefpop" style="z-index:11000">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab99" class="view-99 view tab active">'+
//
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left" style="color:white;"></div>'+
' <div class="center swipetext" style="color:white;">Availability'+
//'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+
'</div>'+
' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange swipebuttondone">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange swipebuttondone">Done</a></div>'+
'</div>'+
'</div>'+
' <div class="pages">'+
' <div data-page="home-3" class="page">'+
'<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;z-index:9999999999;position:absolute;bottom:0px;">'+
' <div class="toolbar-inner" style="padding:0;">'+
// ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan0 " onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan1" onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>'+
'</div>'+
' <div class="page-content" style="height: calc(100% - 44px);background-color:white;">'+
'<div class="swiper-container swiper-prefer" style="padding-top:54px;margin-bottom:-44px;">'+
'<div class="swiper-wrapper">'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-0">'+
'<div class="list-block media-list availblock" style="margin-bottom:0px;margin-top:0px;">'+
' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+
' </ul>'+
'<div class="list-block-label hiderowpref" style="margin-top:10px;">Make it easier for your matches to organise a time to meet you.</div>'+
'</div> '+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-1">'+
'<div style="background-color:transparent;width:100%;padding-bottom:10px;" class="registerdiv">'+
'<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul class="aboutul">'+
'<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+
'<li class="newam" style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">I am</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="newme">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">Preference</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe2">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="align-top hiderowpref">'+
' <div class="item-content">'+
//'<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="item-inner">'+
'<div class="item-title label">About Me</div>'+
' <div class="item-input">'+
' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="width: calc(100% - 40px);min-height:88px;max-height:176px;" placeholder="Hide"></textarea>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:12px;margin-top:-20px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+
' <li class="hiderowpref hometownli" style="clear:both;margin-top:0px;">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input hometown-input">'+
' <textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Status</div>'+
' <div class="item-input status-div">'+
' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input industry-div">'+
' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input zodiac-div">'+
' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input politics-div">'+
' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input religion-div">'+
' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input ethnicity-div">'+
' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye color</div>'+
' <div class="item-input eyes-div">'+
' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input body-div">'+
' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input height-div">'+
' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input weight-div">'+
' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">All fields are optional and will be hidden on your profile unless completed.</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-2">'+
'<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;top:50%;position: absolute;left: 50%;margin-left: -28.7px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+
'<div class="swiper-wrapper wrapper-photos">'+
'</div>'+
'<div class="swiper-pagination"></div>'+
'</div>'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+
' <div class="buttons-row">'+
'<a href="#" class="button active" onclick="photosPopup();" style="font-size:17px;border:0;border-radius:0px;background-color:#4cd964;margin-left:5px;margin-right:5px;">Add</a>'+
'<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;">Re-order</a>'+
'<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;background-color:#ff3b30;color:white">Clear</a>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul">'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">Photos can be uploaded from your Facebook account.</div>'+
'</ul></div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-3">'+
'<div class="content-block-title" style="margin-top:20px;">Search options</div>'+
// '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+
// '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+
// '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+
// '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+
// '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+
//'</p>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;">Search radius</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="distance-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;"></div>'+
' <div class="item-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>'+
'<div class="content-block-title" style="margin-top:-54px;">Sounds</div>'+
' <div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner" style="float:left;">'+
'<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:17px;font-weight:normal;">Turn off sounds</div>'+
' <div class="item-input" style="width:52px;float:left;">'+
'<label class="label-switch">'+
' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+
'<div class="checkbox" ></div>'+
' </label>'+
' </div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="font-size:17px;border:0;border-radius:0px;">Unblock all </div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">My Account</div>'+
'<li onclick="logout()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title active button" style="border:0;border-radius:0px;font-size:17px;">Logout</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
' <li onclick="deleteAccount()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button" style="font-size:17px;border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'</ul>'+
'</div> '+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
//tabs
'</div>'+
'</div>'+
//tabs
'</div>';
myApp.popup(popupHTML);
if (blocklist){
if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');}
}
if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');}
if(!sexuality){
$( ".swipetoolbar" ).hide();
}
//if (radiussize) {distancepicker.cols[0].setValue(radiussize);}
distancepicker = myApp.picker({
input: '#distance-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + ($( document ).width()/2) + "px");distancepicker.cols[0].setValue(radiussize);distancepicker.cols[1].setValue(radiusunit);if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onClose:function (p, values, displayValues){radiussize = distancepicker.value[0];
radiusunit = distancepicker.value[1];},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Search Distance'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100').split(' ')
},
{
textAlign: 'left',
values: ('Kilometres Miles').split(' ')
},
]
});
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var findustrypicker = myApp.picker({
input: '#f-industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (f_industry_u) {findustrypicker.cols[0].setValue(f_industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#f-industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'f_industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
$( ".slide-pref" ).hide();
mySwiper = myApp.swiper('.swiper-prefer', {
onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );},
onInit:function(swiper){$( ".swipetoolbar" ).show();$( ".pan" + swiper.activeIndex ).addClass('active');},
onSlideChangeStart:function(swiper){
$( ".page-content" ).scrollTop( 0 );
$( ".tab-swipe").removeClass('active');
$( ".pan" + swiper.activeIndex ).addClass('active');
if (swiper.activeIndex == 0){$( ".swipetext" ).text('Availability');
$( ".slide-pref" ).hide();$( ".pref-0").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 1){$( ".swipetext" ).text('Profile');
$( ".slide-pref" ).hide();$( ".pref-1").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 2){$( ".swipetext" ).text('Photos');getData();
$( ".slide-pref" ).hide();$( ".pref-2").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 3){$( ".swipetext" ).text('Settings');
$( ".slide-pref" ).hide();$( ".pref-3").show();$( ".swipetoolbar" ).show();
}
if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();}
}
});
swipePref(chosen);
setTimeout(function(){ $( ".swipetoolbar" ).show(); }, 3000);
myApp.sizeNavbars();
var dateinfo = [];
var s_namesonly = [];
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var daynumber;
var todayday = weekday[d.getDay()];
console.log(todayday);
s_namesonly.push(todayday);
var f_available_array;
var s_alldays_values = [];
var s_alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
daynumber;
daynumber = d.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear());
s_alldays_values.push(tonight_timestamp);
s_alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
var tomorrowdate = new Date(Date.now() + 86400);
var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000);
var tomorrowday = weekday[tomorroww.getDay()];
daynumber = tomorroww.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear());
console.log('tomorrow is' + tomorrowday);
s_namesonly.push(tomorrowday);
s_alldays_values.push(tomorrow_timestamp);
s_alldays_names.push('Tomorrow');
for (i = 1; i < 7; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
s_alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
daynumber = datz.getDate();
var dending;
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
n = weekday[datz.getDay()];
qqq = weekday[datz.getDay() - 1];
console.log(n);
s_alldays_names.push(n + ' ' + daynumber + dending);
dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear());
s_namesonly.push(n);
}
s_namesonly.push(n);
console.log(s_namesonly);
console.log(s_alldays_values);
for (i = 0; i < s_alldays_names.length; i++) {
if (i==0 | i==2 || i==4 || i==6){
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
else if (i==1 || i==3 || i==5 || i==7) {
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
'<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
var alreadyavailchosen = 0;
var columnone;
var columntwo;
var idtochange;
for(var k = 0; k < availarray.length; k++) {
if (availarray[k].id == s_alldays_values[i]){
alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day;
idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); }
else{
alreadyavailchosen = 0;
}
}
function setPicker(){
var myavailpicker = myApp.picker({
input: '#picker' + s_alldays_values[i],
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (s_namesonly[i] + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
}
if (myphotosarray){
}
else {
}
if (f_description){
$( "#userdescription" ).val(f_description);
var inputlengthd = $( "#userdescription" ).val().length;
$( "#maxdescription" ).text(inputlengthd + ' / 100 ');
}
if (radiussize){
$( ".radiusbutton" ).removeClass( "active" );
$( "#distance_" + radiussize ).addClass( "active" );
}
if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);}
else{$('#soundnotif').prop('checked', false);}
if (f_age) {$( ".savebutton" ).removeClass('disabled');}
if (!sexuality){$( "#distance-input" ).val( '100 Kilometres');}
else {$( "#distance-input" ).val( radiussize + ' ' +radiusunit);
}
if(hometown_u){$( "#homesearch" ).val( hometown_u );}
if(industry_u){$( "#industry-input" ).val( industry_u );}
if(status_u){$( "#status-input" ).val( status_u );}
if(politics_u){$( "#politics-input" ).val( politics_u );}
if(eyes_u){$( "#eyes-input" ).val( eyes_u );}
if(body_u){$( "#body-input" ).val( body_u );}
if(religion_u){$( "#religion-input" ).val( religion_u );}
if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );}
if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );}
if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );}
if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
$( "#height-input" ).val( heightset );
}
if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );}
if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );}
pickerDescribe = myApp.picker({
input: '#picker-describe',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onOpen: function (p){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.picker-items-col').eq(0).css('width','50%');
$('.picker-items-col').eq(1).css('width','50%');
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
var gendercol = pickerDescribe.cols[0];
var agecol = pickerDescribe.cols[1];
if (f_age) {agecol.setValue(f_age);}
if (f_gender) {gendercol.setValue(f_gender);}
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
formatValue: function (p, values, displayValues) {
return displayValues[0] + ', ' + values[1];
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'I Am'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Male Female').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
pickerDescribe2 = myApp.picker({
input: '#picker-describe2',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
$('.picker-items-col').eq(0).css('width','33%');
$('.picker-items-col').eq(1).css('width','33%');
$('.picker-items-col').eq(2).css('width','33%');
var interestedcol = pickerDescribe2.cols[0];
var lowercol = pickerDescribe2.cols[1];
var uppercol = pickerDescribe2.cols[2];
if (f_interested) {interestedcol.setValue(f_interested);}
if (f_lower) {lowercol.setValue(f_lower);}
if (f_upper) {uppercol.setValue(f_upper);}
},
formatValue: function (p, values, displayValues) {
if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];}
else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2];
}
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Preference'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Men Women').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
}
function swipePref(index){$( ".swipetoolbar" ).show();$( ".pref-" + index).show();mySwiper.slideTo(index); $( ".swipetoolbar" ).show();
}
function navPicker(){
myApp.pickerModal(
'<div class="picker-modal picker-sub" style="height:88px;">' +
'<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' +
'<div class="toolbar-inner" style="padding:0;">' +
' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>' +
'</div>' +
'<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' +
'<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+
'</div>' +
'</div>'
);
}
function removeProfileSet(pickertype){
$( "#" + pickertype + "-input").remove();
$( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' );
if (pickertype=='industry'){
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);}
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
}
if (pickertype=='status'){
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
}
if (pickertype=='politics'){
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
}
if (pickertype=='zodiac'){
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
}
if (pickertype=='religion'){
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
}
if (pickertype=='ethnicity'){
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
}
if (pickertype=='height'){
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
}
if (pickertype=='weight'){
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
}
if (pickertype=='eyes'){var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
}
if (pickertype=='body'){
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
}
}
function actionSheet(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}
},
{
text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
myApp.closeModal() ;backtoProfile();
}
else{}
}
},
{
text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
else {
var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid);
//var elementPos = new_all.findIndex(x => x.id==targetid);
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}else{viewscroll = true;singleUser(targetid,targetname);}
}
},
{
text: 'View Profile Photos ('+new_all[elementPos].photocount+')',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
backtoProfile();
}else{viewphotos = true;singleUser(targetid,targetname);}
}
},
{ text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
myApp.actions(buttons);
var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number);
photobombsheet.once('value', function(snapshot) {
if(snapshot.val()){$(".color-green").removeClass('disabled');
$(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')');
}
});
}
| Update app.js | www/js/app.js | Update app.js | <ide><path>ww/js/app.js
<ide> function fcm(){
<ide> NativeKeyboard.showMessenger({
<ide> onSubmit: function(text) {
<del> console.log("The user typed: " + text);
<add> //console.log("The user typed: " + text);
<ide> }
<ide> });
<ide>
<ide>
<ide>
<ide> },
<del> error: function (jqXHR, textStatus, errorThrown) {console.log(errorThrown);
<add> error: function (jqXHR, textStatus, errorThrown) {
<add> //console.log(errorThrown);
<ide> },
<ide> complete: function () {
<ide> }
<ide> });
<ide>
<ide> },
<del> error: function (jqXHR, textStatus, errorThrown) {console.log(errorThrown);
<add> error: function (jqXHR, textStatus, errorThrown) {
<add> //console.log(errorThrown);
<ide> },
<ide> complete: function () {
<ide> }
<ide>
<ide> if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){
<ide>
<del>console.log(result[i].availstring);
<add>//console.log(result[i].availstring);
<ide> var availablearrayindividual = JSON.parse(result[i].availstring);
<ide>
<del>console.log(availablearrayindividual);
<add>//console.log(availablearrayindividual);
<ide>
<ide> for (k = 0; k < availablearrayindividual.length; k++) {
<ide> if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
<ide> var heightarray = result[i].heightslides.split(",");
<ide> var widtharray = result[i].widthslides.split(",");
<ide>
<del>console.log(heightarray[0]);
<del>console.log(widtharray[0]);
<add>//console.log(heightarray[0]);
<add>//console.log(widtharray[0]);
<ide>
<ide> if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'}
<ide> if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'}
<ide> var mmn = zz.getTimezoneOffset();
<ide>
<ide>
<del>console.log(result[i].timestamp);
<add>//console.log(result[i].timestamp);
<ide>
<ide> var timestampyear = result[i].timestamp.substring(0,4);
<ide> var timestampmonth = result[i].timestamp.substring(5,7);
<ide>
<ide> .done(function( data ) {
<ide>
<del>console.log('updatedtimestamp');
<add>//console.log('updatedtimestamp');
<ide>
<ide>
<ide>
<ide> var obg = [];
<ide> $.each(objs, function(i, obk) {obg.push (obk)});
<ide>
<del>console.log(obg);
<add>//console.log(obg);
<ide>
<ide> function compare(a,b) {
<ide> if (a.timestamp > b.timestamp)
<ide> $.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
<ide> .done(function( data ) {
<ide> var result = JSON.parse(data);
<del> console.log(result);
<add> //console.log(result);
<ide>
<ide>
<ide>
<ide> f_smallurls = result[0].smallurl.split(',');
<ide> f_largeurls = result[0].largeurl.split(',');
<ide>
<del> console.log(result[0].widthslides);
<del> console.log(result[0].heightslides);
<add> //console.log(result[0].widthslides);
<add> //console.log(result[0].heightslides);
<ide>
<ide> addedwidth = result[0].widthslides.split(',');
<ide> addedheight = result[0].heightslides.split(',');
<ide> f_smallurls.splice(myswiperphotos.clickedIndex, 1);
<ide> addedwidth.splice(myswiperphotos.clickedIndex, 1);
<ide> addedheight.splice(myswiperphotos.clickedIndex, 1);
<del>console.log(addedwidth);
<del>console.log(addedheight);
<add>//console.log(addedwidth);
<add>//console.log(addedheight);
<ide>
<ide> if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
<ide> }
<ide>
<ide> var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid);
<ide> theirnotifs.remove().then(function() {
<del> console.log("their notifs Remove succeeded.")
<add> //console.log("their notifs Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("their notifs failed: " + error.message)
<add> //console.log("their notifs failed: " + error.message)
<ide> });
<ide>
<ide> var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
<ide> mynotifs.remove().then(function() {
<del> console.log("my notifs Remove succeeded.")
<add> //console.log("my notifs Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("my notifs failed: " + error.message)
<add> //console.log("my notifs failed: " + error.message)
<ide> });
<ide>
<ide> var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid);
<ide> theirdates.remove().then(function() {
<del> console.log("their dates Remove succeeded.")
<add> //console.log("their dates Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("their dates failed: " + error.message)
<add> //console.log("their dates failed: " + error.message)
<ide> });
<ide>
<ide> var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid);
<ide> mydates.remove().then(function() {
<del> console.log("my dates Remove succeeded.")
<add> //console.log("my dates Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("my dates failed: " + error.message)
<add> //console.log("my dates failed: " + error.message)
<ide> });
<ide>
<ide> var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number);
<ide> ourchats.remove().then(function() {
<del> console.log("Chats Remove succeeded.")
<add> //console.log("Chats Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("Chats Remove failed: " + error.message)
<add> //console.log("Chats Remove failed: " + error.message)
<ide> });
<ide>
<ide> var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number);
<ide> ourphotochats.remove().then(function() {
<del> console.log("PhotoChats Remove succeeded.")
<add> //console.log("PhotoChats Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("PhotoChats Remove failed: " + error.message)
<add> //console.log("PhotoChats Remove failed: " + error.message)
<ide> });
<ide>
<ide> if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
<ide>
<ide> var daysleft = unixleft / 86400;
<ide>
<del>console.log('daysleft' + daysleft);
<add>//console.log('daysleft' + daysleft);
<ide>
<ide> var weekdaynamew = weekday[expiredateobject.getDay()];
<ide>
<ide> else if(daysleft === 1){chatdaystring = 'Tomorrow';}
<ide> else chatdaystring = weekdaynamew;
<ide>
<del>console.log(unixleft);
<del>console.log(daysleft);
<add>//console.log(unixleft);
<add>//console.log(daysleft);
<ide> var hoursleft = unixleft / 3600;
<ide> var salut;
<ide> if (daysleft <=0){
<ide> .done(function( data ) {
<ide>
<ide>
<del> console.log(data);
<add> //console.log(data);
<ide> var result = JSON.parse(data);
<ide>
<ide>
<ide>
<ide>
<ide> var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
<del>if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
<add>if (!prevdatetitle){prevdatetitle = messagedaytitle;
<add> //console.log('prevdatetitle does not exist');
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide> }
<ide> else {
<ide>
<del>if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
<del>else{console.log('it is a different day');prevdatetitle = messagedaytitle;
<add>if (prevdatetitle == messagedaytitle){datechatstring='';}
<add>else{prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide> if (left2load > 20) {letsload = 20;} else {letsload = left2load;}
<ide>
<ide>
<del>console.log('existingmessages' + existingmessages);
<del>console.log('letsload' + letsload);
<del>console.log('additions' + additions);
<add>//console.log('existingmessages' + existingmessages);
<add>//console.log('letsload' + letsload);
<add>//console.log('additions' + additions);
<ide>
<ide>
<ide> var first_number,second_number;
<ide>
<ide>
<ide> var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
<del>if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
<add>if (!prevdatetitle){prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today'}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
<ide> }
<ide> else {
<ide>
<del>if (prevdatetitle == messagedaytitle){console.log('it is the same day');
<add>if (prevdatetitle == messagedaytitle){
<add>
<ide> //console.log($(".message").length);
<ide>
<ide> if ((letsload < 20) && (message_count == 1) ){
<ide> }
<ide> else {datechatstring='';}
<ide> }
<del>else{console.log('it is a different day');prevdatetitle = messagedaytitle;
<add>else{prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today'}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
<ide>
<ide>
<ide>
<del> console.log(new_all[myPhotoBrowser.activeIndex]);},
<add> },
<ide> onImagesReady:function(swiper){
<ide>
<ide>
<ide>
<ide>
<del> console.log(swiper);},
<add> },
<ide> onInit:function(swiper){
<ide> //console.log(new_all[myPhotoBrowser.activeIndex]);
<ide> //
<ide>
<ide>
<ide> var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
<del>if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
<add>if (!prevdatetitle){prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide> }
<ide> else {
<ide>
<del>if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
<del>else{console.log('it is a different day');prevdatetitle = messagedaytitle;
<add>if (prevdatetitle == messagedaytitle){datechatstring='';}
<add>else{prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide>
<ide> //If existing notifications, get number of unseen messages, delete old notifications
<ide>
<del>console.log(snapshot.val());
<add>//console.log(snapshot.val());
<ide> if (snapshot.val()){
<ide>
<ide> $.each(objs, function(i, obj) {
<ide> if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
<ide>
<ide> messageq = obj.new_message_count;
<del> console.log(messageq);
<add> //console.log(messageq);
<ide> messageq ++;
<ide>
<ide>
<ide> noMessages();
<ide> setDate();
<ide>
<del> console.log('deleted');
<add> //console.log('deleted');
<ide>
<ide> }).catch(function(error) {
<ide> // Uh-oh, an error occurred!
<ide> firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() {
<ide> // File deleted successfully
<ide>
<del> console.log('deleted');
<add> //console.log('deleted');
<ide>
<ide> }).catch(function(error) {
<ide> // Uh-oh, an error occurred!
<ide> updates['notifications/' + targetid + '/' + f_uid] = targetData;
<ide>
<ide> return firebase.database().ref().update(updates).then(function() {
<del>console.log('delete notification sent');
<add>//console.log('delete notification sent');
<ide>
<ide> });
<ide> }
<ide>
<ide>
<ide> var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
<del>if (!prevdatetitle){prevdatetitle = messagedaytitle;console.log('prevdatetitle does not exist');
<add>if (!prevdatetitle){prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide> }
<ide> else {
<ide>
<del>if (prevdatetitle == messagedaytitle){console.log('it is the same day');datechatstring='';}
<del>else{console.log('it is a different day');prevdatetitle = messagedaytitle;
<add>if (prevdatetitle == messagedaytitle){datechatstring='';}
<add>else{prevdatetitle = messagedaytitle;
<ide>
<ide> if (messagedaytitle == todaystring){datechatstring = 'Today';}
<ide> else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
<ide> var eventy = document.getElementById('takePictureField_').files[0];
<ide>
<ide> // var number_of_pictures = $(".imageli").length + 1;
<del> if (eventy == 'undefined') {console.log('undefined');}
<add> if (eventy == 'undefined') {}
<ide> if (eventy !== 'undefined') {
<ide>
<ide> for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) {
<ide> firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
<ide>
<ide>
<del> console.log(obj.received);
<del> console.log(obj.from_uid);
<add> //console.log(obj.received);
<add> //console.log(obj.from_uid);
<ide> if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
<ide>
<ide> messageq = obj.new_message_count;
<ide> updates['notifications/' + targetid + '/' + f_uid] = targetData;
<ide>
<ide> return firebase.database().ref().update(updates).then(function() {
<del>console.log('delete notification sent');
<add>//console.log('delete notification sent');
<ide>
<ide> });
<ide> }
<ide>
<ide> //If existing notifications, get number of unseen messages, delete old notifications
<ide>
<del>console.log(snapshot.val());
<add>//console.log(snapshot.val());
<ide> if (snapshot.val()){
<ide>
<ide> $.each(objs, function(i, obj) {
<ide>
<ide> var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]);
<ide> mymatches.remove().then(function() {
<del> console.log("My matches Remove succeeded.")
<add> //console.log("My matches Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("My matches Remove failed: " + error.message)
<add> //console.log("My matches Remove failed: " + error.message)
<ide> });
<ide>
<ide> var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid);
<ide> theirmatches.remove().then(function() {
<del> console.log("Their matches Remove succeeded.")
<add> //console.log("Their matches Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("Their matches Remove failed: " + error.message)
<add> //console.log("Their matches Remove failed: " + error.message)
<ide> });
<ide>
<ide> var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]);
<ide> mydates.remove().then(function() {
<del> console.log("My dates Remove succeeded.")
<add> //console.log("My dates Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("My dates Remove failed: " + error.message)
<add> //console.log("My dates Remove failed: " + error.message)
<ide> });
<ide>
<ide> var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid);
<ide> theirdates.remove().then(function() {
<del> console.log("Their dates Remove succeeded.")
<add> //console.log("Their dates Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("Their dates Remove failed: " + error.message)
<add> //console.log("Their dates Remove failed: " + error.message)
<ide> });
<ide>
<ide> var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid);
<ide> theirnotifs.remove().then(function() {
<del> console.log("their notifs Remove succeeded.")
<add> //console.log("their notifs Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("their notifs failed: " + error.message)
<add> //console.log("their notifs failed: " + error.message)
<ide> });
<ide>
<ide> var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
<ide> ourchats.remove().then(function() {
<del> console.log("Chats Remove succeeded.")
<add> //console.log("Chats Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("Chats Remove failed: " + error.message)
<add> //console.log("Chats Remove failed: " + error.message)
<ide> });
<ide>
<ide> var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
<ide> ourphotochats.remove().then(function() {
<del> console.log("PhotoChats Remove succeeded.")
<add> //console.log("PhotoChats Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("PhotoChats Remove failed: " + error.message)
<add> //console.log("PhotoChats Remove failed: " + error.message)
<ide> });
<ide>
<ide> }
<ide>
<ide> firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
<ide> var objs = snapshot.val();
<del>console.log(objs);
<add>//console.log(objs);
<ide>
<ide>
<ide>
<ide>
<ide> var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid);
<ide> mynotifs.remove().then(function() {
<del> console.log("my notifs Remove succeeded.")
<add> //console.log("my notifs Remove succeeded.")
<ide> })
<ide> .catch(function(error) {
<del> console.log("my notifs failed: " + error.message)
<add> //console.log("my notifs failed: " + error.message)
<ide> });
<ide>
<ide> });
<ide> firebase.auth().currentUser.getToken().then(function(idToken) {
<ide> $.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
<ide> .done(function( data ) {
<del> console.log(data);
<add> //console.log(data);
<ide>
<ide> firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
<ide>
<ide>
<ide> }).catch(function(error) {
<ide>
<del> console.log(error);
<add> //console.log(error);
<ide> });
<ide>
<ide> });
<ide> function establishNotif(){
<ide>
<ide>
<del>if(notifcount) {alert('removing old notifs');firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
<add>if(notifcount) {firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
<ide>
<ide> notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) {
<ide>
<ide>
<ide> if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;}
<ide>
<del>console.log(response);
<add>//console.log(response);
<ide>
<ide>
<ide>
<ide>
<ide>
<ide> var alreadyselected = addedsmallarray.indexOf(response.data[i].source);
<del>console.log(response.data[i]);
<add>//console.log(response.data[i]);
<ide>
<ide> if (alreadyselected == -1) {
<ide> swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>');
<ide> addedheight.splice(indexdeletedsl, 1);
<ide> addedwidth.splice(indexdeletedsl, 1);
<ide>
<del>console.log(addedheight);
<add>//console.log(addedheight);
<ide>
<ide> }
<ide> else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show();
<ide> firebase.auth().currentUser.getToken().then(function(idToken) {
<ide> $.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
<ide> .done(function( data ) {
<del>console.log('deleted all');
<add>//console.log('deleted all');
<ide>
<ide> });
<ide> }).catch(function(error) {
<ide>
<ide>
<ide>
<del>console.log(todayday);
<add>//console.log(todayday);
<ide> s_namesonly.push(todayday);
<ide>
<ide>
<ide>
<ide> dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear());
<ide>
<del>console.log('tomorrow is' + tomorrowday);
<add>//console.log('tomorrow is' + tomorrowday);
<ide> s_namesonly.push(tomorrowday);
<ide>
<ide> s_alldays_values.push(tomorrow_timestamp);
<ide>
<ide> n = weekday[datz.getDay()];
<ide> qqq = weekday[datz.getDay() - 1];
<del>console.log(n);
<add>//console.log(n);
<ide> s_alldays_names.push(n + ' ' + daynumber + dending);
<ide>
<ide> dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear());
<ide> s_namesonly.push(n);
<ide> }
<ide> s_namesonly.push(n);
<del>console.log(s_namesonly);
<del>
<del>console.log(s_alldays_values);
<add>//console.log(s_namesonly);
<add>
<add>//console.log(s_alldays_values);
<ide>
<ide> for (i = 0; i < s_alldays_names.length; i++) {
<ide> |
|
Java | apache-2.0 | 9c1f3de16cb6c19c8821a3f3617e28837880a3ad | 0 | gbif/occurrence,gbif/occurrence,gbif/occurrence | /*
* Copyright 2012 Global Biodiversity Information Facility (GBIF)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.occurrence.download.service;
import org.gbif.api.exception.ServiceUnavailableException;
import org.gbif.api.model.occurrence.Download;
import org.gbif.api.model.occurrence.DownloadRequest;
import org.gbif.api.service.occurrence.DownloadRequestService;
import org.gbif.api.service.registry.OccurrenceDownloadService;
import org.gbif.dwc.terms.GbifTerm;
import org.gbif.dwc.terms.Term;
import org.gbif.occurrence.common.TermUtils;
import org.gbif.occurrence.common.download.DownloadUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import com.google.common.base.CharMatcher;
import com.google.common.base.Enums;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.sun.jersey.api.NotFoundException;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.Job.Status;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.client.OozieClientException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gbif.occurrence.common.download.DownloadUtils.downloadLink;
import static org.gbif.occurrence.download.service.Constants.NOTIFY_ADMIN;
@Singleton
public class DownloadRequestServiceImpl implements DownloadRequestService, CallbackService {
public static final EnumSet<Download.Status> RUNNING_STATUSES = EnumSet.of(Download.Status.PREPARING,
Download.Status.RUNNING, Download.Status.SUSPENDED);
/**
* Map to provide conversions from oozie.Job.Status to Download.Status.
*/
private static final ImmutableMap<Job.Status, Download.Status> STATUSES_MAP =
new ImmutableMap.Builder<Job.Status, Download.Status>()
.put(Job.Status.PREP, Download.Status.PREPARING)
.put(Job.Status.PREPPAUSED, Download.Status.PREPARING)
.put(Job.Status.PREMATER, Download.Status.PREPARING)
.put(Job.Status.PREPSUSPENDED, Download.Status.SUSPENDED)
.put(Job.Status.RUNNING, Download.Status.RUNNING)
.put(Job.Status.KILLED, Download.Status.KILLED)
.put(Job.Status.RUNNINGWITHERROR, Download.Status.RUNNING)
.put(Job.Status.DONEWITHERROR, Download.Status.FAILED)
.put(Job.Status.FAILED, Download.Status.FAILED)
.put(Job.Status.PAUSED, Download.Status.RUNNING)
.put(Job.Status.PAUSEDWITHERROR, Download.Status.RUNNING)
.put(Job.Status.SUCCEEDED, Download.Status.SUCCEEDED)
.put(Job.Status.SUSPENDED, Download.Status.SUSPENDED)
.put(Job.Status.SUSPENDEDWITHERROR, Download.Status.SUSPENDED).build();
private static final Logger LOG = LoggerFactory.getLogger(DownloadRequestServiceImpl.class);
private static final Joiner EMAIL_JOINER = Joiner.on(';').skipNulls();
private static final CharMatcher REPL_INVALID_HIVE_CHARS = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.DIGIT)
.or(CharMatcher.is('_'))
.negate();
private static final String HIVE_SELECT_INTERPRETED;
private static final String HIVE_SELECT_VERBATIM;
static {
List<String> columns = Lists.newArrayList();
for (Term term : TermUtils.interpretedTerms()) {
final String iCol = TermUtils.getHiveColumn(term);
if (TermUtils.isInterpretedDate(term)) {
columns.add("toISO8601(" + iCol + ") AS " + iCol);
} else if (TermUtils.isInterpretedNumerical(term) || TermUtils.isInterpretedDouble(term)) {
columns.add("cleanNull(" + iCol + ") AS " + iCol);
} else if (TermUtils.isInterpretedBoolean(term)) {
columns.add(iCol);
} else {
columns.add("cleanDelimiters(" + iCol + ") AS " + iCol);
}
}
HIVE_SELECT_INTERPRETED = Joiner.on(',').join(columns);
columns = Lists.newArrayList();
// manually add the GBIF occ key as first column
columns.add(TermUtils.getHiveColumn(GbifTerm.gbifID));
for (Term term : TermUtils.verbatimTerms()) {
if (GbifTerm.gbifID != term) {
String colName = TermUtils.getHiveColumn(term);
columns.add("cleanDelimiters(v_" + colName + ") AS v_" + colName);
}
}
HIVE_SELECT_VERBATIM = Joiner.on(',').join(columns);
}
private static final EnumSet<Status> FAILURE_STATES = EnumSet.of(Status.FAILED, Status.KILLED);
private static final Counter SUCCESSFUL_DOWNLOADS = Metrics.newCounter(CallbackService.class, "successful_downloads");
private static final Counter FAILED_DOWNLOADS = Metrics.newCounter(CallbackService.class, "failed_downloads");
private static final Counter CANCELLED_DOWNLOADS = Metrics.newCounter(CallbackService.class, "cancelled_downloads");
// ObjectMappers are thread safe if not reconfigured in code
private final ObjectMapper mapper = new ObjectMapper();
private final OozieClient client;
private final Map<String, String> defaultProperties;
private final String wsUrl;
private final File downloadMount;
private final OccurrenceDownloadService occurrenceDownloadService;
private final DownloadEmailUtils downloadEmailUtils;
@Inject
public DownloadRequestServiceImpl(OozieClient client,
@Named("oozie.default_properties") Map<String, String> defaultProperties,
@Named("ws.url") String wsUrl,
@Named("ws.mount") String wsMountDir,
OccurrenceDownloadService occurrenceDownloadService,
DownloadEmailUtils downloadEmailUtils) {
this.client = client;
this.defaultProperties = defaultProperties;
this.wsUrl = wsUrl;
this.downloadMount = new File(wsMountDir);
this.occurrenceDownloadService = occurrenceDownloadService;
this.downloadEmailUtils = downloadEmailUtils;
}
@Override
public void cancel(String downloadKey) {
try {
Download download = occurrenceDownloadService.get(downloadKey);
if (download != null) {
if (RUNNING_STATUSES.contains(download.getStatus())) {
updateDownloadStatus(download, Download.Status.CANCELLED);
client.kill(DownloadUtils.downloadToWorkflowId(downloadKey));
LOG.info("Download {} canceled", downloadKey);
}
} else {
throw new NotFoundException(String.format("Download %s not found", downloadKey));
}
} catch (OozieClientException e) {
throw new ServiceUnavailableException("Failed to cancel download " + downloadKey, e);
}
}
@Override
public String create(DownloadRequest request) {
LOG.debug("Trying to create download from request [{}]", request);
Preconditions.checkNotNull(request);
HiveQueryVisitor hiveVisitor = new HiveQueryVisitor();
SolrQueryVisitor solrVisitor = new SolrQueryVisitor();
String hiveQuery;
String solrQuery;
try {
hiveQuery = StringEscapeUtils.escapeXml(hiveVisitor.getHiveQuery(request.getPredicate()));
solrQuery = solrVisitor.getQuery(request.getPredicate());
} catch (QueryBuildingException e) {
throw new ServiceUnavailableException("Error building the hive query, attempting to continue", e);
}
LOG.debug("Attempting to download with hive query [{}]", hiveQuery);
final String uniqueId =
REPL_INVALID_HIVE_CHARS.removeFrom(request.getCreator() + '_' + UUID.randomUUID().toString());
final String tmpTable = "download_tmp_" + uniqueId;
final String citationTable = "download_tmp_citation_" + uniqueId;
Properties jobProps = new Properties();
jobProps.putAll(defaultProperties);
jobProps.setProperty("select_interpreted", HIVE_SELECT_INTERPRETED);
jobProps.setProperty("select_verbatim", HIVE_SELECT_VERBATIM);
jobProps.setProperty("query", hiveQuery);
jobProps.setProperty("solr_query", solrQuery);
jobProps.setProperty("query_result_table", tmpTable);
jobProps.setProperty("citation_table", citationTable);
// we dont have a downloadId yet, submit a placeholder
jobProps.setProperty("download_link", downloadLink(wsUrl, DownloadUtils.DOWNLOAD_ID_PLACEHOLDER));
jobProps.setProperty(Constants.USER_PROPERTY, request.getCreator());
if (request.getNotificationAddresses() != null && !request.getNotificationAddresses().isEmpty()) {
jobProps.setProperty(Constants.NOTIFICATION_PROPERTY, EMAIL_JOINER.join(request.getNotificationAddresses()));
}
// serialize the predicate filter into json
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, request.getPredicate());
writer.flush();
jobProps.setProperty(Constants.FILTER_PROPERTY, writer.toString());
} catch (IOException e) {
throw new ServiceUnavailableException("Failed to serialize download filter " + request.getPredicate(), e);
}
LOG.debug("job properties: {}", jobProps);
try {
final String jobId = client.run(jobProps);
LOG.debug("oozie job id is: [{}], with tmpTable [{}]", jobId, tmpTable);
String downloadId = DownloadUtils.workflowToDownloadId(jobId);
persistDownload(request, downloadId);
return downloadId;
} catch (OozieClientException e) {
throw new ServiceUnavailableException("Failed to create download job", e);
}
}
@Override
public InputStream getResult(String downloadKey) {
Download d = occurrenceDownloadService.get(downloadKey);
if (!d.isAvailable()) {
throw new NotFoundException("Download " + downloadKey + " is not ready yet");
}
File localFile = new File(downloadMount, downloadKey + ".zip");
try {
return new FileInputStream(localFile);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to read download " + downloadKey + " from " + localFile.getAbsolutePath(), e);
}
}
/**
* Processes a callback from Oozie which update the download status.
*/
public void processCallback(String jobId, String status) {
Preconditions.checkNotNull(Strings.isNullOrEmpty(jobId), "<jobId> may not be null or empty");
Preconditions.checkNotNull(Strings.isNullOrEmpty(status), "<status> may not be null or empty");
final Optional<Job.Status> opStatus = Enums.getIfPresent(Job.Status.class, status.toUpperCase());
Preconditions.checkArgument(opStatus.isPresent(), "<status> the requested status is not valid");
final Status jobStatus = opStatus.get();
String downloadId = DownloadUtils.workflowToDownloadId(jobId);
LOG.debug("Processing callback for jobId [{}] with status [{}]", jobId, status);
Download download = occurrenceDownloadService.get(downloadId);
// Updates the job status in the registry DB
org.gbif.api.model.occurrence.Download.Status newStatus = STATUSES_MAP.get(jobStatus);
if (download == null) {
// Download can be null if the oozie reports status before the download is persisted
LOG.error(String.format("Download [%s] not found", downloadId));
return;
}
// Do nor kill a cancelled download
if (download.getStatus() == org.gbif.api.model.occurrence.Download.Status.CANCELLED
&& org.gbif.api.model.occurrence.Download.Status.KILLED == newStatus) {
CANCELLED_DOWNLOADS.inc();
return;
} else {
updateDownloadStatus(download, newStatus);
}
// Catch failures
if (FAILURE_STATES.contains(jobStatus)) {
LOG.error(NOTIFY_ADMIN, "Got callback for unsuccessful query. JobId [{}], Status [{}]", jobId, status);
downloadEmailUtils.sendErrorNotificationMail(download);
FAILED_DOWNLOADS.inc();
return;
}
// Don't notify anyone for RUNNING jobs
if (Status.RUNNING == jobStatus) {
return;
}
// We got some invalid status
if (Status.SUCCEEDED != jobStatus) {
LOG.info("Got invalid callback status. JobId [{}], Status[{}]", jobId, status);
return;
}
SUCCESSFUL_DOWNLOADS.inc();
// notify about download
downloadEmailUtils.sendSuccessNotificationMail(download);
}
/**
* Returns the download size in bytes.
*/
private Long getDownloadSize(String downloadKey) {
File downloadFile = new File(downloadMount, downloadKey + ".zip");
if (downloadFile.exists()) {
return downloadFile.length();
}
return 0L;
}
/**
* Persists the download information.
*/
private void persistDownload(DownloadRequest request, String downloadId) {
Download download = new Download();
download.setKey(downloadId);
download.setRequest(request);
download.setStatus(Download.Status.PREPARING);
download.setDownloadLink(downloadLink(wsUrl, downloadId));
occurrenceDownloadService.create(download);
}
/**
* Updates the download status and file size.
*/
private void updateDownloadStatus(Download download, Download.Status newStatus) {
download.setStatus(newStatus);
download.setSize(getDownloadSize(download.getKey()));
occurrenceDownloadService.update(download);
}
}
| occurrence-ws/src/main/java/org/gbif/occurrence/download/service/DownloadRequestServiceImpl.java | /*
* Copyright 2012 Global Biodiversity Information Facility (GBIF)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.occurrence.download.service;
import org.gbif.api.exception.ServiceUnavailableException;
import org.gbif.api.model.occurrence.Download;
import org.gbif.api.model.occurrence.DownloadRequest;
import org.gbif.api.service.occurrence.DownloadRequestService;
import org.gbif.api.service.registry.OccurrenceDownloadService;
import org.gbif.dwc.terms.GbifTerm;
import org.gbif.dwc.terms.Term;
import org.gbif.occurrence.common.TermUtils;
import org.gbif.occurrence.common.download.DownloadUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import com.google.common.base.CharMatcher;
import com.google.common.base.Enums;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.sun.jersey.api.NotFoundException;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.Job.Status;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.client.OozieClientException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.gbif.occurrence.common.download.DownloadUtils.downloadLink;
import static org.gbif.occurrence.download.service.Constants.NOTIFY_ADMIN;
@Singleton
public class DownloadRequestServiceImpl implements DownloadRequestService, CallbackService {
public static final EnumSet<Download.Status> RUNNING_STATUSES = EnumSet.of(Download.Status.PREPARING,
Download.Status.RUNNING, Download.Status.SUSPENDED);
/**
* Map to provide conversions from oozie.Job.Status to Download.Status.
*/
private static final ImmutableMap<Job.Status, Download.Status> STATUSES_MAP =
new ImmutableMap.Builder<Job.Status, Download.Status>()
.put(Job.Status.PREP, Download.Status.PREPARING)
.put(Job.Status.PREPPAUSED, Download.Status.PREPARING)
.put(Job.Status.PREMATER, Download.Status.PREPARING)
.put(Job.Status.PREPSUSPENDED, Download.Status.SUSPENDED)
.put(Job.Status.RUNNING, Download.Status.RUNNING)
.put(Job.Status.KILLED, Download.Status.KILLED)
.put(Job.Status.RUNNINGWITHERROR, Download.Status.RUNNING)
.put(Job.Status.DONEWITHERROR, Download.Status.FAILED)
.put(Job.Status.FAILED, Download.Status.FAILED)
.put(Job.Status.PAUSED, Download.Status.RUNNING)
.put(Job.Status.PAUSEDWITHERROR, Download.Status.RUNNING)
.put(Job.Status.SUCCEEDED, Download.Status.SUCCEEDED)
.put(Job.Status.SUSPENDED, Download.Status.SUSPENDED)
.put(Job.Status.SUSPENDEDWITHERROR, Download.Status.SUSPENDED).build();
private static final Logger LOG = LoggerFactory.getLogger(DownloadRequestServiceImpl.class);
private static final Joiner EMAIL_JOINER = Joiner.on(';').skipNulls();
private static final CharMatcher REPL_INVALID_HIVE_CHARS = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.DIGIT)
.or(CharMatcher.is('_'))
.negate();
private static final String HIVE_SELECT_INTERPRETED;
private static final String HIVE_SELECT_VERBATIM;
static {
List<String> columns = Lists.newArrayList();
for (Term term : TermUtils.interpretedTerms()) {
final String iCol = TermUtils.getHiveColumn(term);
if (TermUtils.isInterpretedDate(term)) {
columns.add("toISO8601(" + iCol + ") AS " + iCol);
} else if (TermUtils.isInterpretedNumerical(term) || TermUtils.isInterpretedDouble(term)) {
columns.add("cleanNull(" + iCol + ") AS " + iCol);
} else {
columns.add("cleanDelimiters(" + iCol + ") AS " + iCol);
}
}
HIVE_SELECT_INTERPRETED = Joiner.on(',').join(columns);
columns = Lists.newArrayList();
// manually add the GBIF occ key as first column
columns.add(TermUtils.getHiveColumn(GbifTerm.gbifID));
for (Term term : TermUtils.verbatimTerms()) {
if (GbifTerm.gbifID != term) {
String colName = TermUtils.getHiveColumn(term);
columns.add("cleanDelimiters(v_" + colName + ") AS v_" + colName);
}
}
HIVE_SELECT_VERBATIM = Joiner.on(',').join(columns);
}
private static final EnumSet<Status> FAILURE_STATES = EnumSet.of(Status.FAILED, Status.KILLED);
private static final Counter SUCCESSFUL_DOWNLOADS = Metrics.newCounter(CallbackService.class, "successful_downloads");
private static final Counter FAILED_DOWNLOADS = Metrics.newCounter(CallbackService.class, "failed_downloads");
private static final Counter CANCELLED_DOWNLOADS = Metrics.newCounter(CallbackService.class, "cancelled_downloads");
// ObjectMappers are thread safe if not reconfigured in code
private final ObjectMapper mapper = new ObjectMapper();
private final OozieClient client;
private final Map<String, String> defaultProperties;
private final String wsUrl;
private final File downloadMount;
private final OccurrenceDownloadService occurrenceDownloadService;
private final DownloadEmailUtils downloadEmailUtils;
@Inject
public DownloadRequestServiceImpl(OozieClient client,
@Named("oozie.default_properties") Map<String, String> defaultProperties,
@Named("ws.url") String wsUrl,
@Named("ws.mount") String wsMountDir,
OccurrenceDownloadService occurrenceDownloadService,
DownloadEmailUtils downloadEmailUtils) {
this.client = client;
this.defaultProperties = defaultProperties;
this.wsUrl = wsUrl;
this.downloadMount = new File(wsMountDir);
this.occurrenceDownloadService = occurrenceDownloadService;
this.downloadEmailUtils = downloadEmailUtils;
}
@Override
public void cancel(String downloadKey) {
try {
Download download = occurrenceDownloadService.get(downloadKey);
if (download != null) {
if (RUNNING_STATUSES.contains(download.getStatus())) {
updateDownloadStatus(download, Download.Status.CANCELLED);
client.kill(DownloadUtils.downloadToWorkflowId(downloadKey));
LOG.info("Download {} canceled", downloadKey);
}
} else {
throw new NotFoundException(String.format("Download %s not found", downloadKey));
}
} catch (OozieClientException e) {
throw new ServiceUnavailableException("Failed to cancel download " + downloadKey, e);
}
}
@Override
public String create(DownloadRequest request) {
LOG.debug("Trying to create download from request [{}]", request);
Preconditions.checkNotNull(request);
HiveQueryVisitor hiveVisitor = new HiveQueryVisitor();
SolrQueryVisitor solrVisitor = new SolrQueryVisitor();
String hiveQuery;
String solrQuery;
try {
hiveQuery = StringEscapeUtils.escapeXml(hiveVisitor.getHiveQuery(request.getPredicate()));
solrQuery = solrVisitor.getQuery(request.getPredicate());
} catch (QueryBuildingException e) {
throw new ServiceUnavailableException("Error building the hive query, attempting to continue", e);
}
LOG.debug("Attempting to download with hive query [{}]", hiveQuery);
final String uniqueId =
REPL_INVALID_HIVE_CHARS.removeFrom(request.getCreator() + '_' + UUID.randomUUID().toString());
final String tmpTable = "download_tmp_" + uniqueId;
final String citationTable = "download_tmp_citation_" + uniqueId;
Properties jobProps = new Properties();
jobProps.putAll(defaultProperties);
jobProps.setProperty("select_interpreted", HIVE_SELECT_INTERPRETED);
jobProps.setProperty("select_verbatim", HIVE_SELECT_VERBATIM);
jobProps.setProperty("query", hiveQuery);
jobProps.setProperty("solr_query", solrQuery);
jobProps.setProperty("query_result_table", tmpTable);
jobProps.setProperty("citation_table", citationTable);
// we dont have a downloadId yet, submit a placeholder
jobProps.setProperty("download_link", downloadLink(wsUrl, DownloadUtils.DOWNLOAD_ID_PLACEHOLDER));
jobProps.setProperty(Constants.USER_PROPERTY, request.getCreator());
if (request.getNotificationAddresses() != null && !request.getNotificationAddresses().isEmpty()) {
jobProps.setProperty(Constants.NOTIFICATION_PROPERTY, EMAIL_JOINER.join(request.getNotificationAddresses()));
}
// serialize the predicate filter into json
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, request.getPredicate());
writer.flush();
jobProps.setProperty(Constants.FILTER_PROPERTY, writer.toString());
} catch (IOException e) {
throw new ServiceUnavailableException("Failed to serialize download filter " + request.getPredicate(), e);
}
LOG.debug("job properties: {}", jobProps);
try {
final String jobId = client.run(jobProps);
LOG.debug("oozie job id is: [{}], with tmpTable [{}]", jobId, tmpTable);
String downloadId = DownloadUtils.workflowToDownloadId(jobId);
persistDownload(request, downloadId);
return downloadId;
} catch (OozieClientException e) {
throw new ServiceUnavailableException("Failed to create download job", e);
}
}
@Override
public InputStream getResult(String downloadKey) {
Download d = occurrenceDownloadService.get(downloadKey);
if (!d.isAvailable()) {
throw new NotFoundException("Download " + downloadKey + " is not ready yet");
}
File localFile = new File(downloadMount, downloadKey + ".zip");
try {
return new FileInputStream(localFile);
} catch (IOException e) {
throw new IllegalStateException(
"Failed to read download " + downloadKey + " from " + localFile.getAbsolutePath(), e);
}
}
/**
* Processes a callback from Oozie which update the download status.
*/
public void processCallback(String jobId, String status) {
Preconditions.checkNotNull(Strings.isNullOrEmpty(jobId), "<jobId> may not be null or empty");
Preconditions.checkNotNull(Strings.isNullOrEmpty(status), "<status> may not be null or empty");
final Optional<Job.Status> opStatus = Enums.getIfPresent(Job.Status.class, status.toUpperCase());
Preconditions.checkArgument(opStatus.isPresent(), "<status> the requested status is not valid");
final Status jobStatus = opStatus.get();
String downloadId = DownloadUtils.workflowToDownloadId(jobId);
LOG.debug("Processing callback for jobId [{}] with status [{}]", jobId, status);
Download download = occurrenceDownloadService.get(downloadId);
// Updates the job status in the registry DB
org.gbif.api.model.occurrence.Download.Status newStatus = STATUSES_MAP.get(jobStatus);
if (download == null) {
// Download can be null if the oozie reports status before the download is persisted
LOG.error(String.format("Download [%s] not found", downloadId));
return;
}
// Do nor kill a cancelled download
if (download.getStatus() == org.gbif.api.model.occurrence.Download.Status.CANCELLED
&& org.gbif.api.model.occurrence.Download.Status.KILLED == newStatus) {
CANCELLED_DOWNLOADS.inc();
return;
} else {
updateDownloadStatus(download, newStatus);
}
// Catch failures
if (FAILURE_STATES.contains(jobStatus)) {
LOG.error(NOTIFY_ADMIN, "Got callback for unsuccessful query. JobId [{}], Status [{}]", jobId, status);
downloadEmailUtils.sendErrorNotificationMail(download);
FAILED_DOWNLOADS.inc();
return;
}
// Don't notify anyone for RUNNING jobs
if (Status.RUNNING == jobStatus) {
return;
}
// We got some invalid status
if (Status.SUCCEEDED != jobStatus) {
LOG.info("Got invalid callback status. JobId [{}], Status[{}]", jobId, status);
return;
}
SUCCESSFUL_DOWNLOADS.inc();
// notify about download
downloadEmailUtils.sendSuccessNotificationMail(download);
}
/**
* Returns the download size in bytes.
*/
private Long getDownloadSize(String downloadKey) {
File downloadFile = new File(downloadMount, downloadKey + ".zip");
if (downloadFile.exists()) {
return downloadFile.length();
}
return 0L;
}
/**
* Persists the download information.
*/
private void persistDownload(DownloadRequest request, String downloadId) {
Download download = new Download();
download.setKey(downloadId);
download.setRequest(request);
download.setStatus(Download.Status.PREPARING);
download.setDownloadLink(downloadLink(wsUrl, downloadId));
occurrenceDownloadService.create(download);
}
/**
* Updates the download status and file size.
*/
private void updateDownloadStatus(Download download, Download.Status newStatus) {
download.setStatus(newStatus);
download.setSize(getDownloadSize(download.getKey()));
occurrenceDownloadService.update(download);
}
}
| Boolean columns are excluded from null checking
| occurrence-ws/src/main/java/org/gbif/occurrence/download/service/DownloadRequestServiceImpl.java | Boolean columns are excluded from null checking | <ide><path>ccurrence-ws/src/main/java/org/gbif/occurrence/download/service/DownloadRequestServiceImpl.java
<ide> columns.add("toISO8601(" + iCol + ") AS " + iCol);
<ide> } else if (TermUtils.isInterpretedNumerical(term) || TermUtils.isInterpretedDouble(term)) {
<ide> columns.add("cleanNull(" + iCol + ") AS " + iCol);
<add> } else if (TermUtils.isInterpretedBoolean(term)) {
<add> columns.add(iCol);
<ide> } else {
<ide> columns.add("cleanDelimiters(" + iCol + ") AS " + iCol);
<ide> } |
|
Java | epl-1.0 | a0bf486572582e106d62cb427e90a13e4ba0878e | 0 | jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012-2014 Chuck Ritola
* Part of the jTRFP.org project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.beh;
import java.awt.Point;
import java.lang.ref.WeakReference;
import java.util.Collection;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.NormalMap;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.flow.Mission;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.TerrainChunk;
import org.jtrfp.trcl.obj.TunnelEntranceObject;
import org.jtrfp.trcl.obj.WorldObject;
public class CollidesWithTerrain extends Behavior {
private double[] surfaceNormalVar;
public static final double CEILING_Y_NUDGE = -5000;
private int tickCounter = 0;
private boolean autoNudge = false;
private double nudgePadding = 5000;
private boolean recentlyCollided = false;
private boolean tunnelEntryCapable = false;
private boolean ignoreHeadingForImpact = true;
private boolean ignoreCeiling = false;
private static TerrainChunk dummyTerrainChunk;
// WORK VARS
private final double[] groundNormal = new double[3];
private final double[] ceilingNormal = new double[3];
private WeakReference<OverworldSystem>lastOWS;
private NormalMap normalMap;
@Override
public void _tick(long tickTimeMillis) {
if (tickCounter++ % 2 == 0 && !recentlyCollided)
return;
recentlyCollided=false;
final WorldObject p = getParent();
final TR tr = p.getTr();
final World world = tr.getWorld();
final Mission mission = tr.getGame().getCurrentMission();
OverworldSystem ows = lastOWS!=null?lastOWS.get():null;
if(mission.getOverworldSystem()!=ows){
normalMap=null;
lastOWS=new WeakReference<OverworldSystem>(mission.getOverworldSystem());
}
try{if(normalMap==null)
//normalMap=new NormalMap(new WallOffAltitudeMap(mission.getOverworldSystem().getAltitudeMap(),tr.getWorld().sizeY/2.1,tr.getWorld().sizeY*2));
normalMap=new NormalMap(mission.getOverworldSystem().getAltitudeMap());
}catch(NullPointerException e){return;}
ows = mission.getOverworldSystem();
if(ows==null)
return;
if(ows.isTunnelMode())
return;//No terrain to collide with while in tunnel mode.
if(normalMap==null)return;
final double[] thisPos = p.getPosition();
final double groundHeight= normalMap.heightAt(thisPos[0],thisPos[2]);
final double ceilingHeight = (tr.getWorld().sizeY - groundHeight)
+ CEILING_Y_NUDGE;
normalMap.normalAt(thisPos[0], thisPos[2], groundNormal);
final OverworldSystem overworldSystem = tr.getGame().getCurrentMission().getOverworldSystem();
if(overworldSystem==null)return;
final boolean terrainMirror = overworldSystem.isChamberMode();
final double thisY = thisPos[1];
boolean groundImpact = thisY < (groundHeight + (autoNudge ? nudgePadding
: 0));
final boolean ceilingImpact = (thisY > ceilingHeight && terrainMirror && !ignoreCeiling);
ceilingNormal[0] = groundNormal[0];
ceilingNormal[1] = -groundNormal[1];
ceilingNormal[2] = groundNormal[2];
double [] surfaceNormal = groundImpact ? groundNormal : ceilingNormal;
final double dot = Vect3D.dot3(surfaceNormal,getParent().getHeading().toArray());
//final double dot = surfaceNormal.dotProduct(getParent().getHeading());
/*
if (terrainMirror && groundHeight/(tr.getWorld().sizeY/2) > .97) {
groundImpact = true;
surfaceNormal = downhillDirectionXZ;
}//end if(smushed between floor and ceiling)
*/
if (tunnelEntryCapable && groundImpact && dot < 0){
final OverworldSystem os = mission.getOverworldSystem();
if(!os.isTunnelMode() ){
TunnelEntranceObject teo = mission.getTunnelEntranceObject(new Point(
(int)(thisPos[0] / TR.mapSquareSize),
(int)(thisPos[2] / TR.mapSquareSize)));
if(teo!=null && !mission.isBossFight())
{mission.enterTunnel(teo.getSourceTunnel());return;}
}//end if(above ground)
}//end if(tunnelEntryCapable())
if (groundImpact || ceilingImpact && dot < 0) {// detect collision
if(getParent() instanceof Player)
System.err.println(new Vector3D(surfaceNormal));
recentlyCollided=true;
double padding = autoNudge ? nudgePadding : 0;
padding *= groundImpact ? 1 : -1;
thisPos[1] = (groundImpact ? groundHeight + padding: ceilingHeight - padding);
p.notifyPositionChange();
/* if(dot < 0 || ignoreHeadingForImpact)*/{//If toward ground, call impact listeners.
surfaceNormalVar = surfaceNormal;
final Behavior behavior = p.getBehavior();
behavior.probeForBehaviors(sub, SurfaceImpactListener.class);
}//end if(pointedTowardGround)
}// end if(collision)
}// end _tick
private final Submitter<SurfaceImpactListener> sub = new Submitter<SurfaceImpactListener>() {
@Override
public void submit(SurfaceImpactListener item) {
item.collidedWithSurface(getDummyTerrainChunk(getParent().getTr()), surfaceNormalVar);
}
@Override
public void submit(Collection<SurfaceImpactListener> items) {
for (SurfaceImpactListener l : items) {
submit(l);
}//end for(items)
}//end submit(...)
};
/**
* @return the autoNudge
*/
public boolean isAutoNudge() {
return autoNudge;
}
/**
* @param autoNudge
* the autoNudge to set
*/
public CollidesWithTerrain setAutoNudge(boolean autoNudge) {
this.autoNudge = autoNudge;
return this;
}
/**
* @return the nudgePadding
*/
public double getNudgePadding() {
return nudgePadding;
}
/**
* @param nudgePadding
* the nudgePadding to set
*/
public CollidesWithTerrain setNudgePadding(double nudgePadding) {
this.nudgePadding = nudgePadding;
return this;
}
/**
* @return the tunnelEntryCapable
*/
public boolean isTunnelEntryCapable() {
return tunnelEntryCapable;
}
/**
* @param tunnelEntryCapable the tunnelEntryCapable to set
*/
public CollidesWithTerrain setTunnelEntryCapable(boolean tunnelEntryCapable) {
this.tunnelEntryCapable = tunnelEntryCapable;
return this;
}
/**
* @param ignoreHeadingForImpact the ignoreHeadingForImpact to set
*/
public CollidesWithTerrain setIgnoreHeadingForImpact(boolean ignoreHeadingForImpact) {
this.ignoreHeadingForImpact = ignoreHeadingForImpact;
return this;
}
public CollidesWithTerrain setIgnoreCeiling(boolean ignoreCeiling) {
this.ignoreCeiling=ignoreCeiling;
return this;
}
/**
* @return the ignoreCeiling
*/
public boolean isIgnoreCeiling() {
return ignoreCeiling;
}
private static TerrainChunk getDummyTerrainChunk(TR tr){
if (dummyTerrainChunk==null)
dummyTerrainChunk = new TerrainChunk(tr);
return dummyTerrainChunk;
}
}// end BouncesOffTerrain
| src/main/java/org/jtrfp/trcl/beh/CollidesWithTerrain.java | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012-2014 Chuck Ritola
* Part of the jTRFP.org project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.beh;
import java.awt.Point;
import java.lang.ref.WeakReference;
import java.util.Collection;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.NormalMap;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.WallOffAltitudeMap;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.flow.Mission;
import org.jtrfp.trcl.math.Vect3D;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.TerrainChunk;
import org.jtrfp.trcl.obj.TunnelEntranceObject;
import org.jtrfp.trcl.obj.WorldObject;
public class CollidesWithTerrain extends Behavior {
private double[] surfaceNormalVar;
public static final double CEILING_Y_NUDGE = -5000;
private int tickCounter = 0;
private boolean autoNudge = false;
private double nudgePadding = 5000;
private boolean recentlyCollided = false;
private boolean tunnelEntryCapable = false;
private boolean ignoreHeadingForImpact = true;
private boolean ignoreCeiling = false;
private static TerrainChunk dummyTerrainChunk;
// WORK VARS
private final double[] groundNormal = new double[3];
private final double[] ceilingNormal = new double[3];
private WeakReference<OverworldSystem>lastOWS;
private NormalMap normalMap;
@Override
public void _tick(long tickTimeMillis) {
if (tickCounter++ % 2 == 0 && !recentlyCollided)
return;
recentlyCollided=false;
final WorldObject p = getParent();
final TR tr = p.getTr();
final World world = tr.getWorld();
final Mission mission = tr.getGame().getCurrentMission();
OverworldSystem ows = lastOWS!=null?lastOWS.get():null;
if(mission.getOverworldSystem()!=ows){
normalMap=null;
lastOWS=new WeakReference<OverworldSystem>(mission.getOverworldSystem());
}
try{if(normalMap==null)
//normalMap=new NormalMap(new WallOffAltitudeMap(mission.getOverworldSystem().getAltitudeMap(),tr.getWorld().sizeY/2.1,tr.getWorld().sizeY*2));
normalMap=new NormalMap(mission.getOverworldSystem().getAltitudeMap());
}catch(NullPointerException e){return;}
ows = mission.getOverworldSystem();
if(ows==null)
return;
if(ows.isTunnelMode())
return;//No terrain to collide with while in tunnel mode.
if(normalMap==null)return;
final double[] thisPos = p.getPosition();
final double groundHeight= normalMap.heightAt(thisPos[0],thisPos[2]);
final double ceilingHeight = (tr.getWorld().sizeY - groundHeight)
+ CEILING_Y_NUDGE;
normalMap.normalAt(thisPos[0], thisPos[2], groundNormal);
final OverworldSystem overworldSystem = tr.getGame().getCurrentMission().getOverworldSystem();
if(overworldSystem==null)return;
final boolean terrainMirror = overworldSystem.isChamberMode();
final double thisY = thisPos[1];
boolean groundImpact = thisY < (groundHeight + (autoNudge ? nudgePadding
: 0));
final boolean ceilingImpact = (thisY > ceilingHeight && terrainMirror && !ignoreCeiling);
ceilingNormal[0] = groundNormal[0];
ceilingNormal[1] = -groundNormal[1];
ceilingNormal[2] = groundNormal[2];
double [] surfaceNormal = groundImpact ? groundNormal : ceilingNormal;
final double dot = Vect3D.dot3(surfaceNormal,getParent().getHeading().toArray());
//final double dot = surfaceNormal.dotProduct(getParent().getHeading());
/*
if (terrainMirror && groundHeight/(tr.getWorld().sizeY/2) > .97) {
groundImpact = true;
surfaceNormal = downhillDirectionXZ;
}//end if(smushed between floor and ceiling)
*/
if (tunnelEntryCapable && groundImpact && dot < 0){
final OverworldSystem os = mission.getOverworldSystem();
if(!os.isTunnelMode() ){
TunnelEntranceObject teo = mission.getTunnelEntranceObject(new Point(
(int)(thisPos[0] / TR.mapSquareSize),
(int)(thisPos[2] / TR.mapSquareSize)));
if(teo!=null && !mission.isBossFight())
{mission.enterTunnel(teo.getSourceTunnel());return;}
}//end if(above ground)
}//end if(tunnelEntryCapable())
if (groundImpact || ceilingImpact && dot < 0) {// detect collision
if(getParent() instanceof Player)
System.err.println(new Vector3D(surfaceNormal));
recentlyCollided=true;
double padding = autoNudge ? nudgePadding : 0;
padding *= groundImpact ? 1 : -1;
thisPos[1] = (groundImpact ? groundHeight + padding: ceilingHeight - padding);
p.notifyPositionChange();
/* if(dot < 0 || ignoreHeadingForImpact)*/{//If toward ground, call impact listeners.
surfaceNormalVar = surfaceNormal;
final Behavior behavior = p.getBehavior();
behavior.probeForBehaviors(sub, SurfaceImpactListener.class);
}//end if(pointedTowardGround)
}// end if(collision)
}// end _tick
private final Submitter<SurfaceImpactListener> sub = new Submitter<SurfaceImpactListener>() {
@Override
public void submit(SurfaceImpactListener item) {
item.collidedWithSurface(getDummyTerrainChunk(getParent().getTr()), surfaceNormalVar);
}
@Override
public void submit(Collection<SurfaceImpactListener> items) {
for (SurfaceImpactListener l : items) {
submit(l);
}//end for(items)
}//end submit(...)
};
/**
* @return the autoNudge
*/
public boolean isAutoNudge() {
return autoNudge;
}
/**
* @param autoNudge
* the autoNudge to set
*/
public CollidesWithTerrain setAutoNudge(boolean autoNudge) {
this.autoNudge = autoNudge;
return this;
}
/**
* @return the nudgePadding
*/
public double getNudgePadding() {
return nudgePadding;
}
/**
* @param nudgePadding
* the nudgePadding to set
*/
public CollidesWithTerrain setNudgePadding(double nudgePadding) {
this.nudgePadding = nudgePadding;
return this;
}
/**
* @return the tunnelEntryCapable
*/
public boolean isTunnelEntryCapable() {
return tunnelEntryCapable;
}
/**
* @param tunnelEntryCapable the tunnelEntryCapable to set
*/
public CollidesWithTerrain setTunnelEntryCapable(boolean tunnelEntryCapable) {
this.tunnelEntryCapable = tunnelEntryCapable;
return this;
}
/**
* @param ignoreHeadingForImpact the ignoreHeadingForImpact to set
*/
public CollidesWithTerrain setIgnoreHeadingForImpact(boolean ignoreHeadingForImpact) {
this.ignoreHeadingForImpact = ignoreHeadingForImpact;
return this;
}
public CollidesWithTerrain setIgnoreCeiling(boolean ignoreCeiling) {
this.ignoreCeiling=ignoreCeiling;
return this;
}
/**
* @return the ignoreCeiling
*/
public boolean isIgnoreCeiling() {
return ignoreCeiling;
}
private static TerrainChunk getDummyTerrainChunk(TR tr){
if (dummyTerrainChunk==null)
dummyTerrainChunk = new TerrainChunk(tr);
return dummyTerrainChunk;
}
}// end BouncesOffTerrain
| Append to previous commit. | src/main/java/org/jtrfp/trcl/beh/CollidesWithTerrain.java | Append to previous commit. | <ide><path>rc/main/java/org/jtrfp/trcl/beh/CollidesWithTerrain.java
<ide> import org.jtrfp.trcl.NormalMap;
<ide> import org.jtrfp.trcl.OverworldSystem;
<ide> import org.jtrfp.trcl.Submitter;
<del>import org.jtrfp.trcl.WallOffAltitudeMap;
<ide> import org.jtrfp.trcl.World;
<ide> import org.jtrfp.trcl.core.TR;
<ide> import org.jtrfp.trcl.flow.Mission; |
|
Java | apache-2.0 | c8154fc9a383b53a4c2f31fd7ae8bf0b6d963862 | 0 | udayg/sakai,wfuedu/sakai,Fudan-University/sakai,lorenamgUMU/sakai,pushyamig/sakai,zqian/sakai,Fudan-University/sakai,lorenamgUMU/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,liubo404/sakai,kingmook/sakai,frasese/sakai,bkirschn/sakai,surya-janani/sakai,bkirschn/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,conder/sakai,zqian/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,conder/sakai,pushyamig/sakai,kwedoff1/sakai,colczr/sakai,hackbuteer59/sakai,joserabal/sakai,noondaysun/sakai,willkara/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,ouit0408/sakai,frasese/sakai,surya-janani/sakai,colczr/sakai,buckett/sakai-gitflow,noondaysun/sakai,udayg/sakai,bkirschn/sakai,clhedrick/sakai,liubo404/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,colczr/sakai,udayg/sakai,ktakacs/sakai,OpenCollabZA/sakai,whumph/sakai,ouit0408/sakai,whumph/sakai,hackbuteer59/sakai,udayg/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,bkirschn/sakai,buckett/sakai-gitflow,Fudan-University/sakai,puramshetty/sakai,noondaysun/sakai,joserabal/sakai,colczr/sakai,joserabal/sakai,whumph/sakai,clhedrick/sakai,udayg/sakai,kingmook/sakai,willkara/sakai,kwedoff1/sakai,rodriguezdevera/sakai,frasese/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,noondaysun/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,zqian/sakai,surya-janani/sakai,introp-software/sakai,whumph/sakai,bzhouduke123/sakai,kwedoff1/sakai,Fudan-University/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,surya-janani/sakai,introp-software/sakai,whumph/sakai,colczr/sakai,ouit0408/sakai,Fudan-University/sakai,rodriguezdevera/sakai,puramshetty/sakai,kingmook/sakai,bzhouduke123/sakai,udayg/sakai,frasese/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,ktakacs/sakai,puramshetty/sakai,frasese/sakai,kwedoff1/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,kingmook/sakai,kwedoff1/sakai,whumph/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,conder/sakai,conder/sakai,bkirschn/sakai,kingmook/sakai,whumph/sakai,willkara/sakai,pushyamig/sakai,zqian/sakai,rodriguezdevera/sakai,willkara/sakai,wfuedu/sakai,buckett/sakai-gitflow,kwedoff1/sakai,frasese/sakai,frasese/sakai,clhedrick/sakai,willkara/sakai,ouit0408/sakai,liubo404/sakai,clhedrick/sakai,colczr/sakai,willkara/sakai,surya-janani/sakai,introp-software/sakai,lorenamgUMU/sakai,pushyamig/sakai,bzhouduke123/sakai,noondaysun/sakai,puramshetty/sakai,zqian/sakai,rodriguezdevera/sakai,puramshetty/sakai,ouit0408/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,wfuedu/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,ktakacs/sakai,liubo404/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,colczr/sakai,joserabal/sakai,introp-software/sakai,Fudan-University/sakai,surya-janani/sakai,introp-software/sakai,bkirschn/sakai,Fudan-University/sakai,Fudan-University/sakai,kingmook/sakai,wfuedu/sakai,liubo404/sakai,ktakacs/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,zqian/sakai,hackbuteer59/sakai,whumph/sakai,liubo404/sakai,lorenamgUMU/sakai,liubo404/sakai,ktakacs/sakai,noondaysun/sakai,clhedrick/sakai,surya-janani/sakai,bkirschn/sakai,puramshetty/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,hackbuteer59/sakai,kwedoff1/sakai,introp-software/sakai,bzhouduke123/sakai,conder/sakai,liubo404/sakai,wfuedu/sakai,introp-software/sakai,noondaysun/sakai,introp-software/sakai,wfuedu/sakai,kingmook/sakai,conder/sakai,udayg/sakai,joserabal/sakai,bzhouduke123/sakai,kingmook/sakai,conder/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,surya-janani/sakai,willkara/sakai,bzhouduke123/sakai,joserabal/sakai,lorenamgUMU/sakai,joserabal/sakai,clhedrick/sakai,buckett/sakai-gitflow,ouit0408/sakai,ktakacs/sakai,udayg/sakai,bkirschn/sakai,conder/sakai,buckett/sakai-gitflow,zqian/sakai,frasese/sakai,colczr/sakai,clhedrick/sakai,pushyamig/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,zqian/sakai,ktakacs/sakai,puramshetty/sakai | /**********************************************************************************
* $URL: $
* $Id: $
***********************************************************************************
*
* Author: Eric Jeney, [email protected]
* The original author was Joshua Ryan [email protected]. However little of that code is actually left
*
* Copyright (c) 2010 Rutgers, the State University of New Jersey
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.lessonbuildertool.tool.beans;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.AbstractList;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.lessonbuildertool.service.LessonEntity;
import org.sakaiproject.lessonbuildertool.service.LessonSubmission;
import org.sakaiproject.lessonbuildertool.service.GradebookIfc;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.lessonbuildertool.SimplePage;
import org.sakaiproject.lessonbuildertool.SimplePageGroup;
import org.sakaiproject.lessonbuildertool.SimplePageItem;
import org.sakaiproject.lessonbuildertool.SimplePageLogEntry;
import org.sakaiproject.lessonbuildertool.tool.view.FilePickerViewParameters;
import org.sakaiproject.lessonbuildertool.model.SimplePageToolDao;
import org.sakaiproject.lessonbuildertool.service.GroupPermissionsService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAssessmentData;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.Validator;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.springframework.web.multipart.MultipartFile;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIInternalLink;
import org.sakaiproject.lessonbuildertool.tool.view.GeneralViewParameters;
import org.sakaiproject.lessonbuildertool.tool.producers.ShowPageProducer;
import org.sakaiproject.lessonbuildertool.tool.producers.ShowItemProducer;
import org.sakaiproject.lessonbuildertool.cc.CartridgeLoader;
import org.sakaiproject.lessonbuildertool.cc.ZipLoader;
import org.sakaiproject.lessonbuildertool.cc.Parser;
import org.sakaiproject.lessonbuildertool.cc.PrintHandler;
/**
* Backing bean for Simple pages
*
* @author Eric Jeney <[email protected]>
* @author Joshua Ryan [email protected] alt^I
*/
// This bean has two related but somewhat separate uses:
// 1) It keeps common data for the producers and other code. In that use the lifetime of the bean is while
// generating a single page. The bean has common application logic. The producers are pretty much just UI.
// The DAO is low-level data access. This is everything else. The producers call this bean, and not the
// DAO directly. This layer sticks caches on top of the data access, and provides more complex logic. Security
// is primarily in the DAO, but the DAO only checks permissions. We have to make sure we only acccess pages
// and items in our site
// 2) It is used by RSF to access data. Normally the bean is associated with a specific page. However the
// UI often has to update attributes of a specific item. For that use, there are some item-specific variables
// in the bean. They are only meaningful during item operations, when itemId will show which item is involved.
// While the bean is used by all the producers, the caching was designed specifically for ShowPageProducer.
// That's because it is used a lot more often than the others. ShowPageProducer should do all data acess through
// the methods here that cache. There is also caching by hibernate. However this code is cheaper, partly because
// it doesn't have to do synchronization (since it applies just to processing one transaction).
public class SimplePageBean {
private static Log log = LogFactory.getLog(SimplePageBean.class);
public enum Status {
NOT_REQUIRED, REQUIRED, DISABLED, COMPLETED, FAILED
}
public static final Pattern YOUTUBE_PATTERN = Pattern.compile("v[=/_][\\w-]{11}");
public static final String GRADES[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "F" };
public static final String FILTERHTML = "lessonbuilder.filterhtml";
public static final String LESSONBUILDER_ITEMID = "lessonbuilder.itemid";
public static final String LESSONBUILDER_PATH = "lessonbuilder.path";
public static final String LESSONBUILDER_BACKPATH = "lessonbuilder.backpath";
public static final String LESSONBUILDER_ID = "sakai.lessonbuildertool";
private static String PAGE = "simplepage.page";
private static String SITE_UPD = "site.upd";
private String contents = null;
private String pageTitle = null;
private String newPageTitle = null;
private String subpageTitle = null;
private boolean subpageNext = false;
private boolean subpageButton = false;
private List<Long> currentPath = null;
private Set<Long>allowedPages = null;
private Site currentSite = null; // cache, can be null; used by getCurrentSite
private boolean filterHtml = ServerConfigurationService.getBoolean(FILTERHTML, false);
public String selectedAssignment = null;
// generic entity stuff. selectedEntity is the string
// coming from the picker. We'll use the same variable for any entity type
public String selectedEntity = null;
public String[] selectedEntities = new String[] {};
public String selectedQuiz = null;
private SimplePage currentPage;
private Long currentPageId = null;
private Long currentPageItemId = null;
private String currentUserId = null;
private long previousPageId = -1;
// Item-specific variables. These are set by setters which are called
// by the various edit dialogs. So they're basically inputs to the
// methods used to make changes to items. The way it works is that
// when the user submits the form, RSF takes all the form variables,
// calls setters for each field, and then calls the method specified
// by the form. The setters set these variables
public Long itemId = null;
public boolean isMultimedia = false;
private String linkUrl;
private String height, width;
private String description;
private String name;
private boolean required;
private boolean subrequirement;
private boolean prerequisite;
private boolean newWindow;
private String dropDown;
private String points;
private String mimetype;
private String numberOfPages;
private boolean copyPage;
private String alt = null;
private String order = null;
private String youtubeURL;
private String mmUrl;
private long youtubeId;
private boolean hidePage;
private Date releaseDate;
private boolean hasReleaseDate;
private String redirectSendingPage = null;
private String redirectViewId = null;
private String quiztool = null;
private String topictool = null;
public Map<String, MultipartFile> multipartMap;
// Caches
// The following caches are used only during a single display of the page. I believe they
// are so transient that we don't have to worry about synchronizing them or keeping them up to date.
// Because the producer code tends to deal with items and even item ID's, it doesn't keep objects such
// as Assignment or PublishedAssessment around. It calls functions here to worry about those. If we
// don't cache, we'll be doing database lookups a lot. The worst is the code to see whether an item
// is available. Because it checks all items above, we'd end up order N**2 in the number of items on the
// page in database queries. It doesn't appear that assignments and assessments do any caching of their
// own, but hibernate as we use it does.
// Normal code shouldn't use the caches directly, but should call something like getAssignment here,
// which checks the cache and if necessary calls the real getAssignment. I've chosen to do caching on
// this level, and let the DAO be actual database access. I've really only optimized what is used by
// ShowPageProducer, as that is used every time a page is shown. Things used when you add or change
// an item aren't as critical.
// If anyone is doing serious work on the code, I recommend creating an Item class that encapsulates
// all the stuff associated with items. Then the producer would manipulate items. Thus the things in
// these caches would be held in the Items.
private Map<Long, SimplePageItem> itemCache = new HashMap<Long, SimplePageItem> ();
private Map<Long, List<SimplePageItem>> itemsCache = new HashMap<Long, List<SimplePageItem>> ();
private Map<Long, SimplePageLogEntry> logCache = new HashMap<Long, SimplePageLogEntry>();
private Map<Long, Boolean> completeCache = new HashMap<Long, Boolean>();
public static class PathEntry {
public Long pageId;
public Long pageItemId;
public String title;
}
public static class UrlItem {
public String Url;
public String label;
public UrlItem(String Url, String label) {
this.Url = Url;
this.label = label;
}
}
// Image types
private static ArrayList<String> imageTypes;
static {
imageTypes = new ArrayList<String>();
imageTypes.add("bmp");
imageTypes.add("gif");
imageTypes.add("icns");
imageTypes.add("ico");
imageTypes.add("jpg");
imageTypes.add("jpeg");
imageTypes.add("png");
imageTypes.add("tiff");
imageTypes.add("tif");
}
// Spring Injection
private SessionManager sessionManager;
public void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
private ContentHostingService contentHostingService;
public void setContentHostingService(ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
private GradebookIfc gradebookIfc = null;
public void setGradebookIfc(GradebookIfc g) {
gradebookIfc = g;
}
private LessonEntity forumEntity = null;
public void setForumEntity(Object e) {
forumEntity = (LessonEntity)e;
}
private LessonEntity quizEntity = null;
public void setQuizEntity(Object e) {
quizEntity = (LessonEntity)e;
}
private LessonEntity assignmentEntity = null;
public void setAssignmentEntity(Object e) {
assignmentEntity = (LessonEntity)e;
}
private ToolManager toolManager;
private SecurityService securityService;
private SiteService siteService;
private SimplePageToolDao simplePageToolDao;
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator x) {
messageLocator = x;
}
public MessageLocator getMessageLocator() {
return messageLocator;
}
// End Injection
public SimplePageItem findItem(long itId) {
Long itemId = itId;
SimplePageItem ret = itemCache.get(itemId);
if (ret != null)
return ret;
ret = simplePageToolDao.findItem(itemId);
if (ret != null)
itemCache.put(itemId, ret);
return ret;
}
public String errMessage() {
ToolSession toolSession = sessionManager.getCurrentToolSession();
String error = (String)toolSession.getAttribute("lessonbuilder.error");
if (error != null)
toolSession.removeAttribute("lessonbuilder.error");
return error;
}
public void setErrMessage(String s) {
ToolSession toolSession = sessionManager.getCurrentToolSession();
toolSession.setAttribute("lessonbuilder.error", s);
}
public void setErrKey(String key, String text ) {
ToolSession toolSession = sessionManager.getCurrentToolSession();
toolSession.setAttribute("lessonbuilder.error", messageLocator.getMessage(key).replace("{}", text));
}
// a lot of these are setters and getters used for the form process, as
// described above
public void setAlt(String alt) {
this.alt = alt;
}
public String getDescription() {
if (itemId != null && itemId != -1) {
return findItem(itemId).getDescription();
} else {
return null;
}
}
public void setDescription(String description) {
this.description = description;
}
public void setHidePage(boolean hide) {
hidePage = hide;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setHasReleaseDate(boolean hasReleaseDate) {
this.hasReleaseDate = hasReleaseDate;
}
// gets called for non-checked boxes also, but q will be null
public void setQuiztool(String q) {
if (q != null)
quiztool = q;
}
public void setTopictool(String q) {
if (q != null)
topictool = q;
}
public String getName() {
if (itemId != null && itemId != -1) {
return findItem(itemId).getName();
} else {
return null;
}
}
public void setName(String name) {
this.name = name;
}
public void setRequired(boolean required) {
this.required = required;
}
public void setSubrequirement(boolean subrequirement) {
this.subrequirement = subrequirement;
}
public void setPrerequisite(boolean prerequisite) {
this.prerequisite = prerequisite;
}
public void setNewWindow(boolean newWindow) {
this.newWindow = newWindow;
}
public void setDropDown(String dropDown) {
this.dropDown = dropDown;
}
public void setPoints(String points) {
this.points = points;
}
public void setMimetype(String mimetype) {
if (mimetype != null)
mimetype = mimetype.toLowerCase().trim();
this.mimetype = mimetype;
}
public String getPageTitle() {
return getCurrentPage().getTitle();
}
public void setPageTitle(String title) {
pageTitle = title;
}
public void setNewPageTitle(String title) {
newPageTitle = title;
}
public void setNumberOfPages(String n) {
numberOfPages = n;
}
public void setCopyPage(boolean c) {
this.copyPage = c;
}
public String getContents() {
return (itemId != null && itemId != -1 ? findItem(itemId).getHtml() : "");
}
public void setContents(String contents) {
this.contents = contents;
}
public void setItemId(Long id) {
itemId = id;
}
public Long getItemId() {
return itemId;
}
public void setMultimedia(boolean isMm) {
isMultimedia = isMm;
}
// hibernate interposes something between us and saveItem, and that proxy gets an
// error after saveItem does. Thus we never see any value that saveItem might
// return. Hence we pass saveItem a list to which it adds the error message. If
// there is a mesasge from saveItem take precedence over the message we detect here,
// since it's the root cause.
public boolean saveItem(Object i) {
String err = null;
List<String>elist = new ArrayList<String>();
try {
simplePageToolDao.saveItem(i, elist, messageLocator.getMessage("simplepage.nowrite"));
} catch (Throwable t) {
// this is probably a bogus error, but find its root cause
while (t.getCause() != null) {
t = t.getCause();
}
err = t.toString();
}
// if we got an error from saveItem use it instead
if (elist.size() > 0)
err = elist.get(0);
if (err != null) {
setErrMessage(messageLocator.getMessage("simplepage.savefailed") + err);
return false;
}
return true;
}
// see notes for saveupdate
boolean update(Object i) {
String err = null;
List<String>elist = new ArrayList<String>();
try {
simplePageToolDao.update(i, elist, messageLocator.getMessage("simplepage.nowrite"));
} catch (Throwable t) {
// this is probably a bogus error, but find its root cause
while (t.getCause() != null) {
t = t.getCause();
}
err = t.toString();
}
// if we got an error from saveItem use it instead
if (elist.size() > 0)
err = elist.get(0);
if (err != null) {
setErrMessage(messageLocator.getMessage("simplepage.savefailed") + err);
return false;
}
return true;
}
// The permissions model assumes that all code operates on the current
// page. When the current page is set, the set code verifies that the
// page is in the current site. However when operatig on items, we
// have to make sure they are in the current page, or we could end up
// hacking on an item in a completely different site. This method checks
// that an item is OK to hack on, given the current page.
private boolean itemOk(Long itemId) {
// not specified, we'll add a new one
if (itemId == null || itemId == -1)
return true;
SimplePageItem item = findItem(itemId);
if (item.getPageId() != getCurrentPageId()) {
return false;
}
return true;
}
// called by the producer that uses FCK to update a text block
public String submit() {
String rv = "success";
if (!itemOk(itemId))
return "permission-failed";
if (canEditPage()) {
Placement placement = toolManager.getCurrentPlacement();
StringBuilder error = new StringBuilder();
// there's an issue with HTML security in the Sakai community.
// a lot of people feel users shouldn't be able to add javascirpt, etc
// to their HTML. I thik enforcing that makes Sakai less than useful.
// So check config options to see whether to do that check
String html = contents;
if (filterHtml && ! "false".equals(placement.getPlacementConfig().getProperty("filterHtml")) ||
"true".equals(placement.getPlacementConfig().getProperty("filterHtml"))) {
html = FormattedText.processFormattedText(contents, error);
} else {
html = FormattedText.processHtmlDocument(contents, error);
}
if (html != null) {
SimplePageItem item;
// itemid -1 means we're adding a new item to the page,
// specified itemid means we're updating an existing one
if (itemId != null && itemId != -1) {
item = findItem(itemId);
} else {
item = appendItem("", "", SimplePageItem.TEXT);
}
item.setHtml(html);
update(item);
} else {
rv = "cancel";
}
placement.save();
} else {
rv = "cancel";
}
return rv;
}
public String cancel() {
return "cancel";
}
public String processMultimedia() {
return processResource(SimplePageItem.MULTIMEDIA);
}
public String processResource() {
return processResource(SimplePageItem.RESOURCE);
}
// get mime type for a URL. connect to the server hosting
// it and ask them. Sorry, but I don't think there's a better way
public String getTypeOfUrl(String url) {
String mimeType = null;
// try to find the mime type of the remote resource
// this is only likely to be a problem if someone is pointing to
// a url within Sakai. We think in realistic cases those that are
// files will be handled as files, so anything that comes where
// will be HTML. That's the default if this fails.
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
// generate cookie based on code in RequestFilter.java
//String suffix = System.getProperty("sakai.serverId");
//if (suffix == null || suffix.equals(""))
// suffix = "sakai";
//Session s = sessionManager.getCurrentSession();
//conn.setRequestProperty("Cookie", "JSESSIONID=" + s.getId() + "." + suffix);
conn.connect();
String t = conn.getContentType();
if (t != null && !t.equals("")) {
int i = t.indexOf(";");
if (i >= 0)
t = t.substring(0, i);
t = t.trim();
mimeType = t;
}
conn.getInputStream().close();
} catch (Exception e) {log.error("getTypeOfUrl connection error " + e);};
return mimeType;
}
// return call from the file picker, used by add resource
// the picker communicates with us by session variables
public String processResource(int type) {
if (!canEditPage())
return "permission-failed";
ToolSession toolSession = sessionManager.getCurrentToolSession();
List refs = null;
String id = null;
String name = null;
String mimeType = null;
if (toolSession.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
refs = (List) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if (refs == null || refs.size() != 1) {
return "no-reference";
}
Reference ref = (Reference) refs.get(0);
id = ref.getId();
name = ref.getProperties().getProperty("DAV:displayname");
// URLs are complex. There are two issues:
// 1) The stupid helper treats a URL as a file upload. Have to make it a URL type.
// I suspect we're intended to upload a file from the URL, but I don't think
// any part of Sakai actually does that. So we reset Sakai's file type to URL
// 2) Lesson builder needs to know the mime type, to know how to set up the
// OBJECT or IFRAME. We send that out of band in the "html" field of the
// lesson builder item entry. I see no way to do that other than to talk
// to the server at the other end and see what MIME type it claims.
mimeType = ref.getProperties().getProperty("DAV:getcontenttype");
if (mimeType.equals("text/url")) {
mimeType = null; // use default rules if we can't find it
String url = null;
// part 1, fix up the type fields
try {
ContentResourceEdit res = contentHostingService.editResource(id);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
url = new String(res.getContent());
contentHostingService.commitResource(res);
} catch (Exception ignore) {
return "no-reference";
}
// part 2, find the actual data type.
if (url != null)
mimeType = getTypeOfUrl(url);
}
} else {
return "cancel";
}
try {
contentHostingService.checkResource(id);
} catch (PermissionException e) {
return "permission-exception";
} catch (IdUnusedException e) {
// Typically Means Cancel
return "cancel";
} catch (TypeException e) {
return "type-exception";
}
Long itemId = (Long)toolSession.getAttribute(LESSONBUILDER_ITEMID);
if (!itemOk(itemId))
return "permission-failed";
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
toolSession.removeAttribute(LESSONBUILDER_ITEMID);
String[] split = id.split("/");
SimplePageItem i;
if (itemId != null && itemId != -1) {
i = findItem(itemId);
i.setSakaiId(id);
if (mimeType != null)
i.setHtml(mimeType);
i.setName(name != null ? name : split[split.length - 1]);
clearImageSize(i);
} else {
i = appendItem(id, (name != null ? name : split[split.length - 1]), type);
if (mimeType != null) {
i.setHtml(mimeType);
}
}
i.setSameWindow(false);
update(i);
return "importing";
}
// set default for image size for new objects
private void clearImageSize(SimplePageItem i) {
// defaults to a fixed width and height, appropriate for some things, but for an
// image, leave it blank, since browser will then use the native size
if (i.getType() == SimplePageItem.MULTIMEDIA) {
if (isImageType(i)) {
i.setHeight("");
i.setWidth("");
}
}
}
// main code for adding a new item to a page
private SimplePageItem appendItem(String id, String name, int type) {
// add at the end of the page
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
SimplePageItem i = simplePageToolDao.makeItem(getCurrentPageId(), seq, type, id, name);
// defaults to a fixed width and height, appropriate for some things, but for an
// image, leave it blank, since browser will then use the native size
clearImageSize(i);
saveItem(i);
return i;
}
/**
* User can edit if he has site.upd or simplepage.upd. These do database queries, so
* try to save the results, rather than calling them many times on a page.
* @return
*/
public boolean canEditPage() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock(SimplePage.PERMISSION_LESSONBUILDER_UPDATE, ref);
}
public boolean canReadPage() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock(SimplePage.PERMISSION_LESSONBUILDER_READ, ref);
}
public boolean canEditSite() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock("site.upd", ref);
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setSecurityService(SecurityService service) {
securityService = service;
}
public void setSiteService(SiteService service) {
siteService = service;
}
public void setSimplePageToolDao(Object dao) {
simplePageToolDao = (SimplePageToolDao) dao;
}
public List<SimplePageItem> getItemsOnPage(long pageid) {
List<SimplePageItem>items = itemsCache.get(pageid);
if (items != null)
return items;
items = simplePageToolDao.findItemsOnPage(pageid);
for (SimplePageItem item: items) {
itemCache.put(item.getId(), item);
}
itemsCache.put(pageid, items);
return items;
}
/**
* Removes the item from the page, doesn't actually delete it.
*
* @return
*/
public String deleteItem() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
SimplePageItem i = findItem(itemId);
int seq = i.getSequence();
boolean b = false;
// if access controlled, clear it before deleting item
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
}
b = simplePageToolDao.deleteItem(i);
if (b) {
List<SimplePageItem> list = getItemsOnPage(getCurrentPageId());
for (SimplePageItem item : list) {
if (item.getSequence() > seq) {
item.setSequence(item.getSequence() - 1);
update(item);
}
}
return "successDelete";
} else {
log.warn("deleteItem error deleting Item: " + itemId);
return "failure";
}
}
// not clear whether it's worth caching this. The first time it's called for a site
// the pages are fetched. Beyond that it's a linear search of pages that are in memory
// ids are sakai.assignment.grades, sakai.samigo, sakai.mneme, sakai.forums, sakai.jforum.tool
public String getCurrentTool(String commonToolId) {
Site site = getCurrentSite();
ToolConfiguration tool = site.getToolForCommonId(commonToolId);
if (tool == null)
return null;
return tool.getId();
}
public String getCurrentToolTitle(String commonToolId) {
Site site = getCurrentSite();
ToolConfiguration tool = site.getToolForCommonId(commonToolId);
if (tool == null)
return null;
return tool.getTitle();
}
private Site getCurrentSite() {
if (currentSite != null) // cached value
return currentSite;
try {
currentSite = siteService.getSite(toolManager.getCurrentPlacement().getContext());
} catch (Exception impossible) {
impossible.printStackTrace();
}
return currentSite;
}
// find page to show in next link
// If the current page is a LB page, and it has a single "next" link on it, use that
// If the current page is a LB page, and it has more than one
// "next" link on it, show no next. If there's more than one
// next, this is probably a page with a branching queston, in
// which case there really isn't a single next.
// If the current page s a LB page, and it is not finished (i.e.
// there are required items not done), there is no next, or next
// is grayed out.
// Otherwise look at the page above in the breadcrumbs. If the
// next item on the page is not an inline item, and the item is
// available, next should be the next item on that page. (If
// it's an inline item we need to go back to the page above so
// they can see the inline item next.)
// If the current page is something like a test, there is an
// issue. What if the next item is not available when the page is
// displayed, because it requires that you get a passing score on
// the current test? For the moment, if the current item is required
// but the next is not available, show the link but test it when it's
// clicked.
// TODO: showpage and showitem, implement next. Should not pass a
// path argument. That gives next. If there's a pop we do it.
// in showitem, check if it's available, if not, show an error
// with a link to the page above.
// return: new item on same level, null if none, the item arg if need to go up a level
// java really needs to be able to return more than one thing, item == item is being
// used as a flag to return up a level
public SimplePageItem findNextPage(SimplePageItem item) {
if (item.getType() == SimplePageItem.PAGE) {
Long pageId = Long.valueOf(item.getSakaiId());
List<SimplePageItem> items = getItemsOnPage(pageId);
int nexts = 0;
SimplePageItem nextPage = null;
for (SimplePageItem i: items) {
if (i.getType() == SimplePageItem.PAGE && i.getNextPage()) {
nextPage = i;
nexts++;
}
}
// if next, use it; no next if not ready
if (nexts == 1) {
if (isItemAvailable(nextPage, pageId))
return nextPage;
return null;
}
// more than one, presumably you're intended to pick one of them, and
// there is no generic next
if (nexts > 1) {
return null;
}
// here for a page with no explicit next. Treat like any other item
// except that we need to compute pathop. Page must be complete or we
// would have returned null.
}
// see if there's an actual next we can go to, otherwise calling page
SimplePageItem nextItem = simplePageToolDao.findNextItemOnPage(item.getPageId(), item.getSequence());
boolean available = false;
if (nextItem != null) {
int itemType = nextItem.getType();
if (itemType == SimplePageItem.ASSIGNMENT ||
itemType == SimplePageItem.ASSESSMENT ||
itemType == SimplePageItem.FORUM ||
itemType == SimplePageItem.PAGE ||
itemType == SimplePageItem.RESOURCE && nextItem.isSameWindow()) {
// it's easy if the next item is available. If it's not, then
// we need to see if everything other than this item is done and
// this one is required. In that case the issue must be that this
// one isn't finished yet. Let's assume the user is going to finish
// this one. We'll verify that when he actually does the next;
if (isItemAvailable(nextItem, item.getPageId()) ||
item.isRequired() && wouldItemBeAvailable(item, item.getPageId()))
return nextItem;
}
}
// otherwise return to calling page
return item; // special flag
}
// corresponding code for outputting the link
// perhaps I should adjust the definition of path so that normal items show on it and not just pages
// but at the moment path is just the pages. So when we're in a normal item, it doesn't show.
// that means that as we do Next between items and pages, when we go to a page it gets pushed
// on and when we go from a page to an item, the page has to be popped off.
public void addNextLink(UIContainer tofill, SimplePageItem item) {
SimplePageItem nextItem = findNextPage(item);
if (nextItem == item) { // that we need to go up a level
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
int top;
if (path == null)
top = -1;
else
top = path.size()-1;
// if we're on a page, have to pop it off first
// for a normal item the end of the path already is the page above
if (item.getType() == SimplePageItem.PAGE)
top--;
if (top >= 0) {
PathEntry e = path.get(top);
GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
view.setSendingPage(e.pageId);
view.setItemId(e.pageItemId);
view.setPath(Integer.toString(top));
UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
}
} else if (nextItem != null) {
GeneralViewParameters view = new GeneralViewParameters();
int itemType = nextItem.getType();
if (itemType == SimplePageItem.PAGE) {
view.setSendingPage(Long.valueOf(nextItem.getSakaiId()));
view.viewID = ShowPageProducer.VIEW_ID;
if (item.getType() == SimplePageItem.PAGE)
view.setPath("next"); // page to page, just a next
else
view.setPath("push"); // item to page, have to push the page
} else if (itemType == SimplePageItem.RESOURCE) { /// must be a same page resource
view.setSendingPage(Long.valueOf(item.getPageId()));
// to the check. We need the check to set access control appropriately
// if the user has passed.
if (!isItemAvailable(nextItem, nextItem.getPageId()))
view.setRecheck("true");
view.setSource(nextItem.getItemURL());
view.viewID = ShowItemProducer.VIEW_ID;
} else {
view.setSendingPage(Long.valueOf(item.getPageId()));
LessonEntity lessonEntity = null;
switch (nextItem.getType()) {
case SimplePageItem.ASSIGNMENT:
lessonEntity = assignmentEntity.getEntity(nextItem.getSakaiId()); break;
case SimplePageItem.ASSESSMENT:
view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
lessonEntity = quizEntity.getEntity(nextItem.getSakaiId()); break;
case SimplePageItem.FORUM:
lessonEntity = forumEntity.getEntity(nextItem.getSakaiId()); break;
}
// normally we won't send someone to an item that
// isn't available. But if the current item is a test, etc, we can't
// know whether the user will pass it, so we have to ask ShowItem to
// to the check. We need the check to set access control appropriately
// if the user has passed.
if (!isItemAvailable(nextItem, nextItem.getPageId()))
view.setRecheck("true");
view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
if (item.getType() == SimplePageItem.PAGE)
view.setPath("pop"); // now on a have, have to pop it off
view.viewID = ShowItemProducer.VIEW_ID;
}
view.setItemId(nextItem.getId());
view.setBackPath("push");
UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
}
}
// Because of the existence of chains of "next" pages, there's no static approach that will find
// back links. Thus we keep track of the actual path the user has followed. However we have to
// prune both path and back path when we return to an item that's already on them to avoid
// loops of various kinds.
public void addPrevLink(UIContainer tofill, SimplePageItem item) {
List<PathEntry> backPath = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_BACKPATH);
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
// current item is last on path, so need one before that
if (backPath == null || backPath.size() < 2)
return;
PathEntry prevEntry = backPath.get(backPath.size()-2);
SimplePageItem prevItem = findItem(prevEntry.pageItemId);
GeneralViewParameters view = new GeneralViewParameters();
int itemType = prevItem.getType();
if (itemType == SimplePageItem.PAGE) {
view.setSendingPage(Long.valueOf(prevItem.getSakaiId()));
view.viewID = ShowPageProducer.VIEW_ID;
// are we returning to a page? If so use existing path entry
int lastEntry = -1;
int i = 0;
long prevItemId = prevEntry.pageItemId;
for (PathEntry entry: path) {
if (entry.pageItemId == prevItemId)
lastEntry = i;
i++;
}
if (lastEntry >= 0)
view.setPath(Integer.toString(lastEntry));
else if (item.getType() == SimplePageItem.PAGE)
view.setPath("next"); // page to page, just a next
else
view.setPath("push"); // item to page, have to push the page
} else if (itemType == SimplePageItem.RESOURCE) { // must be a samepage resource
view.setSendingPage(Long.valueOf(item.getPageId()));
view.setSource(prevItem.getItemURL());
view.viewID = ShowItemProducer.VIEW_ID;
} else {
view.setSendingPage(Long.valueOf(item.getPageId()));
LessonEntity lessonEntity = null;
switch (prevItem.getType()) {
case SimplePageItem.ASSIGNMENT:
lessonEntity = assignmentEntity.getEntity(prevItem.getSakaiId()); break;
case SimplePageItem.ASSESSMENT:
view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
lessonEntity = quizEntity.getEntity(prevItem.getSakaiId()); break;
case SimplePageItem.FORUM:
lessonEntity = forumEntity.getEntity(prevItem.getSakaiId()); break;
}
view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
if (item.getType() == SimplePageItem.PAGE)
view.setPath("pop"); // now on a page, have to pop it off
view.viewID = ShowItemProducer.VIEW_ID;
}
view.setItemId(prevItem.getId());
view.setBackPath("pop");
UIInternalLink.make(tofill, "prev", messageLocator.getMessage("simplepage.back"), view);
}
public String getCurrentSiteId() {
try {
return toolManager.getCurrentPlacement().getContext();
} catch (Exception impossible) {
return null;
}
}
// recall that code typically operates on a "current page." See below for
// the code that sets a new current page. We also have a current item, which
// is the item defining the page. I.e. if the page is a subpage of anotehr
// one, this is the item on the parent page pointing to this page. If it's
// a top-level page, it's a dummy item. The item is needed in order to do
// access checks. Whether an item is required, etc, is stored in the item.
// in theory a page could be caled from several other pages, with different
// access control parameters. So we need to know the actual item on the page
// page from which this page was called.
// we need to track the pageitem because references to the same page can appear
// in several places. In theory each one could have different status of availability
// so we need to know which in order to check availability
public void updatePageItem(long item) throws PermissionException {
SimplePageItem i = findItem(item);
if (i != null) {
if ((long)currentPageId != (long)Long.valueOf(i.getSakaiId())) {
log.warn("updatePageItem permission failure " + i + " " + Long.valueOf(i.getSakaiId()) + " " + currentPageId);
throw new PermissionException(getCurrentUserId(), "set item", Long.toString(item));
}
}
currentPageItemId = item;
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-item", item);
}
// update our concept of the current page. it is imperative to make sure the page is in
// the current site, or people could hack on other people's pages
// if you call updatePageObject, consider whether you need to call updatePageItem as well
// this combines two functions, so maybe not, but any time you're goign to a new page
// you should do both. Make sure all Producers set the page to the one they will work on
public void updatePageObject(long l) throws PermissionException {
if (l != previousPageId) {
currentPage = simplePageToolDao.getPage(l);
String siteId = toolManager.getCurrentPlacement().getContext();
// page should always be in this site, or someone is gaming us
if (!currentPage.getSiteId().equals(siteId))
throw new PermissionException(getCurrentUserId(), "set page", Long.toString(l));
previousPageId = l;
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-page", l);
currentPageId = (Long)l;
}
}
// if tool was reset, return last page from previous session, so we can give the user
// a chance to go back
public SimplePageToolDao.PageData toolWasReset() {
if (sessionManager.getCurrentToolSession().getAttribute("current-pagetool-page") == null) {
// no page in session, which means it was reset
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
return simplePageToolDao.findMostRecentlyVisitedPage(getCurrentUserId(), toolId);
} else
return null;
}
// ought to be simple, but this is typically called at the beginning of a producer, when
// the current page isn't set yet. So if there isn't one, we use the session variable
// to tell us what the current page is. Note that a user can add our tool using Site
// Info. Site info knows nothing about us, so it will make an entry for the page without
// creating it. When the user then tries to go to the page, this code will be the firsst
// to notice it. Hence we have to create pages that don't exist
private long getCurrentPageId() {
// return ((ToolConfiguration)toolManager.getCurrentPlacement()).getPageId();
if (currentPageId != null)
return (long)currentPageId;
// Let's go back to where we were last time.
Long l = (Long) sessionManager.getCurrentToolSession().getAttribute("current-pagetool-page");
if (l != null && l != 0) {
try {
updatePageObject(l);
Long i = (Long) sessionManager.getCurrentToolSession().getAttribute("current-pagetool-item");
if (i != null && i != 0)
updatePageItem(i);
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to item in toolsession");
return 0;
}
return l;
} else {
// No recent activity. Let's go to the top level page.
l = simplePageToolDao.getTopLevelPageId(((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId());
if (l != null) {
try {
updatePageObject(l);
// this should exist except if the page was created by old code
SimplePageItem i = simplePageToolDao.findTopLevelPageItemBySakaiId(String.valueOf(l));
if (i == null) {
// and dummy item, the site is the notional top level page
i = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, l.toString(), currentPage.getTitle());
saveItem(i);
}
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to page in toolsession");
return 0;
}
return l;
} else {
// No page found. Let's make a new one.
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
String title = getCurrentSite().getPage(toolId).getTitle(); // Use title supplied
// during creation
SimplePage page = simplePageToolDao.makePage(toolId, toolManager.getCurrentPlacement().getContext(), title, null, null);
if (!saveItem(page)) {
currentPage = null;
return 0;
}
try {
updatePageObject(page.getPageId());
l = page.getPageId();
// and dummy item, the site is the notional top level page
SimplePageItem i = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, l.toString(), title);
saveItem(i);
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to new page");
return 0;
}
return l;
}
}
}
// current page must be set.
public SimplePageItem getCurrentPageItem(Long itemId) {
// if itemId is known, this is easy. but check to make sure it's
// actually this page, to prevent the user gaming us
if (itemId == null || itemId == -1)
itemId = currentPageItemId;
if (itemId != null && itemId != -1) {
SimplePageItem ret = findItem(itemId);
if (ret != null && ret.getSakaiId().equals(Long.toString(getCurrentPageId()))) {
try {
updatePageItem(ret.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageItem Permission failed setting to specified item");
return null;
}
return ret;
} else
return null;
}
// else must be a top level item
SimplePageItem ret = simplePageToolDao.findTopLevelPageItemBySakaiId(Long.toString(getCurrentPageId()));
try {
updatePageItem(ret.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageItem Permission failed setting to top level page in tool session");
return null;
}
return ret;
}
// called at the start of showpageproducer, with page info for the page about to be displayed
// updates the breadcrumbs, which are kept in session variables.
// returns string version of the new path
public String adjustPath(String op, Long pageId, Long pageItemId, String title) {
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
// if no current path, op doesn't matter. we can just do the current page
if (path == null || path.size() == 0) {
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
path = new ArrayList<PathEntry>();
path.add(entry);
} else if (path.get(path.size()-1).pageId.equals(pageId)) {
// nothing. we're already there. this is to prevent
// oddities if we refresh the page
} else if (op == null || op.equals("") || op.equals("next")) {
PathEntry entry = path.get(path.size()-1); // overwrite last item
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
} else if (op.equals("push")) {
// a subpage
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
path.add(entry); // put it on the end
} else if (op.equals("pop")) {
// a subpage
path.remove(path.size()-1);
} else if (op.startsWith("log")) {
// set path to what was saved in the last log entry for this item
// this is used for users who go directly to a page from the
// main list of pages.
path = new ArrayList<PathEntry>();
SimplePageLogEntry logEntry = getLogEntry(pageItemId);
if (logEntry != null) {
String items[] = null;
if (logEntry.getPath() != null)
items = logEntry.getPath().split(",");
if (items != null) {
for(String s: items) {
// don't see how this could happen, but it did
if (s.trim().equals("")) {
log.warn("adjustPath attempt to set invalid path: invalid item: " + op + ":" + logEntry.getPath());
return null;
}
SimplePageItem i = findItem(Long.valueOf(s));
if (i == null || i.getType() != SimplePageItem.PAGE) {
log.warn("adjustPath attempt to set invalid path: invalid item: " + op);
return null;
}
SimplePage p = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
if (p == null || !currentPage.getSiteId().equals(p.getSiteId())) {
log.warn("adjustPath attempt to set invalid path: invalid page: " + op);
return null;
}
PathEntry entry = new PathEntry();
entry.pageId = p.getPageId();
entry.pageItemId = i.getId();
entry.title = i.getName();
path.add(entry);
}
}
}
} else {
int index = Integer.valueOf(op); // better be number
if (index < path.size()) {
// if we're going back, this should actually
// be redundant
PathEntry entry = path.get(index); // back to specified item
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
if (index < (path.size()-1))
path.subList(index+1, path.size()).clear();
}
}
// have new path; set it in session variable
sessionManager.getCurrentToolSession().setAttribute(LESSONBUILDER_PATH, path);
// and make string representation to return
String ret = null;
for (PathEntry entry: path) {
String itemString = Long.toString(entry.pageItemId);
if (ret == null)
ret = itemString;
else
ret = ret + "," + itemString;
}
if (ret == null)
ret = "";
return ret;
}
public void adjustBackPath(String op, Long pageId, Long pageItemId, String title) {
List<PathEntry> backPath = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_BACKPATH);
if (backPath == null)
backPath = new ArrayList<PathEntry>();
// default case going directly to something.
// normally we want to push it, but if it's already there,
// we're going back to it, use the old one
if (op == null || op.equals("")) {
// is it there already? Some would argue that we should use the first occurrence
int lastEntry = -1;
int i = 0;
long itemId = pageItemId; // to avoid having to use equals
for (PathEntry entry: backPath) {
if (entry.pageItemId == itemId)
lastEntry = i;
i++;
}
if (lastEntry >= 0) {
// yes, back up to that entry
if (lastEntry < (backPath.size()-1))
backPath.subList(lastEntry+1, backPath.size()).clear();
return;
}
// no fall through and push the new item
}
if (op.equals("pop")) {
if (backPath.size() > 0)
backPath.remove(backPath.size()-1);
} else { // push or no operation
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
backPath.add(entry);
}
// have new path; set it in session variable
sessionManager.getCurrentToolSession().setAttribute(LESSONBUILDER_BACKPATH, backPath);
}
public void setSubpageTitle(String st) {
subpageTitle = st;
}
public void setSubpageNext(boolean s) {
subpageNext = s;
}
public void setSubpageButton(boolean s) {
subpageButton = s;
}
// called from "add subpage" dialog
// create if itemId == null or -1, else update existing
public String createSubpage() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
String title = subpageTitle;
boolean makeNewPage = (selectedEntity == null || selectedEntity.length() == 0);
boolean makeNewItem = (itemId == null || itemId == -1);
if ((title == null || title.length() == 0) &&
(selectedEntity == null || selectedEntity.length() == 0)) {
return "notitle";
}
SimplePage page = getCurrentPage();
Long parent = page.getPageId();
Long topParent = page.getTopParent();
if (topParent == null) {
topParent = parent;
}
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
SimplePage subpage = null;
if (makeNewPage) {
subpage = simplePageToolDao.makePage(toolId, toolManager.getCurrentPlacement().getContext(), title, parent, topParent);
saveItem(subpage);
selectedEntity = String.valueOf(subpage.getPageId());
} else {
subpage = simplePageToolDao.getPage(Long.valueOf(selectedEntity));
}
SimplePageItem i = null;
if (makeNewItem)
i = appendItem(selectedEntity, subpage.getTitle(), SimplePageItem.PAGE);
else
i = findItem(itemId);
if (i == null)
return "failure";
if (makeNewItem) {
i.setNextPage(subpageNext);
if (subpageButton)
i.setFormat("button");
else
i.setFormat("");
} else {
// when itemid is specified, we're changing pages for existing entry
i.setSakaiId(selectedEntity);
i.setName(subpage.getTitle());
}
update(i);
if (makeNewPage) {
// if creating new entry, go to it
try {
updatePageObject(subpage.getPageId());
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("createSubpage permission failed going to new page");
return "failed";
}
adjustPath((subpageNext ? "next" : "push"), subpage.getPageId(), i.getId(), i.getName());
submit();
}
return "success";
}
public String deletePages() {
if (!canEditPage())
return "permission-failed";
String siteId = toolManager.getCurrentPlacement().getContext();
for (int i = 0; i < selectedEntities.length; i++) {
SimplePage target = simplePageToolDao.getPage(Long.valueOf(selectedEntities[i]));
if (target != null) {
if (!target.getSiteId().equals(siteId)) {
return "permission-failed";
}
// delete all the items on the page
List<SimplePageItem> items = getItemsOnPage(target.getPageId());
for (SimplePageItem item: items) {
// if access controlled, clear it before deleting item
if (item.isPrerequisite()) {
item.setPrerequisite(false);
checkControlGroup(item);
}
simplePageToolDao.deleteItem(item);
}
// remove from gradebook
gradebookIfc.removeExternalAssessment(siteId, "lesson-builder:" + target.getPageId());
// remove fake item if it's top level. We won't see it if it's still active
// so this means the user has removed it in site info
SimplePageItem item = simplePageToolDao.findTopLevelPageItemBySakaiId(selectedEntities[i]);
if (item != null)
simplePageToolDao.deleteItem(item);
// currently the UI doesn't allow you to kill top level pages until they have been
// removed by site info, so we don't have to hack on the site pages
// remove page
simplePageToolDao.deleteItem(target);
}
}
return "success";
}
// remove a top-level page from the left margin. Does not actually delete it.
// this and addpages checks only edit page permission. should it check site.upd?
public String removePage() {
if (!canEditPage())
return "permission-failed";
Site site = getCurrentSite();
SimplePage page = getCurrentPage();
SitePage sitePage = site.getPage(page.getToolId());
if (sitePage == null) {
log.error("removePage can't find site page for " + page.getPageId());
return "no-such-page";
}
site.removePage(sitePage);
try {
siteService.save(site);
} catch (Exception e) {
log.error("removePage unable to save site " + e);
}
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.remove", "/lessonbuilder/page/" + page.getPageId(), true));
return "success";
}
// called from "save" in main edit item dialog
public String editItem() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (name.length() < 1) {
return "Notitle";
}
SimplePageItem i = findItem(itemId);
if (i == null) {
return "failure";
} else {
i.setName(name);
i.setDescription(description);
i.setRequired(required);
i.setPrerequisite(prerequisite);
i.setSubrequirement(subrequirement);
i.setNextPage(subpageNext);
if (subpageButton)
i.setFormat("button");
else
i.setFormat("");
if (points != "") {
i.setRequirementText(points);
} else {
i.setRequirementText(dropDown);
}
// currently we only display HTML in the same page
if (i.getType() == SimplePageItem.RESOURCE)
i.setSameWindow(!newWindow);
else
i.setSameWindow(false);
update(i);
if (i.getType() == SimplePageItem.PAGE) {
SimplePage page = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
if (page != null) {
page.setTitle(name);
update(page);
}
} else {
checkControlGroup(i);
}
return "successEdit"; // Shouldn't reload page
}
}
// Set access control for an item to the state requested by i.isPrerequisite().
// This code should depend only upon isPrerequisite() in the item object, not the database,
// because we call it when deleting or updating items, before saving them to the database.
// The caller will update the item in the database, typically after this call
private void checkControlGroup(SimplePageItem i) {
if (i.getType() != SimplePageItem.ASSESSMENT &&
i.getType() != SimplePageItem.ASSIGNMENT &&
i.getType() != SimplePageItem.FORUM) {
// We only do this for assignments and assessments
// currently we can't actually set it for forum topics
return;
}
if (i.getSakaiId().equals(SimplePageItem.DUMMY))
return;
SimplePageGroup group = simplePageToolDao.findGroup(i.getSakaiId());
try {
if (i.isPrerequisite()) {
if (group == null) {
String groupId = GroupPermissionsService.makeGroup(getCurrentPage().getSiteId(), "Access: " + getNameOfSakaiItem(i));
saveItem(simplePageToolDao.makeGroup(i.getSakaiId(), groupId));
GroupPermissionsService.addControl(i.getSakaiId(), getCurrentPage().getSiteId(), groupId, i.getType());
} else {
GroupPermissionsService.addControl(i.getSakaiId(), getCurrentPage().getSiteId(), group.getGroupId(), i.getType());
}
} else {
// if no group ID, nothing to do
if (group != null)
GroupPermissionsService.removeControl(i.getSakaiId(), getCurrentPage().getSiteId(), group.getGroupId(), i.getType());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public SimplePage getCurrentPage() {
getCurrentPageId();
return currentPage;
}
public String getToolId(String tool) {
try {
ToolConfiguration tc = siteService.getSite(currentPage.getSiteId()).getToolForCommonId(tool);
return tc.getId();
} catch (IdUnusedException e) {
// This really shouldn't happen.
log.warn("getToolId 1 attempt to get tool config for " + tool + " failed. Tool missing from site?");
return null;
} catch (java.lang.NullPointerException e) {
log.warn("getToolId 2 attempt to get tool config for " + tool + " failed. Tool missing from site?");
return null;
}
}
public void updateCurrentPage() {
update(currentPage);
}
public List<PathEntry> getHierarchy() {
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
if (path == null)
return new ArrayList<PathEntry>();
return path;
}
public void setSelectedAssignment(String selectedAssignment) {
this.selectedAssignment = selectedAssignment;
}
public void setSelectedEntity(String selectedEntity) {
this.selectedEntity = selectedEntity;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
public String assignmentRef(String id) {
return "/assignment/a/" + toolManager.getCurrentPlacement().getContext() + "/" + id;
}
// called by add forum dialog. Create a new item that points to a forum or
// update an existing item, depending upon whether itemid is set
public String addForum() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedEntity == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = forumEntity.getEntity(selectedEntity);
if (selectedObject == null) {
return "failure";
}
SimplePageItem i;
// editing existing item?
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// if no change, don't worry
if (!i.getSakaiId().equals(selectedEntity)) {
// if access controlled, clear restriction from old assignment and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedEntity);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedEntity);
i.setName(selectedObject.getTitle());
}
// reset assignment-specific stuff
i.setDescription("");
update(i);
}
} else {
// no, add new item
i = appendItem(selectedEntity, selectedObject.getTitle(), SimplePageItem.FORUM);
i.setDescription("");
update(i);
}
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedEntity = null;
}
}
}
// called by add assignment dialog. Create a new item that points to an assigment
// or update an existing item, depending upon whether itemid is set
public String addAssignment() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedAssignment == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = assignmentEntity.getEntity(selectedAssignment);
if (selectedObject == null)
return "failure";
SimplePageItem i;
// editing existing item?
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// if no change, don't worry
LessonEntity existing = assignmentEntity.getEntity(i.getSakaiId());
String ref = existing.getReference();
// if same quiz, nothing to do
if (!ref.equals(selectedAssignment)) {
// if access controlled, clear restriction from old assignment and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedAssignment);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedAssignment);
i.setName(selectedObject.getTitle());
}
// reset assignment-specific stuff
i.setDescription("(Due " + DateFormat.getDateTimeInstance().format(selectedObject.getDueDate()));
update(i);
}
} else {
// no, add new item
i = appendItem(selectedAssignment, selectedObject.getTitle(), SimplePageItem.ASSIGNMENT);
i.setDescription("(Due " + DateFormat.getDateTimeInstance().format(selectedObject.getDueDate()));
update(i);
}
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedAssignment = null;
}
}
}
// called by add quiz dialog. Create a new item that points to a quiz
// or update an existing item, depending upon whether itemid is set
public String addQuiz() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedQuiz == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = quizEntity.getEntity(selectedQuiz);
if (selectedObject == null)
return "failure";
// editing existing item?
SimplePageItem i;
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// do getEntity/getreference to normalize, in case sakaiid is old format
LessonEntity existing = quizEntity.getEntity(i.getSakaiId());
String ref = existing.getReference();
// if same quiz, nothing to do
if (!ref.equals(selectedQuiz)) {
// if access controlled, clear restriction from old quiz and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedQuiz);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedQuiz);
i.setName(selectedObject.getTitle());
}
// reset quiz-specific stuff
i.setDescription("");
update(i);
}
} else // no, add new item
appendItem(selectedQuiz, selectedObject.getTitle(), SimplePageItem.ASSESSMENT);
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedQuiz = null;
}
}
}
public void setLinkUrl(String url) {
linkUrl = url;
}
// doesn't seem to be used at the moment
public String createLink() {
if (linkUrl == null || linkUrl.equals("")) {
return "cancel";
}
String url = linkUrl;
url = url.trim();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
appendItem(url, url, SimplePageItem.URL);
return "success";
}
public void setPage(long pageId) {
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-page", pageId);
currentPageId = null;
}
// more setters and getters used by forms
public void setHeight(String height) {
this.height = height;
}
public String getHeight() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getHeight();
}
return (r == null ? "" : r);
}
public void setWidth(String width) {
this.width = width;
}
public String getWidth() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getWidth();
}
return (r == null ? "" : r);
}
public String getAlt() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getAlt();
}
return (r == null ? "" : r);
}
// called by edit multimedia dialog to change parameters in a multimedia item
public String editMultimedia() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
SimplePageItem i = findItem(itemId);
if (i != null && i.getType() == SimplePageItem.MULTIMEDIA) {
i.setHeight(height);
i.setWidth(width);
i.setAlt(alt);
i.setDescription(description);
i.setHtml(mimetype);
update(i);
return "success";
} else {
log.warn("editMultimedia Could not find multimedia object: " + itemId);
return "cancel";
}
}
// called by edit title dialog to change attributes of the page such as the title
public String editTitle() {
if (pageTitle == null || pageTitle.equals("")) {
return "notitle";
}
// because we're using a security advisor, need to make sure it's OK ourselves
if (!canEditPage()) {
return "permission-failed";
}
Placement placement = toolManager.getCurrentPlacement();
SimplePage page = getCurrentPage();
SimplePageItem pageItem = getCurrentPageItem(null);
// update gradebook link if necessary
Double currentPoints = page.getGradebookPoints();
Double newPoints = null;
boolean needRecompute = false;
Site site = getCurrentSite();
if (points != null) {
try {
newPoints = Double.parseDouble(points);
if (newPoints == 0.0)
newPoints = null;
} catch (Exception ignore) {
newPoints = null;
}
}
// adjust gradebook entry
if (newPoints == null && currentPoints != null) {
gradebookIfc.removeExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId());
} else if (newPoints != null && currentPoints == null) {
gradebookIfc.addExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(), null,
pageTitle, newPoints, null, "Lesson Builder");
needRecompute = true;
} else if (currentPoints != null &&
(!currentPoints.equals(newPoints) || !pageTitle.equals(page.getTitle()))) {
gradebookIfc.updateExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(), null,
pageTitle, newPoints, null);
if (currentPoints != newPoints)
needRecompute = true;
}
page.setGradebookPoints(newPoints);
if (pageTitle != null && pageItem.getPageId() == 0) {
try {
// we need a security advisor because we're allowing users to edit the page if they
// have
// simplepage.upd privileges, but site.save requires site.upd.
securityService.pushAdvisor(new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
if (function.equals(SITE_UPD) && reference.equals("/site/" + toolManager.getCurrentPlacement().getContext())) {
return SecurityAdvice.ALLOWED;
} else {
return SecurityAdvice.PASS;
}
}
});
if (true) {
SitePage sitePage = site.getPage(page.getToolId());
sitePage.setTitle(pageTitle);
siteService.save(site);
page.setTitle(pageTitle);
page.setHidden(hidePage);
if (hasReleaseDate)
page.setReleaseDate(releaseDate);
else
page.setReleaseDate(null);
update(page);
updateCurrentPage();
placement.setTitle(pageTitle);
placement.save();
pageVisibilityHelper(site, page.getToolId(), !hidePage);
pageItem.setPrerequisite(prerequisite);
pageItem.setRequired(required);
update(pageItem);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
securityService.popAdvisor();
}
} else if (pageTitle != null) {
page.setTitle(pageTitle);
update(page);
}
if(pageTitle != null) {
pageItem.setName(pageTitle);
update(pageItem);
adjustPath("", pageItem.getPageId(), pageItem.getId(), pageTitle);
}
// have to do this after the page itself is updated
if (needRecompute)
recomputeGradebookEntries(page.getPageId(), points);
// points, not newPoints because API wants a string
if (pageItem.getPageId() == 0) {
return "reload";
} else {
return "success";
}
}
public String addPages() {
if (!canEditPage())
return "permission-fail";
// javascript should have checked all this
if (newPageTitle == null || newPageTitle.equals(""))
return "fail";
int numPages = 1;
if (numberOfPages !=null && !numberOfPages.equals(""))
numPages = Integer.valueOf(numberOfPages);
String prefix = "";
String suffix = "";
int start = 1;
if (numPages > 1) {
Pattern pattern = Pattern.compile("(\\D*)(\\d+)(.*)");
Matcher matcher = pattern.matcher(newPageTitle);
if (!matcher.matches())
return "fail";
prefix = matcher.group(1);
suffix = matcher.group(3);
start = Integer.parseInt(matcher.group(2));
}
if (numPages == 1) {
addPage(newPageTitle, copyPage);
} else {
// note sure what to do here. We have to have a maximum to prevent creating 1,000,000 pages due
// to a typo. This allows one a week for a year. Surely that's enough. We can make it
// configurable if necessary.
if (numPages > 52)
numPages = 52;
while (numPages > 0) {
String title = prefix + Integer.toString(start) + suffix;
addPage(title, copyPage);
numPages--;
start++;
}
}
return "success";
}
public SimplePage addPage(String title, boolean copyCurrent) {
Site site = getCurrentSite();
SitePage sitePage = site.addPage();
ToolConfiguration tool = sitePage.addTool(LESSONBUILDER_ID);
tool.setTitle(title);
String toolId = tool.getPageId();
sitePage.setTitle(title);
sitePage.setTitleCustom(true);
try {
siteService.save(site);
} catch (Exception e) {
log.error("addPage unable to save site " + e);
}
currentSite = null; // force refetch, since we've changed it
SimplePage page = simplePageToolDao.makePage(toolId, getCurrentSiteId(), title, null, null);
saveItem(page);
SimplePageItem item = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, Long.toString(page.getPageId()), title);
saveItem(item);
if (copyCurrent) {
long oldPageId = getCurrentPageId();
long newPageId = page.getPageId();
for (SimplePageItem oldItem: simplePageToolDao.findItemsOnPage(oldPageId)) {
SimplePageItem newItem = simplePageToolDao.copyItem(oldItem);
newItem.setPageId(newPageId);
saveItem(newItem);
}
}
return page;
}
// when a gradebook entry is added or point value for page changed, need to
// add or update all student entries for the page
// this only updates grades for users that are complete. Others should have 0 score, which won't change
public void recomputeGradebookEntries(Long pageId, String newPoints) {
Map<String, String> userMap = new HashMap<String,String>();
List<SimplePageItem> items = simplePageToolDao.findPageItemsBySakaiId(Long.toString(pageId));
if (items == null)
return;
for (SimplePageItem item : items) {
List<String> users = simplePageToolDao.findUserWithCompletePages(item.getId());
for (String user: users)
userMap.put(user, newPoints);
}
gradebookIfc.updateExternalAssessmentScores(getCurrentSiteId(), "lesson-builder:" + pageId, userMap);
}
public boolean isImageType(SimplePageItem item) {
// if mime type is defined use it
String mimeType = item.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals("")))
mimeType = null;
if (mimeType != null && mimeType.length() > 0) {
return mimeType.toLowerCase().startsWith("image/");
}
// else use extension
String name = item.getSakaiId();
// starts after last /
int i = name.lastIndexOf("/");
if (i >= 0)
name = name.substring(i+1);
String extension = null;
i = name.lastIndexOf(".");
if (i > 0)
extension = name.substring(i+1);
if (extension == null)
return false;
extension = extension.trim();
extension = extension.toLowerCase();
if (imageTypes.contains(extension)) {
return true;
} else {
return false;
}
}
public void setOrder(String order) {
this.order = order;
}
// called by reorder tool to do the reordering
public String reorder() {
if (!canEditPage())
return "permission-fail";
if (order == null) {
return "cancel";
}
order = order.trim();
List<SimplePageItem> items = getItemsOnPage(getCurrentPageId());
String[] split = order.split(" ");
// make sure nothing is duplicated. I know it shouldn't be, but
// I saw the Fluid reorderer get confused once.
Set<Integer> used = new HashSet<Integer>();
for (int i = 0; i < split.length; i++) {
if (!used.add(Integer.valueOf(split[i]))) {
log.warn("reorder: duplicate value");
return "failed"; // it was already there. Oops.
}
}
// now do the reordering
for (int i = 0; i < split.length; i++) {
int old = items.get(Integer.valueOf(split[i]) - 1).getSequence();
items.get(Integer.valueOf(split[i]) - 1).setSequence(i + 1);
if (old != i + 1) {
update(items.get(Integer.valueOf(split[i]) - 1));
}
}
return "success";
}
// this is sort of sleasy. A simple redirect passes no data. Thus it takes
// us back to the default page. So we advance the default page. It would probably
// have been better to use a link rather than a command, then the link could
// have passed the page and item.
// public String next() {
// getCurrentPageId(); // sets item id, which is what we want
// SimplePageItem item = getCurrentPageItem(null);
//
// List<SimplePageItem> items = getItemsOnPage(item.getPageId());
//
// item = items.get(item.getSequence()); // sequence start with 1, so this is the next item
// updatePageObject(Long.valueOf(item.getSakaiId()));
// updatePageItem(item.getId());
//
// return "redirect";
// }
public String getCurrentUserId() {
if (currentUserId == null)
currentUserId = sessionManager.getCurrentSessionUserId();
return currentUserId;
}
// page is complete, update gradebook entry if any
// note that if the user has never gone to a page, the gradebook item will be missing.
// if they gone to it but it's not complete, it will be 0. We can't explicitly set
// a missing value, and this is the only way things will work if someone completes a page
// and something changes so it is no longer complete.
public void trackComplete(SimplePageItem item, boolean complete ) {
SimplePage page = getCurrentPage();
if (page.getGradebookPoints() != null)
gradebookIfc.updateExternalAssessmentScore(getCurrentSiteId(), "lesson-builder:" + page.getPageId(), getCurrentUserId(),
complete ? Double.toString(page.getGradebookPoints()) : "0.0");
}
/**
*
* @param itemId
* The ID in the <b>items</b> table.
* @param path
* breadcrumbs, only supplied it the item is a page
* It is valid for code to check path == null to see
* whether it is a page
* Create or update a log entry when user accesses an item.
*/
public void track(long itemId, String path) {
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
SimplePageLogEntry entry = getLogEntry(itemId);
if (entry == null) {
entry = simplePageToolDao.makeLogEntry(userId, itemId);
if (path != null) {
boolean complete = isPageComplete(itemId);
entry.setComplete(complete);
entry.setPath(path);
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
entry.setToolId(toolId);
SimplePageItem i = findItem(itemId);
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.read", "/lessonbuilder/page/" + i.getSakaiId(), complete));
trackComplete(i, complete);
}
saveItem(entry);
logCache.put((Long)itemId, entry);
} else {
if (path != null) {
boolean wasComplete = entry.isComplete();
boolean complete = isPageComplete(itemId);
entry.setComplete(complete);
entry.setPath(path);
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
entry.setToolId(toolId);
entry.setDummy(false);
SimplePageItem i = findItem(itemId);
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.read", "/lessonbuilder/page/" + i.getSakaiId(), complete));
if (complete != wasComplete)
trackComplete(i, complete);
}
update(entry);
}
//SimplePageItem i = findItem(itemId);
// todo
// code can't work anymore. I'm not sure whether it's needed.
// we don't update a page as complete if the user finishes a test, etc, until he
// comes back to the page. I'm not sure I feel compelled to do this either. But
// once we move to the new hiearchy, we'll see
// top level doesn't have a next level, so avoid null pointer problem
// if (i.getPageId() != 0) {
// SimplePageItem nextLevelUp = simplePageToolDao.findPageItemBySakaiId(String.valueOf(i.getPageId()));
// if (isItemComplete(findItem(itemId)) && nextLevelUp != null) {
// track(nextLevelUp.getId(), true);
// }
// }
}
public SimplePageLogEntry getLogEntry(long itemId) {
SimplePageLogEntry entry = logCache.get((Long)itemId);
if (entry != null)
return entry;
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
entry = simplePageToolDao.getLogEntry(userId, itemId);
logCache.put((Long)itemId, entry);
return entry;
}
public boolean hasLogEntry(long itemId) {
return (getLogEntry(itemId) != null);
}
// this is called in a loop to see whether items are avaiable. Since computing it can require
// database transactions, we cache the results
public boolean isItemComplete(SimplePageItem item) {
if (!item.isRequired()) {
// We don't care if it has been completed if it isn't required.
return true;
}
Long itemId = item.getId();
Boolean cached = completeCache.get(itemId);
if (cached != null)
return (boolean)cached;
if (item.getType() == SimplePageItem.RESOURCE || item.getType() == SimplePageItem.URL) {
// Resource. Completed if viewed.
if (hasLogEntry(item.getId())) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.PAGE) {
SimplePageLogEntry entry = getLogEntry(item.getId());
if (entry == null || entry.getDummy()) {
completeCache.put(itemId, false);
return false;
} else if (entry.isComplete()) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.ASSIGNMENT) {
try {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
LessonEntity assignment = assignmentEntity.getEntity(item.getSakaiId());
if (assignment == null) {
completeCache.put(itemId, false);
return false;
}
LessonSubmission submission = assignment.getSubmission(getCurrentUserId());
if (submission == null) {
completeCache.put(itemId, false);
return false;
}
int type = assignment.getTypeOfGrade();
if (!item.getSubrequirement()) {
completeCache.put(itemId, true);
return true;
} else if (submission.getGradeString() != null) {
// assume that assignments always use string grade. this may change
boolean ret = isAssignmentComplete(type, submission, item.getRequirementText());
completeCache.put(itemId, ret);
return ret;
} else {
completeCache.put(itemId, false);
return false;
}
} catch (Exception e) {
e.printStackTrace();
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.FORUM) {
try {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
User user = UserDirectoryService.getUser(getCurrentUserId());
LessonEntity forum = forumEntity.getEntity(item.getSakaiId());
if (forum == null)
return false;
// for the moment don't find grade. just see if they submitted
if (forum.getSubmissionCount(user.getId()) > 0) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} catch (Exception e) {
e.printStackTrace();
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.ASSESSMENT) {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
LessonEntity quiz = quizEntity.getEntity(item.getSakaiId());
if (quiz == null) {
completeCache.put(itemId, false);
return false;
}
User user = null;
try {
user = UserDirectoryService.getUser(getCurrentUserId());
} catch (Exception ignore) {
completeCache.put(itemId, false);
return false;
}
LessonSubmission submission = quiz.getSubmission(user.getId());
if (submission == null) {
completeCache.put(itemId, false);
return false;
} else if (!item.getSubrequirement()) {
// All that was required was that the user submit the test
completeCache.put(itemId, true);
return true;
} else {
Float grade = submission.getGrade();
if (grade >= Float.valueOf(item.getRequirementText())) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
}
} else if (item.getType() == SimplePageItem.TEXT || item.getType() == SimplePageItem.MULTIMEDIA) {
// In order to be considered "complete", these items
// only have to be viewed. If this code is reached,
// we know that that the page has already been viewed.
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
}
private boolean isAssignmentComplete(int type, LessonSubmission submission, String requirementString) {
String grade = submission.getGradeString();
if (type == SimplePageItem.ASSESSMENT) {
if (grade.equals("Pass")) {
return true;
} else {
return false;
}
} else if (type == SimplePageItem.TEXT) {
if (grade.equals("Checked")) {
return true;
} else {
return false;
}
} else if (type == SimplePageItem.PAGE) {
if (grade.equals("ungraded")) {
return false;
}
int requiredIndex = -1;
int currentIndex = -1;
for (int i = 0; i < GRADES.length; i++) {
if (GRADES[i].equals(requirementString)) {
requiredIndex = i;
}
if (GRADES[i].equals(grade)) {
currentIndex = i;
}
}
if (requiredIndex == -1 || currentIndex == -1) {
return false;
} else {
if (requiredIndex >= currentIndex) {
return true;
} else {
return false;
}
}
} else if (type == SimplePageItem.ASSIGNMENT) {
if (Float.valueOf(Integer.valueOf(grade) / 10) >= Float.valueOf(requirementString)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* @param itemId
* The ID of the page from the <b>items</b> table (not the page table).
* @return
*/
public boolean isPageComplete(long itemId) {
List<SimplePageItem> items = getItemsOnPage(Long.valueOf(findItem(itemId).getSakaiId()));
for (SimplePageItem item : items) {
if (!isItemComplete(item)) {
return false;
}
}
// All of them were complete.
return true;
}
// return list of pages needed for current page. This is the primary code
// used by ShowPageProducer to see whether the user is allowed to the page
// (given that they have read permission, of course)
// Note that the same page can occur
// multiple places, but we're passing the item, so we've got the right one
public List<String> pagesNeeded(SimplePageItem item) {
String currentPageId = Long.toString(getCurrentPageId());
List<String> needed = new ArrayList<String>();
if (!item.isPrerequisite()){
return needed;
}
// authorized or maybe user is gaming us, or maybe next page code
// sent them to something that isn't availbale.
// as an optimization chek haslogentry first. That will be true if
// they have been here before. Saves us the trouble of doing full
// access checking. Otherwise do a real check. That should only happen
// for next page in odd situations.
if (item.getPageId() > 0) {
if (!hasLogEntry(item.getId()) &&
!isItemAvailable(item, item.getPageId())) {
SimplePage parent = simplePageToolDao.getPage(item.getPageId());
if (parent != null)
needed.add(parent.getTitle());
else
needed.add("unknown page"); // not possible, it says
}
return needed;
}
// we've got a top level page.
// get dummy items for top level pages in site
List<SimplePageItem> items =
simplePageToolDao.findItemsInSite(getCurrentSite().getId());
// sorted by SQL
for (SimplePageItem i : items) {
if (i.getSakaiId().equals(currentPageId)) {
return needed; // reached current page. we're done
}
if (i.isRequired() && !isItemComplete(i))
needed.add(i.getName());
}
return needed;
}
public boolean isItemAvailable(SimplePageItem item) {
return isItemAvailable(item, getCurrentPageId());
}
public boolean isItemAvailable(SimplePageItem item, long pageId) {
if (item.isPrerequisite()) {
List<SimplePageItem> items = getItemsOnPage(pageId);
for (SimplePageItem i : items) {
if (i.getSequence() >= item.getSequence()) {
break;
} else if (i.isRequired()) {
if (!isItemComplete(i))
return false;
}
}
}
return true;
}
// weird variant that works even if current item doesn't have prereq.
public boolean wouldItemBeAvailable(SimplePageItem item, long pageId) {
List<SimplePageItem> items = getItemsOnPage(pageId);
for (SimplePageItem i : items) {
if (i.getSequence() >= item.getSequence()) {
break;
} else if (i.isRequired()) {
if (!isItemComplete(i))
return false;
}
}
return true;
}
public String getNameOfSakaiItem(SimplePageItem i) {
String SakaiId = i.getSakaiId();
if (SakaiId == null || SakaiId.equals(SimplePageItem.DUMMY))
return null;
if (i.getType() == SimplePageItem.ASSIGNMENT) {
LessonEntity assignment = assignmentEntity.getEntity(i.getSakaiId());
if (assignment == null)
return null;
return assignment.getTitle();
} else if (i.getType() == SimplePageItem.FORUM) {
LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
if (forum == null)
return null;
return forum.getTitle();
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
LessonEntity quiz = quizEntity.getEntity(i.getSakaiId());
if (quiz == null)
return null;
return quiz.getTitle();
} else
return null;
}
/*
* return 11-char youtube ID for a URL, or null if it doesn't match
* we store URLs as content objects, so we have to retrieve the object
* in order to check. The actual URL is stored as the contents
* of the entity
*/
public String getYoutubeKey(SimplePageItem i) {
String sakaiId = i.getSakaiId();
// find the resource
ContentResource resource = null;
try {
resource = contentHostingService.getResource(sakaiId);
} catch (Exception ignore) {
return null;
}
// make sure it's a URL
if (resource == null ||
!resource.getResourceType().equals("org.sakaiproject.content.types.urlResource") ||
!resource.getContentType().equals("text/url")) {
return null;
}
// get the actual URL
String URL = null;
try {
URL = new String(resource.getContent());
} catch (Exception ignore) {
return null;
}
if (URL == null) {
return null;
}
// see if it has a Youtube ID
if (URL.startsWith("http://www.youtube.com/") || URL.startsWith("http://youtube.com/")) {
Matcher match = YOUTUBE_PATTERN.matcher(URL);
if (match.find()) {
return match.group().substring(2);
}
}
// no
return null;
}
/**
* Meant to guarantee that the permissions are set correctly on an assessment for a user.
*
* @param item
* @param shouldHaveAccess
*/
public void checkItemPermissions(SimplePageItem item, boolean shouldHaveAccess) {
checkItemPermissions(item, shouldHaveAccess, true);
}
/**
*
* @param item
* @param shouldHaveAccess
* @param canRecurse
* Is it allowed to delete the row in the table for the group and recurse to try
* again. true for normal calls; false if called inside this code to avoid infinite loop
*/
private void checkItemPermissions(SimplePageItem item, boolean shouldHaveAccess, boolean canRecurse) {
if (SimplePageItem.DUMMY.equals(item.getSakaiId()))
return;
// for pages, presence of log entry is it
if (item.getType() == SimplePageItem.PAGE) {
Long itemId = item.getId();
if (getLogEntry(itemId) != null)
return; // already ok
// if no log entry, create a dummy entry
if (shouldHaveAccess) {
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
SimplePageLogEntry entry = simplePageToolDao.makeLogEntry(userId, itemId);
entry.setDummy(true);
saveItem(entry);
logCache.put((Long)itemId, entry);
}
return;
}
SimplePageGroup group = simplePageToolDao.findGroup(item.getSakaiId());
if (group == null) {
// For some reason, the group doesn't exist. Let's re-add it.
String groupId;
try {
groupId = GroupPermissionsService.makeGroup(getCurrentPage().getSiteId(), "Access: " + getNameOfSakaiItem(item));
saveItem(simplePageToolDao.makeGroup(item.getSakaiId(), groupId));
GroupPermissionsService.addControl(item.getSakaiId(), getCurrentPage().getSiteId(), groupId, item.getType());
} catch (IOException e) {
// If this fails, there's no way for us to check the permissions
// in the group. This shouldn't happen.
e.printStackTrace();
return;
}
group = simplePageToolDao.findGroup(item.getSakaiId());
if (group == null) {
// Something really weird is up.
log.warn("checkItemPermissions Can't create a group for " + item.getName() + " permissions.");
return;
}
}
boolean success = true;
String groupId = group.getGroupId();
try {
if (shouldHaveAccess) {
success = GroupPermissionsService.addCurrentUser(getCurrentPage().getSiteId(), getCurrentUserId(), groupId);
} else {
success = GroupPermissionsService.removeUser(getCurrentPage().getSiteId(), getCurrentUserId(), groupId);
}
} catch (Exception ex) {
ex.printStackTrace();
return;
}
// hmmm.... couldn't add or remove from group. Most likely the Sakai-level group
// doesn't exist, although our database entry says it was created. Presumably
// the user deleted the group for Site Info. Make very sure that's the cause,
// or we'll create a duplicate group. I've seen failures for other reasons, such
// as a weird permissions problem with the only maintain users trying to unjoin
// a group.
if (!success && canRecurse) {
try {
AuthzGroupService.getAuthzGroup(groupId);
// group exists, it was something else. Who knows what
return;
} catch (org.sakaiproject.authz.api.GroupNotDefinedException ee) {
} catch (Exception e) {
// some other failure from getAuthzGroup, shouldn't be possible
log.warn("checkItemPermissions unable to join or unjoin group " + groupId);
}
log.warn("checkItemPermissions: User seems to have deleted group " + groupId + ". We'll recreate it.");
// OK, group doesn't exist. When we recreate it, it's going to have a
// different groupId, so we have to back out of everything and reset it
try {
GroupPermissionsService.removeControl(item.getSakaiId(), getCurrentPage().getSiteId(), groupId, item.getType());
} catch (IOException e) {
// Shoudln't happen, but we'll continue anyway
e.printStackTrace();
}
simplePageToolDao.deleteItem(group);
// We've undone it; call ourselves again, since the code at the
// start will recreate the group
checkItemPermissions(item, shouldHaveAccess, false);
}
}
public void setYoutubeURL(String url) {
youtubeURL = url;
}
public void setYoutubeId(long id) {
youtubeId = id;
}
public void deleteYoutubeItem() {
simplePageToolDao.deleteItem(findItem(youtubeId));
}
public void setMmUrl(String url) {
mmUrl = url;
}
public void setMultipartMap(Map<String, MultipartFile> multipartMap) {
this.multipartMap = multipartMap;
}
public String getCollectionId(boolean urls) {
String siteId = getCurrentPage().getSiteId();
String collectionId = contentHostingService.getSiteCollection(siteId);
// folder we really want
String folder = collectionId + Validator.escapeResourceName(getPageTitle()) + "/";
if (urls)
folder = folder + "urls/";
// OK?
try {
contentHostingService.checkCollection(folder);
// OK, let's use it
return folder;
} catch (Exception ignore) {};
// no. create folders as needed
// if url subdir, need an extra level
if (urls) {
// try creating the root. if it exists this will fail. That's OK.
String root = collectionId + Validator.escapeResourceName(getPageTitle()) + "/";
try {
ContentCollectionEdit edit = contentHostingService.addCollection(root);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(getPageTitle()));
contentHostingService.commitCollection(edit);
// well, we got that far anyway
collectionId = root;
} catch (Exception ignore) {
};
}
// now try creating what we want
try {
ContentCollectionEdit edit = contentHostingService.addCollection(folder);
if (urls)
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, "urls");
else
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(getPageTitle()));
contentHostingService.commitCollection(edit);
return folder; // worked. use it
} catch (Exception ignore) {};
// didn't. do the best we can
return collectionId;
}
public boolean isHtml(SimplePageItem i) {
StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");
String extension = "";
while (token.hasMoreTokens()) {
extension = token.nextToken().toLowerCase();
}
// we are just starting to store the MIME type for resources now. So existing content
// won't have them.
String mimeType = i.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals("")))
mimeType = null;
if (mimeType != null && (mimeType.equals("text/html") || mimeType.equals("application/xhtml+xml"))
|| mimeType == null && (extension.equals("html") || extension.equals("htm"))) {
return true;
}
return false;
}
public static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = 100;
// called by dialog to add inline multimedia item, or update existing
// item if itemid is specified
public void addMultimedia() {
if (!itemOk(itemId))
return;
if (!canEditPage())
return;
String name = null;
String sakaiId = null;
String mimeType = null;
MultipartFile file = null;
if (multipartMap.size() > 0) {
// user specified a file, create it
file = multipartMap.values().iterator().next();
if (file.isEmpty())
file = null;
}
if (file != null) {
String collectionId = getCollectionId(false);
// user specified a file, create it
name = file.getOriginalFilename();
if (name == null || name.length() == 0)
name = file.getName();
int i = name.lastIndexOf("/");
if (i >= 0)
name = name.substring(i+1);
String base = name;
String extension = "";
i = name.lastIndexOf(".");
if (i > 0) {
base = name.substring(0, i);
extension = name.substring(i+1);
}
mimeType = file.getContentType();
try {
ContentResourceEdit res = contentHostingService.addResource(collectionId,
Validator.escapeResourceName(base),
Validator.escapeResourceName(extension),
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType(mimeType);
res.setContent(file.getInputStream());
try {
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
// there's a bug in the kernel that can cause
// a null pointer if it can't determine the encoding
// type. Since we want this code to work on old
// systems, work around it.
} catch (java.lang.NullPointerException e) {
setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror"));
}
sakaiId = res.getId();
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
return;
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 1 " + e);
return;
};
} else if (mmUrl != null && !mmUrl.trim().equals("")) {
// user specified a URL, create the item
String url = mmUrl.trim();
if (!url.startsWith("http:") &&
!url.startsWith("https:")) {
if (!url.startsWith("//"))
url = "//" + url;
url = "http:" + url;
}
name = url;
String base = url;
String extension = "";
int i = url.lastIndexOf("/");
if (i < 0) i = 0;
i = url.lastIndexOf(".", i);
if (i > 0) {
extension = url.substring(i);
base = url.substring(0,i);
}
String collectionId = getCollectionId(true);
try {
// urls aren't something people normally think of as resources. Let's hide them
ContentResourceEdit res = contentHostingService.addResource(collectionId,
Validator.escapeResourceName(base),
Validator.escapeResourceName(extension),
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
res.setContent(url.getBytes());
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
sakaiId = res.getId();
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
return;
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 2 " + e);
return;
};
// connect to url and get mime type
mimeType = getTypeOfUrl(url);
} else
// nothing to do
return;
// itemId tells us whether it's an existing item
// isMultimedia tells us whether resource or multimedia
// sameWindow is only passed for existing items of type HTML/XHTML
// for new items it should be set true for HTML/XTML, false otherwise
// for existing items it should be set to the passed value for HTML/XMTL, false otherwise
// it is ignored for isMultimedia, as those are always displayed inline in the current page
SimplePageItem item = null;
if (itemId == -1 && isMultimedia) {
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
item = simplePageToolDao.makeItem(getCurrentPageId(), seq, SimplePageItem.MULTIMEDIA, sakaiId, name);
} else if (itemId == -1) {
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
item = simplePageToolDao.makeItem(getCurrentPageId(), seq, SimplePageItem.RESOURCE, sakaiId, name);
} else {
item = findItem(itemId);
if (item == null)
return;
item.setSakaiId(sakaiId);
item.setName(name);
}
if (mimeType != null) {
item.setHtml(mimeType);
} else {
item.setHtml(null);
}
// if this is an existing item and a resource, leave it alone
// otherwise initialize to false
if (isMultimedia || itemId == -1)
item.setSameWindow(false);
clearImageSize(item);
try {
if (itemId == -1)
saveItem(item);
else
update(item);
} catch (Exception e) {
// saveItem and update produce the errors
}
}
public boolean deleteRecursive(File path) throws FileNotFoundException{
if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath());
boolean ret = true;
if (path.isDirectory()){
for (File f : path.listFiles()){
ret = ret && deleteRecursive(f);
}
}
return ret && path.delete();
}
public void importCc() {
System.out.println("importCc");
if (!canEditPage())
return;
MultipartFile file = null;
if (multipartMap.size() > 0) {
// user specified a file, create it
file = multipartMap.values().iterator().next();
if (file.isEmpty())
file = null;
}
if (file != null) {
File cc = null;
File root = null;
try {
cc = File.createTempFile("ccloader", "file");
root = File.createTempFile("ccloader", "root");
if (root.exists())
root.delete();
root.mkdir();
BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cc));
byte[] buffer = new byte[8096];
int n = 0;
while ((n = bis.read(buffer, 0, 8096)) >= 0) {
if (n > 0)
bos.write(buffer, 0, n);
}
bis.close();
bos.close();
CartridgeLoader cartridgeLoader = ZipLoader.getUtilities(cc, root.getCanonicalPath());
Parser parser = Parser.createCartridgeParser(cartridgeLoader);
LessonEntity quizobject = null;
for (LessonEntity q = quizEntity; q != null; q = q.getNextEntity()) {
if (q.getToolId().equals(quiztool))
quizobject = q;
}
LessonEntity topicobject = null;
for (LessonEntity q = forumEntity; q != null; q = q.getNextEntity()) {
if (q.getToolId().equals(topictool))
topicobject = q;
}
parser.parse(new PrintHandler(this, cartridgeLoader, simplePageToolDao, quizobject, topicobject));
} catch (Exception e) {
System.out.println("exception in importcc " + e);
e.printStackTrace();
} finally {
if (cc != null)
try {
deleteRecursive(cc);
} catch (Exception e){
System.out.println("Unable to delete temp file " + cc);
}
try {
deleteRecursive(root);
} catch (Exception e){
System.out.println("Unable to delete temp file " + cc);
}
}
}
}
// called by edit dialog to update parameters of a Youtube item
public void updateYoutube() {
if (!itemOk(youtubeId))
return;
if (!canEditPage())
return;
SimplePageItem item = findItem(youtubeId);
// find the new key, if the new thing is a legit youtube url
Matcher match = YOUTUBE_PATTERN.matcher(youtubeURL);
String key = null;
if (match.find()) {
key = match.group().substring(2);
}
// oldkey had better work, since the youtube edit woudln't
// be displayed if it wasn't recognized
String oldkey = getYoutubeKey(item);
// if there's a new youtube URL, and it's different from
// the old one, update the URL if they are different
if (key != null && !key.equals(oldkey)) {
String url = "http://www.youtube.com/watch#!v=" + key;
String siteId = getCurrentPage().getSiteId();
String collectionId = getCollectionId(true);
try {
ContentResourceEdit res = contentHostingService.addResource(collectionId,Validator.escapeResourceName("Youtube video " + key),Validator.escapeResourceName("swf"),MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
res.setContent(url.getBytes());
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
item.setSakaiId(res.getId());
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 3 " + e);
};
}
// even if there's some oddity with URLs, we do these updates
item.setHeight(height);
item.setWidth(width);
item.setDescription(description);
update(item);
}
/**
* Adds or removes the requirement to have site.upd in order to see a page
* i.e. hide or unhide a page
* @param pageId
* The Id of the Page
* @param visible
* @return true for success, false for failure
* @throws IdUnusedException
* , PermissionException
*/
private boolean pageVisibilityHelper(Site site, String pageId, boolean visible) throws IdUnusedException, PermissionException {
SitePage page = site.getPage(pageId);
List<ToolConfiguration> tools = page.getTools();
Iterator<ToolConfiguration> iterator = tools.iterator();
// If all the tools on a page require site.upd then only users with site.upd will see
// the page in the site nav of Charon... not sure about the other Sakai portals floating
// about
while (iterator.hasNext()) {
ToolConfiguration placement = iterator.next();
Properties roleConfig = placement.getPlacementConfig();
String roleList = roleConfig.getProperty("functions.require");
boolean saveChanges = false;
if (roleList == null) {
roleList = "";
}
if (!(roleList.indexOf(SITE_UPD) > -1) && !visible) {
if (roleList.length() > 0) {
roleList += ",";
}
roleList += SITE_UPD;
saveChanges = true;
} else if (visible) {
roleList = roleList.replaceAll("," + SITE_UPD, "");
roleList = roleList.replaceAll(SITE_UPD, "");
saveChanges = true;
}
if (saveChanges) {
roleConfig.setProperty("functions.require", roleList);
placement.save();
siteService.save(site);
}
}
return true;
}
// used by edit dialog to update properties of a multimedia object
public void updateMovie() {
if (!itemOk(itemId))
return;
if (!canEditPage())
return;
SimplePageItem item = findItem(itemId);
item.setHeight(height);
item.setWidth(width);
item.setDescription(description);
item.setHtml(mimetype);
update(item);
}
} | lessonbuilder/tool/src/java/org/sakaiproject/lessonbuildertool/tool/beans/SimplePageBean.java | /**********************************************************************************
* $URL: $
* $Id: $
***********************************************************************************
*
* Author: Eric Jeney, [email protected]
* The original author was Joshua Ryan [email protected]. However little of that code is actually left
*
* Copyright (c) 2010 Rutgers, the State University of New Jersey
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.lessonbuildertool.tool.beans;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.AbstractList;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.lessonbuildertool.service.LessonEntity;
import org.sakaiproject.lessonbuildertool.service.LessonSubmission;
import org.sakaiproject.lessonbuildertool.service.GradebookIfc;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.lessonbuildertool.SimplePage;
import org.sakaiproject.lessonbuildertool.SimplePageGroup;
import org.sakaiproject.lessonbuildertool.SimplePageItem;
import org.sakaiproject.lessonbuildertool.SimplePageLogEntry;
import org.sakaiproject.lessonbuildertool.tool.view.FilePickerViewParameters;
import org.sakaiproject.lessonbuildertool.model.SimplePageToolDao;
import org.sakaiproject.lessonbuildertool.service.GroupPermissionsService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAssessmentData;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.Validator;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.springframework.web.multipart.MultipartFile;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIInternalLink;
import org.sakaiproject.lessonbuildertool.tool.view.GeneralViewParameters;
import org.sakaiproject.lessonbuildertool.tool.producers.ShowPageProducer;
import org.sakaiproject.lessonbuildertool.tool.producers.ShowItemProducer;
import org.sakaiproject.lessonbuildertool.cc.CartridgeLoader;
import org.sakaiproject.lessonbuildertool.cc.ZipLoader;
import org.sakaiproject.lessonbuildertool.cc.Parser;
import org.sakaiproject.lessonbuildertool.cc.PrintHandler;
/**
* Backing bean for Simple pages
*
* @author Eric Jeney <[email protected]>
* @author Joshua Ryan [email protected] alt^I
*/
// This bean has two related but somewhat separate uses:
// 1) It keeps common data for the producers and other code. In that use the lifetime of the bean is while
// generating a single page. The bean has common application logic. The producers are pretty much just UI.
// The DAO is low-level data access. This is everything else. The producers call this bean, and not the
// DAO directly. This layer sticks caches on top of the data access, and provides more complex logic. Security
// is primarily in the DAO, but the DAO only checks permissions. We have to make sure we only acccess pages
// and items in our site
// 2) It is used by RSF to access data. Normally the bean is associated with a specific page. However the
// UI often has to update attributes of a specific item. For that use, there are some item-specific variables
// in the bean. They are only meaningful during item operations, when itemId will show which item is involved.
// While the bean is used by all the producers, the caching was designed specifically for ShowPageProducer.
// That's because it is used a lot more often than the others. ShowPageProducer should do all data acess through
// the methods here that cache. There is also caching by hibernate. However this code is cheaper, partly because
// it doesn't have to do synchronization (since it applies just to processing one transaction).
public class SimplePageBean {
private static Log log = LogFactory.getLog(SimplePageBean.class);
public enum Status {
NOT_REQUIRED, REQUIRED, DISABLED, COMPLETED, FAILED
}
public static final Pattern YOUTUBE_PATTERN = Pattern.compile("v[=/_][\\w-]{11}");
public static final String GRADES[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "F" };
public static final String FILTERHTML = "lessonbuilder.filterhtml";
public static final String LESSONBUILDER_ITEMID = "lessonbuilder.itemid";
public static final String LESSONBUILDER_PATH = "lessonbuilder.path";
public static final String LESSONBUILDER_BACKPATH = "lessonbuilder.backpath";
public static final String LESSONBUILDER_ID = "sakai.lessonbuildertool";
private static String PAGE = "simplepage.page";
private static String SITE_UPD = "site.upd";
private String contents = null;
private String pageTitle = null;
private String newPageTitle = null;
private String subpageTitle = null;
private boolean subpageNext = false;
private boolean subpageButton = false;
private List<Long> currentPath = null;
private Set<Long>allowedPages = null;
private Site currentSite = null; // cache, can be null; used by getCurrentSite
private boolean filterHtml = ServerConfigurationService.getBoolean(FILTERHTML, false);
public String selectedAssignment = null;
// generic entity stuff. selectedEntity is the string
// coming from the picker. We'll use the same variable for any entity type
public String selectedEntity = null;
public String[] selectedEntities = new String[] {};
public String selectedQuiz = null;
private SimplePage currentPage;
private Long currentPageId = null;
private Long currentPageItemId = null;
private String currentUserId = null;
private long previousPageId = -1;
// Item-specific variables. These are set by setters which are called
// by the various edit dialogs. So they're basically inputs to the
// methods used to make changes to items. The way it works is that
// when the user submits the form, RSF takes all the form variables,
// calls setters for each field, and then calls the method specified
// by the form. The setters set these variables
public Long itemId = null;
public boolean isMultimedia = false;
private String linkUrl;
private String height, width;
private String description;
private String name;
private boolean required;
private boolean subrequirement;
private boolean prerequisite;
private boolean newWindow;
private String dropDown;
private String points;
private String mimetype;
private String numberOfPages;
private boolean copyPage;
private String alt = null;
private String order = null;
private String youtubeURL;
private String mmUrl;
private long youtubeId;
private boolean hidePage;
private Date releaseDate;
private boolean hasReleaseDate;
private String redirectSendingPage = null;
private String redirectViewId = null;
private String quiztool = null;
private String topictool = null;
public Map<String, MultipartFile> multipartMap;
// Caches
// The following caches are used only during a single display of the page. I believe they
// are so transient that we don't have to worry about synchronizing them or keeping them up to date.
// Because the producer code tends to deal with items and even item ID's, it doesn't keep objects such
// as Assignment or PublishedAssessment around. It calls functions here to worry about those. If we
// don't cache, we'll be doing database lookups a lot. The worst is the code to see whether an item
// is available. Because it checks all items above, we'd end up order N**2 in the number of items on the
// page in database queries. It doesn't appear that assignments and assessments do any caching of their
// own, but hibernate as we use it does.
// Normal code shouldn't use the caches directly, but should call something like getAssignment here,
// which checks the cache and if necessary calls the real getAssignment. I've chosen to do caching on
// this level, and let the DAO be actual database access. I've really only optimized what is used by
// ShowPageProducer, as that is used every time a page is shown. Things used when you add or change
// an item aren't as critical.
// If anyone is doing serious work on the code, I recommend creating an Item class that encapsulates
// all the stuff associated with items. Then the producer would manipulate items. Thus the things in
// these caches would be held in the Items.
private Map<Long, SimplePageItem> itemCache = new HashMap<Long, SimplePageItem> ();
private Map<Long, List<SimplePageItem>> itemsCache = new HashMap<Long, List<SimplePageItem>> ();
private Map<Long, SimplePageLogEntry> logCache = new HashMap<Long, SimplePageLogEntry>();
private Map<Long, Boolean> completeCache = new HashMap<Long, Boolean>();
public static class PathEntry {
public Long pageId;
public Long pageItemId;
public String title;
}
public static class UrlItem {
public String Url;
public String label;
public UrlItem(String Url, String label) {
this.Url = Url;
this.label = label;
}
}
// Image types
private static ArrayList<String> imageTypes;
static {
imageTypes = new ArrayList<String>();
imageTypes.add("bmp");
imageTypes.add("gif");
imageTypes.add("icns");
imageTypes.add("ico");
imageTypes.add("jpg");
imageTypes.add("jpeg");
imageTypes.add("png");
imageTypes.add("tiff");
imageTypes.add("tif");
}
// Spring Injection
private SessionManager sessionManager;
public void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
private ContentHostingService contentHostingService;
public void setContentHostingService(ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
private GradebookIfc gradebookIfc = null;
public void setGradebookIfc(GradebookIfc g) {
gradebookIfc = g;
}
private LessonEntity forumEntity = null;
public void setForumEntity(Object e) {
forumEntity = (LessonEntity)e;
}
private LessonEntity quizEntity = null;
public void setQuizEntity(Object e) {
quizEntity = (LessonEntity)e;
}
private LessonEntity assignmentEntity = null;
public void setAssignmentEntity(Object e) {
assignmentEntity = (LessonEntity)e;
}
private ToolManager toolManager;
private SecurityService securityService;
private SiteService siteService;
private SimplePageToolDao simplePageToolDao;
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator x) {
messageLocator = x;
}
public MessageLocator getMessageLocator() {
return messageLocator;
}
// End Injection
public SimplePageItem findItem(long itId) {
Long itemId = itId;
SimplePageItem ret = itemCache.get(itemId);
if (ret != null)
return ret;
ret = simplePageToolDao.findItem(itemId);
if (ret != null)
itemCache.put(itemId, ret);
return ret;
}
public String errMessage() {
ToolSession toolSession = sessionManager.getCurrentToolSession();
String error = (String)toolSession.getAttribute("lessonbuilder.error");
if (error != null)
toolSession.removeAttribute("lessonbuilder.error");
return error;
}
public void setErrMessage(String s) {
ToolSession toolSession = sessionManager.getCurrentToolSession();
toolSession.setAttribute("lessonbuilder.error", s);
}
public void setErrKey(String key, String text ) {
ToolSession toolSession = sessionManager.getCurrentToolSession();
toolSession.setAttribute("lessonbuilder.error", messageLocator.getMessage(key).replace("{}", text));
}
// a lot of these are setters and getters used for the form process, as
// described above
public void setAlt(String alt) {
this.alt = alt;
}
public String getDescription() {
if (itemId != null && itemId != -1) {
return findItem(itemId).getDescription();
} else {
return null;
}
}
public void setDescription(String description) {
this.description = description;
}
public void setHidePage(boolean hide) {
hidePage = hide;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setHasReleaseDate(boolean hasReleaseDate) {
this.hasReleaseDate = hasReleaseDate;
}
// gets called for non-checked boxes also, but q will be null
public void setQuiztool(String q) {
if (q != null)
quiztool = q;
}
public void setTopictool(String q) {
if (q != null)
topictool = q;
}
public String getName() {
if (itemId != null && itemId != -1) {
return findItem(itemId).getName();
} else {
return null;
}
}
public void setName(String name) {
this.name = name;
}
public void setRequired(boolean required) {
this.required = required;
}
public void setSubrequirement(boolean subrequirement) {
this.subrequirement = subrequirement;
}
public void setPrerequisite(boolean prerequisite) {
this.prerequisite = prerequisite;
}
public void setNewWindow(boolean newWindow) {
this.newWindow = newWindow;
}
public void setDropDown(String dropDown) {
this.dropDown = dropDown;
}
public void setPoints(String points) {
this.points = points;
}
public void setMimetype(String mimetype) {
if (mimetype != null)
mimetype = mimetype.toLowerCase().trim();
this.mimetype = mimetype;
}
public String getPageTitle() {
return getCurrentPage().getTitle();
}
public void setPageTitle(String title) {
pageTitle = title;
}
public void setNewPageTitle(String title) {
newPageTitle = title;
}
public void setNumberOfPages(String n) {
numberOfPages = n;
}
public void setCopyPage(boolean c) {
this.copyPage = c;
}
public String getContents() {
return (itemId != null && itemId != -1 ? findItem(itemId).getHtml() : "");
}
public void setContents(String contents) {
this.contents = contents;
}
public void setItemId(Long id) {
itemId = id;
}
public Long getItemId() {
return itemId;
}
public void setMultimedia(boolean isMm) {
isMultimedia = isMm;
}
// hibernate interposes something between us and saveItem, and that proxy gets an
// error after saveItem does. Thus we never see any value that saveItem might
// return. Hence we pass saveItem a list to which it adds the error message. If
// there is a mesasge from saveItem take precedence over the message we detect here,
// since it's the root cause.
public boolean saveItem(Object i) {
String err = null;
List<String>elist = new ArrayList<String>();
try {
simplePageToolDao.saveItem(i, elist, messageLocator.getMessage("simplepage.nowrite"));
} catch (Throwable t) {
// this is probably a bogus error, but find its root cause
while (t.getCause() != null) {
t = t.getCause();
}
err = t.toString();
}
// if we got an error from saveItem use it instead
if (elist.size() > 0)
err = elist.get(0);
if (err != null) {
setErrMessage(messageLocator.getMessage("simplepage.savefailed") + err);
return false;
}
return true;
}
// see notes for saveupdate
boolean update(Object i) {
String err = null;
List<String>elist = new ArrayList<String>();
try {
simplePageToolDao.update(i, elist, messageLocator.getMessage("simplepage.nowrite"));
} catch (Throwable t) {
// this is probably a bogus error, but find its root cause
while (t.getCause() != null) {
t = t.getCause();
}
err = t.toString();
}
// if we got an error from saveItem use it instead
if (elist.size() > 0)
err = elist.get(0);
if (err != null) {
setErrMessage(messageLocator.getMessage("simplepage.savefailed") + err);
return false;
}
return true;
}
// The permissions model assumes that all code operates on the current
// page. When the current page is set, the set code verifies that the
// page is in the current site. However when operatig on items, we
// have to make sure they are in the current page, or we could end up
// hacking on an item in a completely different site. This method checks
// that an item is OK to hack on, given the current page.
private boolean itemOk(Long itemId) {
// not specified, we'll add a new one
if (itemId == null || itemId == -1)
return true;
SimplePageItem item = findItem(itemId);
if (item.getPageId() != getCurrentPageId()) {
return false;
}
return true;
}
// called by the producer that uses FCK to update a text block
public String submit() {
String rv = "success";
if (!itemOk(itemId))
return "permission-failed";
if (canEditPage()) {
Placement placement = toolManager.getCurrentPlacement();
StringBuilder error = new StringBuilder();
// there's an issue with HTML security in the Sakai community.
// a lot of people feel users shouldn't be able to add javascirpt, etc
// to their HTML. I thik enforcing that makes Sakai less than useful.
// So check config options to see whether to do that check
String html = contents;
if (filterHtml && ! "false".equals(placement.getPlacementConfig().getProperty("filterHtml")) ||
"true".equals(placement.getPlacementConfig().getProperty("filterHtml"))) {
html = FormattedText.processFormattedText(contents, error);
} else {
html = FormattedText.processHtmlDocument(contents, error);
}
if (html != null) {
SimplePageItem item;
// itemid -1 means we're adding a new item to the page,
// specified itemid means we're updating an existing one
if (itemId != null && itemId != -1) {
item = findItem(itemId);
} else {
item = appendItem("", "", SimplePageItem.TEXT);
}
item.setHtml(html);
update(item);
} else {
rv = "cancel";
}
placement.save();
} else {
rv = "cancel";
}
return rv;
}
public String cancel() {
return "cancel";
}
public String processMultimedia() {
return processResource(SimplePageItem.MULTIMEDIA);
}
public String processResource() {
return processResource(SimplePageItem.RESOURCE);
}
// get mime type for a URL. connect to the server hosting
// it and ask them. Sorry, but I don't think there's a better way
public String getTypeOfUrl(String url) {
String mimeType = null;
// try to find the mime type of the remote resource
// this is only likely to be a problem if someone is pointing to
// a url within Sakai. We think in realistic cases those that are
// files will be handled as files, so anything that comes where
// will be HTML. That's the default if this fails.
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
// generate cookie based on code in RequestFilter.java
//String suffix = System.getProperty("sakai.serverId");
//if (suffix == null || suffix.equals(""))
// suffix = "sakai";
//Session s = sessionManager.getCurrentSession();
//conn.setRequestProperty("Cookie", "JSESSIONID=" + s.getId() + "." + suffix);
conn.connect();
String t = conn.getContentType();
if (t != null && !t.equals("")) {
int i = t.indexOf(";");
if (i >= 0)
t = t.substring(0, i);
t = t.trim();
mimeType = t;
}
conn.getInputStream().close();
} catch (Exception e) {log.error("getTypeOfUrl connection error " + e);};
return mimeType;
}
// return call from the file picker, used by add resource
// the picker communicates with us by session variables
public String processResource(int type) {
if (!canEditPage())
return "permission-failed";
ToolSession toolSession = sessionManager.getCurrentToolSession();
List refs = null;
String id = null;
String name = null;
String mimeType = null;
if (toolSession.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
refs = (List) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if (refs == null || refs.size() != 1) {
return "no-reference";
}
Reference ref = (Reference) refs.get(0);
id = ref.getId();
name = ref.getProperties().getProperty("DAV:displayname");
// URLs are complex. There are two issues:
// 1) The stupid helper treats a URL as a file upload. Have to make it a URL type.
// I suspect we're intended to upload a file from the URL, but I don't think
// any part of Sakai actually does that. So we reset Sakai's file type to URL
// 2) Lesson builder needs to know the mime type, to know how to set up the
// OBJECT or IFRAME. We send that out of band in the "html" field of the
// lesson builder item entry. I see no way to do that other than to talk
// to the server at the other end and see what MIME type it claims.
mimeType = ref.getProperties().getProperty("DAV:getcontenttype");
if (mimeType.equals("text/url")) {
mimeType = null; // use default rules if we can't find it
String url = null;
// part 1, fix up the type fields
try {
ContentResourceEdit res = contentHostingService.editResource(id);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
url = new String(res.getContent());
contentHostingService.commitResource(res);
} catch (Exception ignore) {
return "no-reference";
}
// part 2, find the actual data type.
if (url != null)
mimeType = getTypeOfUrl(url);
}
} else {
return "cancel";
}
try {
contentHostingService.checkResource(id);
} catch (PermissionException e) {
return "permission-exception";
} catch (IdUnusedException e) {
// Typically Means Cancel
return "cancel";
} catch (TypeException e) {
return "type-exception";
}
Long itemId = (Long)toolSession.getAttribute(LESSONBUILDER_ITEMID);
if (!itemOk(itemId))
return "permission-failed";
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
toolSession.removeAttribute(LESSONBUILDER_ITEMID);
String[] split = id.split("/");
SimplePageItem i;
if (itemId != null && itemId != -1) {
i = findItem(itemId);
i.setSakaiId(id);
if (mimeType != null)
i.setHtml(mimeType);
i.setName(name != null ? name : split[split.length - 1]);
clearImageSize(i);
} else {
i = appendItem(id, (name != null ? name : split[split.length - 1]), type);
if (mimeType != null) {
i.setHtml(mimeType);
}
}
i.setSameWindow(false);
update(i);
return "importing";
}
// set default for image size for new objects
private void clearImageSize(SimplePageItem i) {
// defaults to a fixed width and height, appropriate for some things, but for an
// image, leave it blank, since browser will then use the native size
if (i.getType() == SimplePageItem.MULTIMEDIA) {
if (isImageType(i)) {
i.setHeight("");
i.setWidth("");
}
}
}
// main code for adding a new item to a page
private SimplePageItem appendItem(String id, String name, int type) {
// add at the end of the page
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
SimplePageItem i = simplePageToolDao.makeItem(getCurrentPageId(), seq, type, id, name);
// defaults to a fixed width and height, appropriate for some things, but for an
// image, leave it blank, since browser will then use the native size
clearImageSize(i);
saveItem(i);
return i;
}
/**
* User can edit if he has site.upd or simplepage.upd. These do database queries, so
* try to save the results, rather than calling them many times on a page.
* @return
*/
public boolean canEditPage() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock(SimplePage.PERMISSION_LESSONBUILDER_UPDATE, ref);
}
public boolean canReadPage() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock(SimplePage.PERMISSION_LESSONBUILDER_READ, ref);
}
public boolean canEditSite() {
String ref = "/site/" + toolManager.getCurrentPlacement().getContext();
return securityService.unlock("site.upd", ref);
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setSecurityService(SecurityService service) {
securityService = service;
}
public void setSiteService(SiteService service) {
siteService = service;
}
public void setSimplePageToolDao(Object dao) {
simplePageToolDao = (SimplePageToolDao) dao;
}
public List<SimplePageItem> getItemsOnPage(long pageid) {
List<SimplePageItem>items = itemsCache.get(pageid);
if (items != null)
return items;
items = simplePageToolDao.findItemsOnPage(pageid);
for (SimplePageItem item: items) {
itemCache.put(item.getId(), item);
}
itemsCache.put(pageid, items);
return items;
}
/**
* Removes the item from the page, doesn't actually delete it.
*
* @return
*/
public String deleteItem() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
SimplePageItem i = findItem(itemId);
int seq = i.getSequence();
boolean b = false;
// if access controlled, clear it before deleting item
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
}
b = simplePageToolDao.deleteItem(i);
if (b) {
List<SimplePageItem> list = getItemsOnPage(getCurrentPageId());
for (SimplePageItem item : list) {
if (item.getSequence() > seq) {
item.setSequence(item.getSequence() - 1);
update(item);
}
}
return "successDelete";
} else {
log.warn("deleteItem error deleting Item: " + itemId);
return "failure";
}
}
// not clear whether it's worth caching this. The first time it's called for a site
// the pages are fetched. Beyond that it's a linear search of pages that are in memory
// ids are sakai.assignment.grades, sakai.samigo, sakai.mneme, sakai.forums, sakai.jforum.tool
public String getCurrentTool(String commonToolId) {
Site site = getCurrentSite();
ToolConfiguration tool = site.getToolForCommonId(commonToolId);
if (tool == null)
return null;
return tool.getId();
}
public String getCurrentToolTitle(String commonToolId) {
Site site = getCurrentSite();
ToolConfiguration tool = site.getToolForCommonId(commonToolId);
if (tool == null)
return null;
return tool.getTitle();
}
private Site getCurrentSite() {
if (currentSite != null) // cached value
return currentSite;
try {
currentSite = siteService.getSite(toolManager.getCurrentPlacement().getContext());
} catch (Exception impossible) {
impossible.printStackTrace();
}
return currentSite;
}
// find page to show in next link
// If the current page is a LB page, and it has a single "next" link on it, use that
// If the current page is a LB page, and it has more than one
// "next" link on it, show no next. If there's more than one
// next, this is probably a page with a branching queston, in
// which case there really isn't a single next.
// If the current page s a LB page, and it is not finished (i.e.
// there are required items not done), there is no next, or next
// is grayed out.
// Otherwise look at the page above in the breadcrumbs. If the
// next item on the page is not an inline item, and the item is
// available, next should be the next item on that page. (If
// it's an inline item we need to go back to the page above so
// they can see the inline item next.)
// If the current page is something like a test, there is an
// issue. What if the next item is not available when the page is
// displayed, because it requires that you get a passing score on
// the current test? For the moment, if the current item is required
// but the next is not available, show the link but test it when it's
// clicked.
// TODO: showpage and showitem, implement next. Should not pass a
// path argument. That gives next. If there's a pop we do it.
// in showitem, check if it's available, if not, show an error
// with a link to the page above.
// return: new item on same level, null if none, the item arg if need to go up a level
// java really needs to be able to return more than one thing, item == item is being
// used as a flag to return up a level
public SimplePageItem findNextPage(SimplePageItem item) {
if (item.getType() == SimplePageItem.PAGE) {
Long pageId = Long.valueOf(item.getSakaiId());
List<SimplePageItem> items = getItemsOnPage(pageId);
int nexts = 0;
SimplePageItem nextPage = null;
for (SimplePageItem i: items) {
if (i.getType() == SimplePageItem.PAGE && i.getNextPage()) {
nextPage = i;
nexts++;
}
}
// if next, use it; no next if not ready
if (nexts == 1) {
if (isItemAvailable(nextPage, pageId))
return nextPage;
return null;
}
// more than one, presumably you're intended to pick one of them, and
// there is no generic next
if (nexts > 1) {
return null;
}
// here for a page with no explicit next. Treat like any other item
// except that we need to compute pathop. Page must be complete or we
// would have returned null.
}
// see if there's an actual next we can go to, otherwise calling page
SimplePageItem nextItem = simplePageToolDao.findNextItemOnPage(item.getPageId(), item.getSequence());
boolean available = false;
if (nextItem != null) {
int itemType = nextItem.getType();
if (itemType == SimplePageItem.ASSIGNMENT ||
itemType == SimplePageItem.ASSESSMENT ||
itemType == SimplePageItem.FORUM ||
itemType == SimplePageItem.PAGE ||
itemType == SimplePageItem.RESOURCE && nextItem.isSameWindow()) {
// it's easy if the next item is available. If it's not, then
// we need to see if everything other than this item is done and
// this one is required. In that case the issue must be that this
// one isn't finished yet. Let's assume the user is going to finish
// this one. We'll verify that when he actually does the next;
if (isItemAvailable(nextItem, item.getPageId()) ||
item.isRequired() && wouldItemBeAvailable(item, item.getPageId()))
return nextItem;
}
}
// otherwise return to calling page
return item; // special flag
}
// corresponding code for outputting the link
// perhaps I should adjust the definition of path so that normal items show on it and not just pages
// but at the moment path is just the pages. So when we're in a normal item, it doesn't show.
// that means that as we do Next between items and pages, when we go to a page it gets pushed
// on and when we go from a page to an item, the page has to be popped off.
public void addNextLink(UIContainer tofill, SimplePageItem item) {
SimplePageItem nextItem = findNextPage(item);
if (nextItem == item) { // that we need to go up a level
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
int top;
if (path == null)
top = -1;
else
top = path.size()-1;
// if we're on a page, have to pop it off first
// for a normal item the end of the path already is the page above
if (item.getType() == SimplePageItem.PAGE)
top--;
if (top >= 0) {
PathEntry e = path.get(top);
GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
view.setSendingPage(e.pageId);
view.setItemId(e.pageItemId);
view.setPath(Integer.toString(top));
UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
}
} else if (nextItem != null) {
GeneralViewParameters view = new GeneralViewParameters();
int itemType = nextItem.getType();
if (itemType == SimplePageItem.PAGE) {
view.setSendingPage(Long.valueOf(nextItem.getSakaiId()));
view.viewID = ShowPageProducer.VIEW_ID;
if (item.getType() == SimplePageItem.PAGE)
view.setPath("next"); // page to page, just a next
else
view.setPath("push"); // item to page, have to push the page
} else if (itemType == SimplePageItem.RESOURCE) { /// must be a same page resource
view.setSendingPage(Long.valueOf(item.getPageId()));
// to the check. We need the check to set access control appropriately
// if the user has passed.
if (!isItemAvailable(nextItem, nextItem.getPageId()))
view.setRecheck("true");
view.setSource(nextItem.getItemURL());
view.viewID = ShowItemProducer.VIEW_ID;
} else {
view.setSendingPage(Long.valueOf(item.getPageId()));
LessonEntity lessonEntity = null;
switch (nextItem.getType()) {
case SimplePageItem.ASSIGNMENT:
lessonEntity = assignmentEntity.getEntity(nextItem.getSakaiId()); break;
case SimplePageItem.ASSESSMENT:
view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
lessonEntity = quizEntity.getEntity(nextItem.getSakaiId()); break;
case SimplePageItem.FORUM:
lessonEntity = forumEntity.getEntity(nextItem.getSakaiId()); break;
}
// normally we won't send someone to an item that
// isn't available. But if the current item is a test, etc, we can't
// know whether the user will pass it, so we have to ask ShowItem to
// to the check. We need the check to set access control appropriately
// if the user has passed.
if (!isItemAvailable(nextItem, nextItem.getPageId()))
view.setRecheck("true");
view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
if (item.getType() == SimplePageItem.PAGE)
view.setPath("pop"); // now on a have, have to pop it off
view.viewID = ShowItemProducer.VIEW_ID;
}
view.setItemId(nextItem.getId());
view.setBackPath("push");
UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
}
}
// Because of the existence of chains of "next" pages, there's no static approach that will find
// back links. Thus we keep track of the actual path the user has followed. However we have to
// prune both path and back path when we return to an item that's already on them to avoid
// loops of various kinds.
public void addPrevLink(UIContainer tofill, SimplePageItem item) {
List<PathEntry> backPath = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_BACKPATH);
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
// current item is last on path, so need one before that
if (backPath == null || backPath.size() < 2)
return;
PathEntry prevEntry = backPath.get(backPath.size()-2);
SimplePageItem prevItem = findItem(prevEntry.pageItemId);
GeneralViewParameters view = new GeneralViewParameters();
int itemType = prevItem.getType();
if (itemType == SimplePageItem.PAGE) {
view.setSendingPage(Long.valueOf(prevItem.getSakaiId()));
view.viewID = ShowPageProducer.VIEW_ID;
// are we returning to a page? If so use existing path entry
int lastEntry = -1;
int i = 0;
long prevItemId = prevEntry.pageItemId;
for (PathEntry entry: path) {
if (entry.pageItemId == prevItemId)
lastEntry = i;
i++;
}
if (lastEntry >= 0)
view.setPath(Integer.toString(lastEntry));
else if (item.getType() == SimplePageItem.PAGE)
view.setPath("next"); // page to page, just a next
else
view.setPath("push"); // item to page, have to push the page
} else if (itemType == SimplePageItem.RESOURCE) { // must be a samepage resource
view.setSendingPage(Long.valueOf(item.getPageId()));
view.setSource(prevItem.getItemURL());
view.viewID = ShowItemProducer.VIEW_ID;
} else {
view.setSendingPage(Long.valueOf(item.getPageId()));
LessonEntity lessonEntity = null;
switch (prevItem.getType()) {
case SimplePageItem.ASSIGNMENT:
lessonEntity = assignmentEntity.getEntity(prevItem.getSakaiId()); break;
case SimplePageItem.ASSESSMENT:
view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
lessonEntity = quizEntity.getEntity(prevItem.getSakaiId()); break;
case SimplePageItem.FORUM:
lessonEntity = forumEntity.getEntity(prevItem.getSakaiId()); break;
}
view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
if (item.getType() == SimplePageItem.PAGE)
view.setPath("pop"); // now on a page, have to pop it off
view.viewID = ShowItemProducer.VIEW_ID;
}
view.setItemId(prevItem.getId());
view.setBackPath("pop");
UIInternalLink.make(tofill, "prev", messageLocator.getMessage("simplepage.back"), view);
}
public String getCurrentSiteId() {
try {
return toolManager.getCurrentPlacement().getContext();
} catch (Exception impossible) {
return null;
}
}
// recall that code typically operates on a "current page." See below for
// the code that sets a new current page. We also have a current item, which
// is the item defining the page. I.e. if the page is a subpage of anotehr
// one, this is the item on the parent page pointing to this page. If it's
// a top-level page, it's a dummy item. The item is needed in order to do
// access checks. Whether an item is required, etc, is stored in the item.
// in theory a page could be caled from several other pages, with different
// access control parameters. So we need to know the actual item on the page
// page from which this page was called.
// we need to track the pageitem because references to the same page can appear
// in several places. In theory each one could have different status of availability
// so we need to know which in order to check availability
public void updatePageItem(long item) throws PermissionException {
SimplePageItem i = findItem(item);
if (i != null) {
if ((long)currentPageId != (long)Long.valueOf(i.getSakaiId())) {
log.warn("updatePageItem permission failure " + i + " " + Long.valueOf(i.getSakaiId()) + " " + currentPageId);
throw new PermissionException(getCurrentUserId(), "set item", Long.toString(item));
}
}
currentPageItemId = item;
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-item", item);
}
// update our concept of the current page. it is imperative to make sure the page is in
// the current site, or people could hack on other people's pages
// if you call updatePageObject, consider whether you need to call updatePageItem as well
// this combines two functions, so maybe not, but any time you're goign to a new page
// you should do both. Make sure all Producers set the page to the one they will work on
public void updatePageObject(long l) throws PermissionException {
if (l != previousPageId) {
currentPage = simplePageToolDao.getPage(l);
String siteId = toolManager.getCurrentPlacement().getContext();
// page should always be in this site, or someone is gaming us
if (!currentPage.getSiteId().equals(siteId))
throw new PermissionException(getCurrentUserId(), "set page", Long.toString(l));
previousPageId = l;
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-page", l);
currentPageId = (Long)l;
}
}
// if tool was reset, return last page from previous session, so we can give the user
// a chance to go back
public SimplePageToolDao.PageData toolWasReset() {
if (sessionManager.getCurrentToolSession().getAttribute("current-pagetool-page") == null) {
// no page in session, which means it was reset
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
return simplePageToolDao.findMostRecentlyVisitedPage(getCurrentUserId(), toolId);
} else
return null;
}
// ought to be simple, but this is typically called at the beginning of a producer, when
// the current page isn't set yet. So if there isn't one, we use the session variable
// to tell us what the current page is. Note that a user can add our tool using Site
// Info. Site info knows nothing about us, so it will make an entry for the page without
// creating it. When the user then tries to go to the page, this code will be the firsst
// to notice it. Hence we have to create pages that don't exist
private long getCurrentPageId() {
// return ((ToolConfiguration)toolManager.getCurrentPlacement()).getPageId();
if (currentPageId != null)
return (long)currentPageId;
// Let's go back to where we were last time.
Long l = (Long) sessionManager.getCurrentToolSession().getAttribute("current-pagetool-page");
if (l != null && l != 0) {
try {
updatePageObject(l);
Long i = (Long) sessionManager.getCurrentToolSession().getAttribute("current-pagetool-item");
if (i != null && i != 0)
updatePageItem(i);
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to item in toolsession");
return 0;
}
return l;
} else {
// No recent activity. Let's go to the top level page.
l = simplePageToolDao.getTopLevelPageId(((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId());
if (l != null) {
try {
updatePageObject(l);
// this should exist except if the page was created by old code
SimplePageItem i = simplePageToolDao.findTopLevelPageItemBySakaiId(String.valueOf(l));
if (i == null) {
// and dummy item, the site is the notional top level page
i = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, l.toString(), currentPage.getTitle());
saveItem(i);
}
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to page in toolsession");
return 0;
}
return l;
} else {
// No page found. Let's make a new one.
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
String title = getCurrentSite().getPage(toolId).getTitle(); // Use title supplied
// during creation
SimplePage page = simplePageToolDao.makePage(toolId, toolManager.getCurrentPlacement().getContext(), title, null, null);
if (!saveItem(page)) {
currentPage = null;
return 0;
}
try {
updatePageObject(page.getPageId());
l = page.getPageId();
// and dummy item, the site is the notional top level page
SimplePageItem i = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, l.toString(), title);
saveItem(i);
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageId Permission failed setting to new page");
return 0;
}
return l;
}
}
}
// current page must be set.
public SimplePageItem getCurrentPageItem(Long itemId) {
// if itemId is known, this is easy. but check to make sure it's
// actually this page, to prevent the user gaming us
if (itemId == null || itemId == -1)
itemId = currentPageItemId;
if (itemId != null && itemId != -1) {
SimplePageItem ret = findItem(itemId);
if (ret != null && ret.getSakaiId().equals(Long.toString(getCurrentPageId()))) {
try {
updatePageItem(ret.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageItem Permission failed setting to specified item");
return null;
}
return ret;
} else
return null;
}
// else must be a top level item
SimplePageItem ret = simplePageToolDao.findTopLevelPageItemBySakaiId(Long.toString(getCurrentPageId()));
try {
updatePageItem(ret.getId());
} catch (PermissionException e) {
log.warn("getCurrentPageItem Permission failed setting to top level page in tool session");
return null;
}
return ret;
}
// called at the start of showpageproducer, with page info for the page about to be displayed
// updates the breadcrumbs, which are kept in session variables.
// returns string version of the new path
public String adjustPath(String op, Long pageId, Long pageItemId, String title) {
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
// if no current path, op doesn't matter. we can just do the current page
if (path == null || path.size() == 0) {
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
path = new ArrayList<PathEntry>();
path.add(entry);
} else if (path.get(path.size()-1).pageId.equals(pageId)) {
// nothing. we're already there. this is to prevent
// oddities if we refresh the page
} else if (op == null || op.equals("") || op.equals("next")) {
PathEntry entry = path.get(path.size()-1); // overwrite last item
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
} else if (op.equals("push")) {
// a subpage
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
path.add(entry); // put it on the end
} else if (op.equals("pop")) {
// a subpage
path.remove(path.size()-1);
} else if (op.startsWith("log")) {
// set path to what was saved in the last log entry for this item
// this is used for users who go directly to a page from the
// main list of pages.
path = new ArrayList<PathEntry>();
SimplePageLogEntry logEntry = getLogEntry(pageItemId);
if (logEntry != null) {
String items[] = null;
if (logEntry.getPath() != null)
items = logEntry.getPath().split(",");
if (items != null) {
for(String s: items) {
// don't see how this could happen, but it did
if (s.trim().equals("")) {
log.warn("adjustPath attempt to set invalid path: invalid item: " + op + ":" + logEntry.getPath());
return null;
}
SimplePageItem i = findItem(Long.valueOf(s));
if (i == null || i.getType() != SimplePageItem.PAGE) {
log.warn("adjustPath attempt to set invalid path: invalid item: " + op);
return null;
}
SimplePage p = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
if (p == null || !currentPage.getSiteId().equals(p.getSiteId())) {
log.warn("adjustPath attempt to set invalid path: invalid page: " + op);
return null;
}
PathEntry entry = new PathEntry();
entry.pageId = p.getPageId();
entry.pageItemId = i.getId();
entry.title = i.getName();
path.add(entry);
}
}
}
} else {
int index = Integer.valueOf(op); // better be number
if (index < path.size()) {
// if we're going back, this should actually
// be redundant
PathEntry entry = path.get(index); // back to specified item
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
if (index < (path.size()-1))
path.subList(index+1, path.size()).clear();
}
}
// have new path; set it in session variable
sessionManager.getCurrentToolSession().setAttribute(LESSONBUILDER_PATH, path);
// and make string representation to return
String ret = null;
for (PathEntry entry: path) {
String itemString = Long.toString(entry.pageItemId);
if (ret == null)
ret = itemString;
else
ret = ret + "," + itemString;
}
if (ret == null)
ret = "";
return ret;
}
public void adjustBackPath(String op, Long pageId, Long pageItemId, String title) {
List<PathEntry> backPath = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_BACKPATH);
if (backPath == null)
backPath = new ArrayList<PathEntry>();
// default case going directly to something.
// normally we want to push it, but if it's already there,
// we're going back to it, use the old one
if (op == null || op.equals("")) {
// is it there already? Some would argue that we should use the first occurrence
int lastEntry = -1;
int i = 0;
long itemId = pageItemId; // to avoid having to use equals
for (PathEntry entry: backPath) {
if (entry.pageItemId == itemId)
lastEntry = i;
i++;
}
if (lastEntry >= 0) {
// yes, back up to that entry
if (lastEntry < (backPath.size()-1))
backPath.subList(lastEntry+1, backPath.size()).clear();
return;
}
// no fall through and push the new item
}
if (op.equals("pop")) {
if (backPath.size() > 0)
backPath.remove(backPath.size()-1);
} else { // push or no operation
PathEntry entry = new PathEntry();
entry.pageId = pageId;
entry.pageItemId = pageItemId;
entry.title = title;
backPath.add(entry);
}
// have new path; set it in session variable
sessionManager.getCurrentToolSession().setAttribute(LESSONBUILDER_BACKPATH, backPath);
}
public void setSubpageTitle(String st) {
subpageTitle = st;
}
public void setSubpageNext(boolean s) {
subpageNext = s;
}
public void setSubpageButton(boolean s) {
subpageButton = s;
}
// called from "add subpage" dialog
// create if itemId == null or -1, else update existing
public String createSubpage() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
String title = subpageTitle;
boolean makeNewPage = (selectedEntity == null || selectedEntity.length() == 0);
boolean makeNewItem = (itemId == null || itemId == -1);
if ((title == null || title.length() == 0) &&
(selectedEntity == null || selectedEntity.length() == 0)) {
return "notitle";
}
SimplePage page = getCurrentPage();
Long parent = page.getPageId();
Long topParent = page.getTopParent();
if (topParent == null) {
topParent = parent;
}
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
SimplePage subpage = null;
if (makeNewPage) {
subpage = simplePageToolDao.makePage(toolId, toolManager.getCurrentPlacement().getContext(), title, parent, topParent);
saveItem(subpage);
selectedEntity = String.valueOf(subpage.getPageId());
} else {
subpage = simplePageToolDao.getPage(Long.valueOf(selectedEntity));
}
SimplePageItem i = null;
if (makeNewItem)
i = appendItem(selectedEntity, subpage.getTitle(), SimplePageItem.PAGE);
else
i = findItem(itemId);
if (i == null)
return "failure";
if (makeNewItem) {
i.setNextPage(subpageNext);
if (subpageButton)
i.setFormat("button");
else
i.setFormat("");
} else {
// when itemid is specified, we're changing pages for existing entry
i.setSakaiId(selectedEntity);
i.setName(subpage.getTitle());
}
update(i);
if (makeNewPage) {
// if creating new entry, go to it
try {
updatePageObject(subpage.getPageId());
updatePageItem(i.getId());
} catch (PermissionException e) {
log.warn("createSubpage permission failed going to new page");
return "failed";
}
adjustPath((subpageNext ? "next" : "push"), subpage.getPageId(), i.getId(), i.getName());
submit();
}
return "success";
}
public String deletePages() {
if (!canEditPage())
return "permission-failed";
String siteId = toolManager.getCurrentPlacement().getContext();
for (int i = 0; i < selectedEntities.length; i++) {
SimplePage target = simplePageToolDao.getPage(Long.valueOf(selectedEntities[i]));
if (target != null) {
if (!target.getSiteId().equals(siteId)) {
return "permission-failed";
}
// delete all the items on the page
List<SimplePageItem> items = getItemsOnPage(target.getPageId());
for (SimplePageItem item: items) {
// if access controlled, clear it before deleting item
if (item.isPrerequisite()) {
item.setPrerequisite(false);
checkControlGroup(item);
}
simplePageToolDao.deleteItem(item);
}
// remove from gradebook
gradebookIfc.removeExternalAssessment(siteId, "lesson-builder:" + target.getPageId());
// remove fake item if it's top level. We won't see it if it's still active
// so this means the user has removed it in site info
SimplePageItem item = simplePageToolDao.findTopLevelPageItemBySakaiId(selectedEntities[i]);
if (item != null)
simplePageToolDao.deleteItem(item);
// currently the UI doesn't allow you to kill top level pages until they have been
// removed by site info, so we don't have to hack on the site pages
// remove page
simplePageToolDao.deleteItem(target);
}
}
return "success";
}
// remove a top-level page from the left margin. Does not actually delete it.
// this and addpages checks only edit page permission. should it check site.upd?
public String removePage() {
if (!canEditPage())
return "permission-failed";
Site site = getCurrentSite();
SimplePage page = getCurrentPage();
SitePage sitePage = site.getPage(page.getToolId());
if (sitePage == null) {
log.error("removePage can't find site page for " + page.getPageId());
return "no-such-page";
}
site.removePage(sitePage);
try {
siteService.save(site);
} catch (Exception e) {
log.error("removePage unable to save site " + e);
}
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.remove", "/lessonbuilder/page/" + page.getPageId(), true));
return "success";
}
// called from "save" in main edit item dialog
public String editItem() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (name.length() < 1) {
return "Notitle";
}
SimplePageItem i = findItem(itemId);
if (i == null) {
return "failure";
} else {
i.setName(name);
i.setDescription(description);
i.setRequired(required);
i.setPrerequisite(prerequisite);
i.setSubrequirement(subrequirement);
i.setNextPage(subpageNext);
if (subpageButton)
i.setFormat("button");
else
i.setFormat("");
if (points != "") {
i.setRequirementText(points);
} else {
i.setRequirementText(dropDown);
}
// currently we only display HTML in the same page
if (i.getType() == SimplePageItem.RESOURCE)
i.setSameWindow(!newWindow);
else
i.setSameWindow(false);
update(i);
if (i.getType() == SimplePageItem.PAGE) {
SimplePage page = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
if (page != null) {
page.setTitle(name);
update(page);
}
} else {
checkControlGroup(i);
}
return "successEdit"; // Shouldn't reload page
}
}
// Set access control for an item to the state requested by i.isPrerequisite().
// This code should depend only upon isPrerequisite() in the item object, not the database,
// because we call it when deleting or updating items, before saving them to the database.
// The caller will update the item in the database, typically after this call
private void checkControlGroup(SimplePageItem i) {
if (i.getType() != SimplePageItem.ASSESSMENT &&
i.getType() != SimplePageItem.ASSIGNMENT &&
i.getType() != SimplePageItem.FORUM) {
// We only do this for assignments and assessments
// currently we can't actually set it for forum topics
return;
}
if (i.getSakaiId().equals(SimplePageItem.DUMMY))
return;
SimplePageGroup group = simplePageToolDao.findGroup(i.getSakaiId());
try {
if (i.isPrerequisite()) {
if (group == null) {
String groupId = GroupPermissionsService.makeGroup(getCurrentPage().getSiteId(), "Access: " + getNameOfSakaiItem(i));
saveItem(simplePageToolDao.makeGroup(i.getSakaiId(), groupId));
GroupPermissionsService.addControl(i.getSakaiId(), getCurrentPage().getSiteId(), groupId, i.getType());
} else {
GroupPermissionsService.addControl(i.getSakaiId(), getCurrentPage().getSiteId(), group.getGroupId(), i.getType());
}
} else {
// if no group ID, nothing to do
if (group != null)
GroupPermissionsService.removeControl(i.getSakaiId(), getCurrentPage().getSiteId(), group.getGroupId(), i.getType());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public SimplePage getCurrentPage() {
getCurrentPageId();
return currentPage;
}
public String getToolId(String tool) {
try {
ToolConfiguration tc = siteService.getSite(currentPage.getSiteId()).getToolForCommonId(tool);
return tc.getId();
} catch (IdUnusedException e) {
// This really shouldn't happen.
log.warn("getToolId 1 attempt to get tool config for " + tool + " failed. Tool missing from site?");
return null;
} catch (java.lang.NullPointerException e) {
log.warn("getToolId 2 attempt to get tool config for " + tool + " failed. Tool missing from site?");
return null;
}
}
public void updateCurrentPage() {
update(currentPage);
}
public List<PathEntry> getHierarchy() {
List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
if (path == null)
return new ArrayList<PathEntry>();
return path;
}
public void setSelectedAssignment(String selectedAssignment) {
this.selectedAssignment = selectedAssignment;
}
public void setSelectedEntity(String selectedEntity) {
this.selectedEntity = selectedEntity;
}
public void setSelectedQuiz(String selectedQuiz) {
this.selectedQuiz = selectedQuiz;
}
public String assignmentRef(String id) {
return "/assignment/a/" + toolManager.getCurrentPlacement().getContext() + "/" + id;
}
// called by add forum dialog. Create a new item that points to a forum or
// update an existing item, depending upon whether itemid is set
public String addForum() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedEntity == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = forumEntity.getEntity(selectedEntity);
if (selectedObject == null) {
return "failure";
}
SimplePageItem i;
// editing existing item?
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// if no change, don't worry
if (!i.getSakaiId().equals(selectedEntity)) {
// if access controlled, clear restriction from old assignment and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedEntity);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedEntity);
i.setName(selectedObject.getTitle());
}
// reset assignment-specific stuff
i.setDescription("");
update(i);
}
} else {
// no, add new item
i = appendItem(selectedEntity, selectedObject.getTitle(), SimplePageItem.FORUM);
i.setDescription("");
update(i);
}
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedEntity = null;
}
}
}
// called by add assignment dialog. Create a new item that points to an assigment
// or update an existing item, depending upon whether itemid is set
public String addAssignment() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedAssignment == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = assignmentEntity.getEntity(selectedAssignment);
if (selectedObject == null)
return "failure";
SimplePageItem i;
// editing existing item?
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// if no change, don't worry
LessonEntity existing = assignmentEntity.getEntity(i.getSakaiId());
String ref = existing.getReference();
// if same quiz, nothing to do
if (!ref.equals(selectedAssignment)) {
// if access controlled, clear restriction from old assignment and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedAssignment);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedAssignment);
i.setName(selectedObject.getTitle());
}
// reset assignment-specific stuff
i.setDescription("(Due " + DateFormat.getDateTimeInstance().format(selectedObject.getDueDate()));
update(i);
}
} else {
// no, add new item
i = appendItem(selectedAssignment, selectedObject.getTitle(), SimplePageItem.ASSIGNMENT);
i.setDescription("(Due " + DateFormat.getDateTimeInstance().format(selectedObject.getDueDate()));
update(i);
}
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedAssignment = null;
}
}
}
// called by add quiz dialog. Create a new item that points to a quiz
// or update an existing item, depending upon whether itemid is set
public String addQuiz() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
if (selectedQuiz == null) {
return "failure";
} else {
try {
LessonEntity selectedObject = quizEntity.getEntity(selectedQuiz);
if (selectedObject == null)
return "failure";
// editing existing item?
SimplePageItem i;
if (itemId != null && itemId != -1) {
i = findItem(itemId);
// do getEntity/getreference to normalize, in case sakaiid is old format
LessonEntity existing = quizEntity.getEntity(i.getSakaiId());
String ref = existing.getReference();
// if same quiz, nothing to do
if (!ref.equals(selectedQuiz)) {
// if access controlled, clear restriction from old quiz and add to new
if (i.isPrerequisite()) {
i.setPrerequisite(false);
checkControlGroup(i);
// sakaiid and name are used in setting control
i.setSakaiId(selectedQuiz);
i.setName(selectedObject.getTitle());
i.setPrerequisite(true);
checkControlGroup(i);
} else {
i.setSakaiId(selectedQuiz);
i.setName(selectedObject.getTitle());
}
// reset quiz-specific stuff
i.setDescription("");
update(i);
}
} else // no, add new item
appendItem(selectedQuiz, selectedObject.getTitle(), SimplePageItem.ASSESSMENT);
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "failure";
} finally {
selectedQuiz = null;
}
}
}
public void setLinkUrl(String url) {
linkUrl = url;
}
// doesn't seem to be used at the moment
public String createLink() {
if (linkUrl == null || linkUrl.equals("")) {
return "cancel";
}
String url = linkUrl;
url = url.trim();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
appendItem(url, url, SimplePageItem.URL);
return "success";
}
public void setPage(long pageId) {
sessionManager.getCurrentToolSession().setAttribute("current-pagetool-page", pageId);
currentPageId = null;
}
// more setters and getters used by forms
public void setHeight(String height) {
this.height = height;
}
public String getHeight() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getHeight();
}
return (r == null ? "" : r);
}
public void setWidth(String width) {
this.width = width;
}
public String getWidth() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getWidth();
}
return (r == null ? "" : r);
}
public String getAlt() {
String r = "";
if (itemId != null && itemId > 0) {
r = findItem(itemId).getAlt();
}
return (r == null ? "" : r);
}
// called by edit multimedia dialog to change parameters in a multimedia item
public String editMultimedia() {
if (!itemOk(itemId))
return "permission-failed";
if (!canEditPage())
return "permission-failed";
SimplePageItem i = findItem(itemId);
if (i != null && i.getType() == SimplePageItem.MULTIMEDIA) {
i.setHeight(height);
i.setWidth(width);
i.setAlt(alt);
i.setDescription(description);
i.setHtml(mimetype);
update(i);
return "success";
} else {
log.warn("editMultimedia Could not find multimedia object: " + itemId);
return "cancel";
}
}
// called by edit title dialog to change attributes of the page such as the title
public String editTitle() {
if (pageTitle == null || pageTitle.equals("")) {
return "notitle";
}
// because we're using a security advisor, need to make sure it's OK ourselves
if (!canEditPage()) {
return "permission-failed";
}
Placement placement = toolManager.getCurrentPlacement();
SimplePage page = getCurrentPage();
SimplePageItem pageItem = getCurrentPageItem(null);
// update gradebook link if necessary
Double currentPoints = page.getGradebookPoints();
Double newPoints = null;
boolean needRecompute = false;
Site site = getCurrentSite();
if (points != null) {
try {
newPoints = Double.parseDouble(points);
if (newPoints == 0.0)
newPoints = null;
} catch (Exception ignore) {
newPoints = null;
}
}
// adjust gradebook entry
if (newPoints == null && currentPoints != null) {
gradebookIfc.removeExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId());
} else if (newPoints != null && currentPoints == null) {
gradebookIfc.addExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(), null,
pageTitle, newPoints, null, "Lesson Builder");
needRecompute = true;
} else if (currentPoints != null &&
(!currentPoints.equals(newPoints) || !pageTitle.equals(page.getTitle()))) {
gradebookIfc.updateExternalAssessment(site.getId(), "lesson-builder:" + page.getPageId(), null,
pageTitle, newPoints, null);
if (currentPoints != newPoints)
needRecompute = true;
}
page.setGradebookPoints(newPoints);
if (pageTitle != null && pageItem.getPageId() == 0) {
try {
// we need a security advisor because we're allowing users to edit the page if they
// have
// simplepage.upd privileges, but site.save requires site.upd.
securityService.pushAdvisor(new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
if (function.equals(SITE_UPD) && reference.equals("/site/" + toolManager.getCurrentPlacement().getContext())) {
return SecurityAdvice.ALLOWED;
} else {
return SecurityAdvice.PASS;
}
}
});
if (true) {
SitePage sitePage = site.getPage(page.getToolId());
sitePage.setTitle(pageTitle);
siteService.save(site);
page.setTitle(pageTitle);
page.setHidden(hidePage);
if (hasReleaseDate)
page.setReleaseDate(releaseDate);
else
page.setReleaseDate(null);
update(page);
updateCurrentPage();
placement.setTitle(pageTitle);
placement.save();
pageVisibilityHelper(site, page.getToolId(), !hidePage);
pageItem.setPrerequisite(prerequisite);
pageItem.setRequired(required);
update(pageItem);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
securityService.popAdvisor();
}
} else if (pageTitle != null) {
page.setTitle(pageTitle);
update(page);
}
// have to do this after the page itself is updated
if (needRecompute)
recomputeGradebookEntries(page.getPageId(), points);
// points, not newPoints because API wants a string
if (pageItem.getPageId() == 0) {
return "reload";
} else {
return "success";
}
}
public String addPages() {
if (!canEditPage())
return "permission-fail";
// javascript should have checked all this
if (newPageTitle == null || newPageTitle.equals(""))
return "fail";
int numPages = 1;
if (numberOfPages !=null && !numberOfPages.equals(""))
numPages = Integer.valueOf(numberOfPages);
String prefix = "";
String suffix = "";
int start = 1;
if (numPages > 1) {
Pattern pattern = Pattern.compile("(\\D*)(\\d+)(.*)");
Matcher matcher = pattern.matcher(newPageTitle);
if (!matcher.matches())
return "fail";
prefix = matcher.group(1);
suffix = matcher.group(3);
start = Integer.parseInt(matcher.group(2));
}
if (numPages == 1) {
addPage(newPageTitle, copyPage);
} else {
// note sure what to do here. We have to have a maximum to prevent creating 1,000,000 pages due
// to a typo. This allows one a week for a year. Surely that's enough. We can make it
// configurable if necessary.
if (numPages > 52)
numPages = 52;
while (numPages > 0) {
String title = prefix + Integer.toString(start) + suffix;
addPage(title, copyPage);
numPages--;
start++;
}
}
return "success";
}
public SimplePage addPage(String title, boolean copyCurrent) {
Site site = getCurrentSite();
SitePage sitePage = site.addPage();
ToolConfiguration tool = sitePage.addTool(LESSONBUILDER_ID);
tool.setTitle(title);
String toolId = tool.getPageId();
sitePage.setTitle(title);
sitePage.setTitleCustom(true);
try {
siteService.save(site);
} catch (Exception e) {
log.error("addPage unable to save site " + e);
}
currentSite = null; // force refetch, since we've changed it
SimplePage page = simplePageToolDao.makePage(toolId, getCurrentSiteId(), title, null, null);
saveItem(page);
SimplePageItem item = simplePageToolDao.makeItem(0, 0, SimplePageItem.PAGE, Long.toString(page.getPageId()), title);
saveItem(item);
if (copyCurrent) {
long oldPageId = getCurrentPageId();
long newPageId = page.getPageId();
for (SimplePageItem oldItem: simplePageToolDao.findItemsOnPage(oldPageId)) {
SimplePageItem newItem = simplePageToolDao.copyItem(oldItem);
newItem.setPageId(newPageId);
saveItem(newItem);
}
}
return page;
}
// when a gradebook entry is added or point value for page changed, need to
// add or update all student entries for the page
// this only updates grades for users that are complete. Others should have 0 score, which won't change
public void recomputeGradebookEntries(Long pageId, String newPoints) {
Map<String, String> userMap = new HashMap<String,String>();
List<SimplePageItem> items = simplePageToolDao.findPageItemsBySakaiId(Long.toString(pageId));
if (items == null)
return;
for (SimplePageItem item : items) {
List<String> users = simplePageToolDao.findUserWithCompletePages(item.getId());
for (String user: users)
userMap.put(user, newPoints);
}
gradebookIfc.updateExternalAssessmentScores(getCurrentSiteId(), "lesson-builder:" + pageId, userMap);
}
public boolean isImageType(SimplePageItem item) {
// if mime type is defined use it
String mimeType = item.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals("")))
mimeType = null;
if (mimeType != null && mimeType.length() > 0) {
return mimeType.toLowerCase().startsWith("image/");
}
// else use extension
String name = item.getSakaiId();
// starts after last /
int i = name.lastIndexOf("/");
if (i >= 0)
name = name.substring(i+1);
String extension = null;
i = name.lastIndexOf(".");
if (i > 0)
extension = name.substring(i+1);
if (extension == null)
return false;
extension = extension.trim();
extension = extension.toLowerCase();
if (imageTypes.contains(extension)) {
return true;
} else {
return false;
}
}
public void setOrder(String order) {
this.order = order;
}
// called by reorder tool to do the reordering
public String reorder() {
if (!canEditPage())
return "permission-fail";
if (order == null) {
return "cancel";
}
order = order.trim();
List<SimplePageItem> items = getItemsOnPage(getCurrentPageId());
String[] split = order.split(" ");
// make sure nothing is duplicated. I know it shouldn't be, but
// I saw the Fluid reorderer get confused once.
Set<Integer> used = new HashSet<Integer>();
for (int i = 0; i < split.length; i++) {
if (!used.add(Integer.valueOf(split[i]))) {
log.warn("reorder: duplicate value");
return "failed"; // it was already there. Oops.
}
}
// now do the reordering
for (int i = 0; i < split.length; i++) {
int old = items.get(Integer.valueOf(split[i]) - 1).getSequence();
items.get(Integer.valueOf(split[i]) - 1).setSequence(i + 1);
if (old != i + 1) {
update(items.get(Integer.valueOf(split[i]) - 1));
}
}
return "success";
}
// this is sort of sleasy. A simple redirect passes no data. Thus it takes
// us back to the default page. So we advance the default page. It would probably
// have been better to use a link rather than a command, then the link could
// have passed the page and item.
// public String next() {
// getCurrentPageId(); // sets item id, which is what we want
// SimplePageItem item = getCurrentPageItem(null);
//
// List<SimplePageItem> items = getItemsOnPage(item.getPageId());
//
// item = items.get(item.getSequence()); // sequence start with 1, so this is the next item
// updatePageObject(Long.valueOf(item.getSakaiId()));
// updatePageItem(item.getId());
//
// return "redirect";
// }
public String getCurrentUserId() {
if (currentUserId == null)
currentUserId = sessionManager.getCurrentSessionUserId();
return currentUserId;
}
// page is complete, update gradebook entry if any
// note that if the user has never gone to a page, the gradebook item will be missing.
// if they gone to it but it's not complete, it will be 0. We can't explicitly set
// a missing value, and this is the only way things will work if someone completes a page
// and something changes so it is no longer complete.
public void trackComplete(SimplePageItem item, boolean complete ) {
SimplePage page = getCurrentPage();
if (page.getGradebookPoints() != null)
gradebookIfc.updateExternalAssessmentScore(getCurrentSiteId(), "lesson-builder:" + page.getPageId(), getCurrentUserId(),
complete ? Double.toString(page.getGradebookPoints()) : "0.0");
}
/**
*
* @param itemId
* The ID in the <b>items</b> table.
* @param path
* breadcrumbs, only supplied it the item is a page
* It is valid for code to check path == null to see
* whether it is a page
* Create or update a log entry when user accesses an item.
*/
public void track(long itemId, String path) {
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
SimplePageLogEntry entry = getLogEntry(itemId);
if (entry == null) {
entry = simplePageToolDao.makeLogEntry(userId, itemId);
if (path != null) {
boolean complete = isPageComplete(itemId);
entry.setComplete(complete);
entry.setPath(path);
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
entry.setToolId(toolId);
SimplePageItem i = findItem(itemId);
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.read", "/lessonbuilder/page/" + i.getSakaiId(), complete));
trackComplete(i, complete);
}
saveItem(entry);
logCache.put((Long)itemId, entry);
} else {
if (path != null) {
boolean wasComplete = entry.isComplete();
boolean complete = isPageComplete(itemId);
entry.setComplete(complete);
entry.setPath(path);
String toolId = ((ToolConfiguration) toolManager.getCurrentPlacement()).getPageId();
entry.setToolId(toolId);
entry.setDummy(false);
SimplePageItem i = findItem(itemId);
EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.read", "/lessonbuilder/page/" + i.getSakaiId(), complete));
if (complete != wasComplete)
trackComplete(i, complete);
}
update(entry);
}
//SimplePageItem i = findItem(itemId);
// todo
// code can't work anymore. I'm not sure whether it's needed.
// we don't update a page as complete if the user finishes a test, etc, until he
// comes back to the page. I'm not sure I feel compelled to do this either. But
// once we move to the new hiearchy, we'll see
// top level doesn't have a next level, so avoid null pointer problem
// if (i.getPageId() != 0) {
// SimplePageItem nextLevelUp = simplePageToolDao.findPageItemBySakaiId(String.valueOf(i.getPageId()));
// if (isItemComplete(findItem(itemId)) && nextLevelUp != null) {
// track(nextLevelUp.getId(), true);
// }
// }
}
public SimplePageLogEntry getLogEntry(long itemId) {
SimplePageLogEntry entry = logCache.get((Long)itemId);
if (entry != null)
return entry;
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
entry = simplePageToolDao.getLogEntry(userId, itemId);
logCache.put((Long)itemId, entry);
return entry;
}
public boolean hasLogEntry(long itemId) {
return (getLogEntry(itemId) != null);
}
// this is called in a loop to see whether items are avaiable. Since computing it can require
// database transactions, we cache the results
public boolean isItemComplete(SimplePageItem item) {
if (!item.isRequired()) {
// We don't care if it has been completed if it isn't required.
return true;
}
Long itemId = item.getId();
Boolean cached = completeCache.get(itemId);
if (cached != null)
return (boolean)cached;
if (item.getType() == SimplePageItem.RESOURCE || item.getType() == SimplePageItem.URL) {
// Resource. Completed if viewed.
if (hasLogEntry(item.getId())) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.PAGE) {
SimplePageLogEntry entry = getLogEntry(item.getId());
if (entry == null || entry.getDummy()) {
completeCache.put(itemId, false);
return false;
} else if (entry.isComplete()) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.ASSIGNMENT) {
try {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
LessonEntity assignment = assignmentEntity.getEntity(item.getSakaiId());
if (assignment == null) {
completeCache.put(itemId, false);
return false;
}
LessonSubmission submission = assignment.getSubmission(getCurrentUserId());
if (submission == null) {
completeCache.put(itemId, false);
return false;
}
int type = assignment.getTypeOfGrade();
if (!item.getSubrequirement()) {
completeCache.put(itemId, true);
return true;
} else if (submission.getGradeString() != null) {
// assume that assignments always use string grade. this may change
boolean ret = isAssignmentComplete(type, submission, item.getRequirementText());
completeCache.put(itemId, ret);
return ret;
} else {
completeCache.put(itemId, false);
return false;
}
} catch (Exception e) {
e.printStackTrace();
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.FORUM) {
try {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
User user = UserDirectoryService.getUser(getCurrentUserId());
LessonEntity forum = forumEntity.getEntity(item.getSakaiId());
if (forum == null)
return false;
// for the moment don't find grade. just see if they submitted
if (forum.getSubmissionCount(user.getId()) > 0) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
} catch (Exception e) {
e.printStackTrace();
completeCache.put(itemId, false);
return false;
}
} else if (item.getType() == SimplePageItem.ASSESSMENT) {
if (item.getSakaiId().equals(SimplePageItem.DUMMY)) {
completeCache.put(itemId, false);
return false;
}
LessonEntity quiz = quizEntity.getEntity(item.getSakaiId());
if (quiz == null) {
completeCache.put(itemId, false);
return false;
}
User user = null;
try {
user = UserDirectoryService.getUser(getCurrentUserId());
} catch (Exception ignore) {
completeCache.put(itemId, false);
return false;
}
LessonSubmission submission = quiz.getSubmission(user.getId());
if (submission == null) {
completeCache.put(itemId, false);
return false;
} else if (!item.getSubrequirement()) {
// All that was required was that the user submit the test
completeCache.put(itemId, true);
return true;
} else {
Float grade = submission.getGrade();
if (grade >= Float.valueOf(item.getRequirementText())) {
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
}
} else if (item.getType() == SimplePageItem.TEXT || item.getType() == SimplePageItem.MULTIMEDIA) {
// In order to be considered "complete", these items
// only have to be viewed. If this code is reached,
// we know that that the page has already been viewed.
completeCache.put(itemId, true);
return true;
} else {
completeCache.put(itemId, false);
return false;
}
}
private boolean isAssignmentComplete(int type, LessonSubmission submission, String requirementString) {
String grade = submission.getGradeString();
if (type == SimplePageItem.ASSESSMENT) {
if (grade.equals("Pass")) {
return true;
} else {
return false;
}
} else if (type == SimplePageItem.TEXT) {
if (grade.equals("Checked")) {
return true;
} else {
return false;
}
} else if (type == SimplePageItem.PAGE) {
if (grade.equals("ungraded")) {
return false;
}
int requiredIndex = -1;
int currentIndex = -1;
for (int i = 0; i < GRADES.length; i++) {
if (GRADES[i].equals(requirementString)) {
requiredIndex = i;
}
if (GRADES[i].equals(grade)) {
currentIndex = i;
}
}
if (requiredIndex == -1 || currentIndex == -1) {
return false;
} else {
if (requiredIndex >= currentIndex) {
return true;
} else {
return false;
}
}
} else if (type == SimplePageItem.ASSIGNMENT) {
if (Float.valueOf(Integer.valueOf(grade) / 10) >= Float.valueOf(requirementString)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* @param itemId
* The ID of the page from the <b>items</b> table (not the page table).
* @return
*/
public boolean isPageComplete(long itemId) {
List<SimplePageItem> items = getItemsOnPage(Long.valueOf(findItem(itemId).getSakaiId()));
for (SimplePageItem item : items) {
if (!isItemComplete(item)) {
return false;
}
}
// All of them were complete.
return true;
}
// return list of pages needed for current page. This is the primary code
// used by ShowPageProducer to see whether the user is allowed to the page
// (given that they have read permission, of course)
// Note that the same page can occur
// multiple places, but we're passing the item, so we've got the right one
public List<String> pagesNeeded(SimplePageItem item) {
String currentPageId = Long.toString(getCurrentPageId());
List<String> needed = new ArrayList<String>();
if (!item.isPrerequisite()){
return needed;
}
// authorized or maybe user is gaming us, or maybe next page code
// sent them to something that isn't availbale.
// as an optimization chek haslogentry first. That will be true if
// they have been here before. Saves us the trouble of doing full
// access checking. Otherwise do a real check. That should only happen
// for next page in odd situations.
if (item.getPageId() > 0) {
if (!hasLogEntry(item.getId()) &&
!isItemAvailable(item, item.getPageId())) {
SimplePage parent = simplePageToolDao.getPage(item.getPageId());
if (parent != null)
needed.add(parent.getTitle());
else
needed.add("unknown page"); // not possible, it says
}
return needed;
}
// we've got a top level page.
// get dummy items for top level pages in site
List<SimplePageItem> items =
simplePageToolDao.findItemsInSite(getCurrentSite().getId());
// sorted by SQL
for (SimplePageItem i : items) {
if (i.getSakaiId().equals(currentPageId)) {
return needed; // reached current page. we're done
}
if (i.isRequired() && !isItemComplete(i))
needed.add(i.getName());
}
return needed;
}
public boolean isItemAvailable(SimplePageItem item) {
return isItemAvailable(item, getCurrentPageId());
}
public boolean isItemAvailable(SimplePageItem item, long pageId) {
if (item.isPrerequisite()) {
List<SimplePageItem> items = getItemsOnPage(pageId);
for (SimplePageItem i : items) {
if (i.getSequence() >= item.getSequence()) {
break;
} else if (i.isRequired()) {
if (!isItemComplete(i))
return false;
}
}
}
return true;
}
// weird variant that works even if current item doesn't have prereq.
public boolean wouldItemBeAvailable(SimplePageItem item, long pageId) {
List<SimplePageItem> items = getItemsOnPage(pageId);
for (SimplePageItem i : items) {
if (i.getSequence() >= item.getSequence()) {
break;
} else if (i.isRequired()) {
if (!isItemComplete(i))
return false;
}
}
return true;
}
public String getNameOfSakaiItem(SimplePageItem i) {
String SakaiId = i.getSakaiId();
if (SakaiId == null || SakaiId.equals(SimplePageItem.DUMMY))
return null;
if (i.getType() == SimplePageItem.ASSIGNMENT) {
LessonEntity assignment = assignmentEntity.getEntity(i.getSakaiId());
if (assignment == null)
return null;
return assignment.getTitle();
} else if (i.getType() == SimplePageItem.FORUM) {
LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
if (forum == null)
return null;
return forum.getTitle();
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
LessonEntity quiz = quizEntity.getEntity(i.getSakaiId());
if (quiz == null)
return null;
return quiz.getTitle();
} else
return null;
}
/*
* return 11-char youtube ID for a URL, or null if it doesn't match
* we store URLs as content objects, so we have to retrieve the object
* in order to check. The actual URL is stored as the contents
* of the entity
*/
public String getYoutubeKey(SimplePageItem i) {
String sakaiId = i.getSakaiId();
// find the resource
ContentResource resource = null;
try {
resource = contentHostingService.getResource(sakaiId);
} catch (Exception ignore) {
return null;
}
// make sure it's a URL
if (resource == null ||
!resource.getResourceType().equals("org.sakaiproject.content.types.urlResource") ||
!resource.getContentType().equals("text/url")) {
return null;
}
// get the actual URL
String URL = null;
try {
URL = new String(resource.getContent());
} catch (Exception ignore) {
return null;
}
if (URL == null) {
return null;
}
// see if it has a Youtube ID
if (URL.startsWith("http://www.youtube.com/") || URL.startsWith("http://youtube.com/")) {
Matcher match = YOUTUBE_PATTERN.matcher(URL);
if (match.find()) {
return match.group().substring(2);
}
}
// no
return null;
}
/**
* Meant to guarantee that the permissions are set correctly on an assessment for a user.
*
* @param item
* @param shouldHaveAccess
*/
public void checkItemPermissions(SimplePageItem item, boolean shouldHaveAccess) {
checkItemPermissions(item, shouldHaveAccess, true);
}
/**
*
* @param item
* @param shouldHaveAccess
* @param canRecurse
* Is it allowed to delete the row in the table for the group and recurse to try
* again. true for normal calls; false if called inside this code to avoid infinite loop
*/
private void checkItemPermissions(SimplePageItem item, boolean shouldHaveAccess, boolean canRecurse) {
if (SimplePageItem.DUMMY.equals(item.getSakaiId()))
return;
// for pages, presence of log entry is it
if (item.getType() == SimplePageItem.PAGE) {
Long itemId = item.getId();
if (getLogEntry(itemId) != null)
return; // already ok
// if no log entry, create a dummy entry
if (shouldHaveAccess) {
String userId = getCurrentUserId();
if (userId == null)
userId = ".anon";
SimplePageLogEntry entry = simplePageToolDao.makeLogEntry(userId, itemId);
entry.setDummy(true);
saveItem(entry);
logCache.put((Long)itemId, entry);
}
return;
}
SimplePageGroup group = simplePageToolDao.findGroup(item.getSakaiId());
if (group == null) {
// For some reason, the group doesn't exist. Let's re-add it.
String groupId;
try {
groupId = GroupPermissionsService.makeGroup(getCurrentPage().getSiteId(), "Access: " + getNameOfSakaiItem(item));
saveItem(simplePageToolDao.makeGroup(item.getSakaiId(), groupId));
GroupPermissionsService.addControl(item.getSakaiId(), getCurrentPage().getSiteId(), groupId, item.getType());
} catch (IOException e) {
// If this fails, there's no way for us to check the permissions
// in the group. This shouldn't happen.
e.printStackTrace();
return;
}
group = simplePageToolDao.findGroup(item.getSakaiId());
if (group == null) {
// Something really weird is up.
log.warn("checkItemPermissions Can't create a group for " + item.getName() + " permissions.");
return;
}
}
boolean success = true;
String groupId = group.getGroupId();
try {
if (shouldHaveAccess) {
success = GroupPermissionsService.addCurrentUser(getCurrentPage().getSiteId(), getCurrentUserId(), groupId);
} else {
success = GroupPermissionsService.removeUser(getCurrentPage().getSiteId(), getCurrentUserId(), groupId);
}
} catch (Exception ex) {
ex.printStackTrace();
return;
}
// hmmm.... couldn't add or remove from group. Most likely the Sakai-level group
// doesn't exist, although our database entry says it was created. Presumably
// the user deleted the group for Site Info. Make very sure that's the cause,
// or we'll create a duplicate group. I've seen failures for other reasons, such
// as a weird permissions problem with the only maintain users trying to unjoin
// a group.
if (!success && canRecurse) {
try {
AuthzGroupService.getAuthzGroup(groupId);
// group exists, it was something else. Who knows what
return;
} catch (org.sakaiproject.authz.api.GroupNotDefinedException ee) {
} catch (Exception e) {
// some other failure from getAuthzGroup, shouldn't be possible
log.warn("checkItemPermissions unable to join or unjoin group " + groupId);
}
log.warn("checkItemPermissions: User seems to have deleted group " + groupId + ". We'll recreate it.");
// OK, group doesn't exist. When we recreate it, it's going to have a
// different groupId, so we have to back out of everything and reset it
try {
GroupPermissionsService.removeControl(item.getSakaiId(), getCurrentPage().getSiteId(), groupId, item.getType());
} catch (IOException e) {
// Shoudln't happen, but we'll continue anyway
e.printStackTrace();
}
simplePageToolDao.deleteItem(group);
// We've undone it; call ourselves again, since the code at the
// start will recreate the group
checkItemPermissions(item, shouldHaveAccess, false);
}
}
public void setYoutubeURL(String url) {
youtubeURL = url;
}
public void setYoutubeId(long id) {
youtubeId = id;
}
public void deleteYoutubeItem() {
simplePageToolDao.deleteItem(findItem(youtubeId));
}
public void setMmUrl(String url) {
mmUrl = url;
}
public void setMultipartMap(Map<String, MultipartFile> multipartMap) {
this.multipartMap = multipartMap;
}
public String getCollectionId(boolean urls) {
String siteId = getCurrentPage().getSiteId();
String collectionId = contentHostingService.getSiteCollection(siteId);
// folder we really want
String folder = collectionId + Validator.escapeResourceName(getPageTitle()) + "/";
if (urls)
folder = folder + "urls/";
// OK?
try {
contentHostingService.checkCollection(folder);
// OK, let's use it
return folder;
} catch (Exception ignore) {};
// no. create folders as needed
// if url subdir, need an extra level
if (urls) {
// try creating the root. if it exists this will fail. That's OK.
String root = collectionId + Validator.escapeResourceName(getPageTitle()) + "/";
try {
ContentCollectionEdit edit = contentHostingService.addCollection(root);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(getPageTitle()));
contentHostingService.commitCollection(edit);
// well, we got that far anyway
collectionId = root;
} catch (Exception ignore) {
};
}
// now try creating what we want
try {
ContentCollectionEdit edit = contentHostingService.addCollection(folder);
if (urls)
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, "urls");
else
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(getPageTitle()));
contentHostingService.commitCollection(edit);
return folder; // worked. use it
} catch (Exception ignore) {};
// didn't. do the best we can
return collectionId;
}
public boolean isHtml(SimplePageItem i) {
StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");
String extension = "";
while (token.hasMoreTokens()) {
extension = token.nextToken().toLowerCase();
}
// we are just starting to store the MIME type for resources now. So existing content
// won't have them.
String mimeType = i.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals("")))
mimeType = null;
if (mimeType != null && (mimeType.equals("text/html") || mimeType.equals("application/xhtml+xml"))
|| mimeType == null && (extension.equals("html") || extension.equals("htm"))) {
return true;
}
return false;
}
public static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = 100;
// called by dialog to add inline multimedia item, or update existing
// item if itemid is specified
public void addMultimedia() {
if (!itemOk(itemId))
return;
if (!canEditPage())
return;
String name = null;
String sakaiId = null;
String mimeType = null;
MultipartFile file = null;
if (multipartMap.size() > 0) {
// user specified a file, create it
file = multipartMap.values().iterator().next();
if (file.isEmpty())
file = null;
}
if (file != null) {
String collectionId = getCollectionId(false);
// user specified a file, create it
name = file.getOriginalFilename();
if (name == null || name.length() == 0)
name = file.getName();
int i = name.lastIndexOf("/");
if (i >= 0)
name = name.substring(i+1);
String base = name;
String extension = "";
i = name.lastIndexOf(".");
if (i > 0) {
base = name.substring(0, i);
extension = name.substring(i+1);
}
mimeType = file.getContentType();
try {
ContentResourceEdit res = contentHostingService.addResource(collectionId,
Validator.escapeResourceName(base),
Validator.escapeResourceName(extension),
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType(mimeType);
res.setContent(file.getInputStream());
try {
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
// there's a bug in the kernel that can cause
// a null pointer if it can't determine the encoding
// type. Since we want this code to work on old
// systems, work around it.
} catch (java.lang.NullPointerException e) {
setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror"));
}
sakaiId = res.getId();
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
return;
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 1 " + e);
return;
};
} else if (mmUrl != null && !mmUrl.trim().equals("")) {
// user specified a URL, create the item
String url = mmUrl.trim();
if (!url.startsWith("http:") &&
!url.startsWith("https:")) {
if (!url.startsWith("//"))
url = "//" + url;
url = "http:" + url;
}
name = url;
String base = url;
String extension = "";
int i = url.lastIndexOf("/");
if (i < 0) i = 0;
i = url.lastIndexOf(".", i);
if (i > 0) {
extension = url.substring(i);
base = url.substring(0,i);
}
String collectionId = getCollectionId(true);
try {
// urls aren't something people normally think of as resources. Let's hide them
ContentResourceEdit res = contentHostingService.addResource(collectionId,
Validator.escapeResourceName(base),
Validator.escapeResourceName(extension),
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
res.setContent(url.getBytes());
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
sakaiId = res.getId();
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
return;
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 2 " + e);
return;
};
// connect to url and get mime type
mimeType = getTypeOfUrl(url);
} else
// nothing to do
return;
// itemId tells us whether it's an existing item
// isMultimedia tells us whether resource or multimedia
// sameWindow is only passed for existing items of type HTML/XHTML
// for new items it should be set true for HTML/XTML, false otherwise
// for existing items it should be set to the passed value for HTML/XMTL, false otherwise
// it is ignored for isMultimedia, as those are always displayed inline in the current page
SimplePageItem item = null;
if (itemId == -1 && isMultimedia) {
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
item = simplePageToolDao.makeItem(getCurrentPageId(), seq, SimplePageItem.MULTIMEDIA, sakaiId, name);
} else if (itemId == -1) {
int seq = getItemsOnPage(getCurrentPageId()).size() + 1;
item = simplePageToolDao.makeItem(getCurrentPageId(), seq, SimplePageItem.RESOURCE, sakaiId, name);
} else {
item = findItem(itemId);
if (item == null)
return;
item.setSakaiId(sakaiId);
item.setName(name);
}
if (mimeType != null) {
item.setHtml(mimeType);
} else {
item.setHtml(null);
}
// if this is an existing item and a resource, leave it alone
// otherwise initialize to false
if (isMultimedia || itemId == -1)
item.setSameWindow(false);
clearImageSize(item);
try {
if (itemId == -1)
saveItem(item);
else
update(item);
} catch (Exception e) {
// saveItem and update produce the errors
}
}
public boolean deleteRecursive(File path) throws FileNotFoundException{
if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath());
boolean ret = true;
if (path.isDirectory()){
for (File f : path.listFiles()){
ret = ret && deleteRecursive(f);
}
}
return ret && path.delete();
}
public void importCc() {
System.out.println("importCc");
if (!canEditPage())
return;
MultipartFile file = null;
if (multipartMap.size() > 0) {
// user specified a file, create it
file = multipartMap.values().iterator().next();
if (file.isEmpty())
file = null;
}
if (file != null) {
File cc = null;
File root = null;
try {
cc = File.createTempFile("ccloader", "file");
root = File.createTempFile("ccloader", "root");
if (root.exists())
root.delete();
root.mkdir();
BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cc));
byte[] buffer = new byte[8096];
int n = 0;
while ((n = bis.read(buffer, 0, 8096)) >= 0) {
if (n > 0)
bos.write(buffer, 0, n);
}
bis.close();
bos.close();
CartridgeLoader cartridgeLoader = ZipLoader.getUtilities(cc, root.getCanonicalPath());
Parser parser = Parser.createCartridgeParser(cartridgeLoader);
LessonEntity quizobject = null;
for (LessonEntity q = quizEntity; q != null; q = q.getNextEntity()) {
if (q.getToolId().equals(quiztool))
quizobject = q;
}
LessonEntity topicobject = null;
for (LessonEntity q = forumEntity; q != null; q = q.getNextEntity()) {
if (q.getToolId().equals(topictool))
topicobject = q;
}
parser.parse(new PrintHandler(this, cartridgeLoader, simplePageToolDao, quizobject, topicobject));
} catch (Exception e) {
System.out.println("exception in importcc " + e);
e.printStackTrace();
} finally {
if (cc != null)
try {
deleteRecursive(cc);
} catch (Exception e){
System.out.println("Unable to delete temp file " + cc);
}
try {
deleteRecursive(root);
} catch (Exception e){
System.out.println("Unable to delete temp file " + cc);
}
}
}
}
// called by edit dialog to update parameters of a Youtube item
public void updateYoutube() {
if (!itemOk(youtubeId))
return;
if (!canEditPage())
return;
SimplePageItem item = findItem(youtubeId);
// find the new key, if the new thing is a legit youtube url
Matcher match = YOUTUBE_PATTERN.matcher(youtubeURL);
String key = null;
if (match.find()) {
key = match.group().substring(2);
}
// oldkey had better work, since the youtube edit woudln't
// be displayed if it wasn't recognized
String oldkey = getYoutubeKey(item);
// if there's a new youtube URL, and it's different from
// the old one, update the URL if they are different
if (key != null && !key.equals(oldkey)) {
String url = "http://www.youtube.com/watch#!v=" + key;
String siteId = getCurrentPage().getSiteId();
String collectionId = getCollectionId(true);
try {
ContentResourceEdit res = contentHostingService.addResource(collectionId,Validator.escapeResourceName("Youtube video " + key),Validator.escapeResourceName("swf"),MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
res.setContentType("text/url");
res.setResourceType("org.sakaiproject.content.types.urlResource");
res.setContent(url.getBytes());
contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
item.setSakaiId(res.getId());
} catch (org.sakaiproject.exception.OverQuotaException ignore) {
setErrMessage(messageLocator.getMessage("simplepage.overquota"));
} catch (Exception e) {
setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
log.error("addMultimedia error 3 " + e);
};
}
// even if there's some oddity with URLs, we do these updates
item.setHeight(height);
item.setWidth(width);
item.setDescription(description);
update(item);
}
/**
* Adds or removes the requirement to have site.upd in order to see a page
* i.e. hide or unhide a page
* @param pageId
* The Id of the Page
* @param visible
* @return true for success, false for failure
* @throws IdUnusedException
* , PermissionException
*/
private boolean pageVisibilityHelper(Site site, String pageId, boolean visible) throws IdUnusedException, PermissionException {
SitePage page = site.getPage(pageId);
List<ToolConfiguration> tools = page.getTools();
Iterator<ToolConfiguration> iterator = tools.iterator();
// If all the tools on a page require site.upd then only users with site.upd will see
// the page in the site nav of Charon... not sure about the other Sakai portals floating
// about
while (iterator.hasNext()) {
ToolConfiguration placement = iterator.next();
Properties roleConfig = placement.getPlacementConfig();
String roleList = roleConfig.getProperty("functions.require");
boolean saveChanges = false;
if (roleList == null) {
roleList = "";
}
if (!(roleList.indexOf(SITE_UPD) > -1) && !visible) {
if (roleList.length() > 0) {
roleList += ",";
}
roleList += SITE_UPD;
saveChanges = true;
} else if (visible) {
roleList = roleList.replaceAll("," + SITE_UPD, "");
roleList = roleList.replaceAll(SITE_UPD, "");
saveChanges = true;
}
if (saveChanges) {
roleConfig.setProperty("functions.require", roleList);
placement.save();
siteService.save(site);
}
}
return true;
}
// used by edit dialog to update properties of a multimedia object
public void updateMovie() {
if (!itemOk(itemId))
return;
if (!canEditPage())
return;
SimplePageItem item = findItem(itemId);
item.setHeight(height);
item.setWidth(width);
item.setDescription(description);
item.setHtml(mimetype);
update(item);
}
} | LSNBLDR-7
git-svn-id: 5bcdb5e50f52176cb730abc866593bd8f5a95ebd@94842 66ffb92e-73f9-0310-93c1-f5514f145a0a
| lessonbuilder/tool/src/java/org/sakaiproject/lessonbuildertool/tool/beans/SimplePageBean.java | LSNBLDR-7 | <ide><path>essonbuilder/tool/src/java/org/sakaiproject/lessonbuildertool/tool/beans/SimplePageBean.java
<ide>
<ide> public static final Pattern YOUTUBE_PATTERN = Pattern.compile("v[=/_][\\w-]{11}");
<ide> public static final String GRADES[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "F" };
<del> public static final String FILTERHTML = "lessonbuilder.filterhtml";
<del> public static final String LESSONBUILDER_ITEMID = "lessonbuilder.itemid";
<add> public static final String FILTERHTML = "lessonbuilder.filterhtml";
<add> public static final String LESSONBUILDER_ITEMID = "lessonbuilder.itemid";
<ide> public static final String LESSONBUILDER_PATH = "lessonbuilder.path";
<ide> public static final String LESSONBUILDER_BACKPATH = "lessonbuilder.backpath";
<del> public static final String LESSONBUILDER_ID = "sakai.lessonbuildertool";
<add> public static final String LESSONBUILDER_ID = "sakai.lessonbuildertool";
<ide>
<ide> private static String PAGE = "simplepage.page";
<ide> private static String SITE_UPD = "site.upd";
<ide> private String pageTitle = null;
<ide> private String newPageTitle = null;
<ide> private String subpageTitle = null;
<del> private boolean subpageNext = false;
<del> private boolean subpageButton = false;
<del> private List<Long> currentPath = null;
<del> private Set<Long>allowedPages = null;
<del> private Site currentSite = null; // cache, can be null; used by getCurrentSite
<del>
<del> private boolean filterHtml = ServerConfigurationService.getBoolean(FILTERHTML, false);
<add> private boolean subpageNext = false;
<add> private boolean subpageButton = false;
<add> private List<Long> currentPath = null;
<add> private Set<Long>allowedPages = null;
<add> private Site currentSite = null; // cache, can be null; used by getCurrentSite
<add>
<add> private boolean filterHtml = ServerConfigurationService.getBoolean(FILTERHTML, false);
<ide>
<ide> public String selectedAssignment = null;
<ide>
<ide> // generic entity stuff. selectedEntity is the string
<ide> // coming from the picker. We'll use the same variable for any entity type
<ide> public String selectedEntity = null;
<del> public String[] selectedEntities = new String[] {};
<add> public String[] selectedEntities = new String[] {};
<ide>
<ide> public String selectedQuiz = null;
<ide>
<ide> private boolean newWindow;
<ide> private String dropDown;
<ide> private String points;
<del> private String mimetype;
<del>
<del> private String numberOfPages;
<del> private boolean copyPage;
<add> private String mimetype;
<add>
<add> private String numberOfPages;
<add> private boolean copyPage;
<ide>
<ide> private String alt = null;
<ide> private String order = null;
<ide>
<ide> private String redirectSendingPage = null;
<ide> private String redirectViewId = null;
<del> private String quiztool = null;
<del> private String topictool = null;
<del>
<del> public Map<String, MultipartFile> multipartMap;
<add> private String quiztool = null;
<add> private String topictool = null;
<add>
<add> public Map<String, MultipartFile> multipartMap;
<ide>
<ide> // Caches
<ide>
<ide> private Map<Long, SimplePageLogEntry> logCache = new HashMap<Long, SimplePageLogEntry>();
<ide> private Map<Long, Boolean> completeCache = new HashMap<Long, Boolean>();
<ide>
<del> public static class PathEntry {
<del> public Long pageId;
<del> public Long pageItemId;
<del> public String title;
<del> }
<del>
<del> public static class UrlItem {
<del> public String Url;
<del> public String label;
<del> public UrlItem(String Url, String label) {
<del> this.Url = Url;
<del> this.label = label;
<add> public static class PathEntry {
<add> public Long pageId;
<add> public Long pageItemId;
<add> public String title;
<add> }
<add>
<add> public static class UrlItem {
<add> public String Url;
<add> public String label;
<add> public UrlItem(String Url, String label) {
<add> this.Url = Url;
<add> this.label = label;
<ide> }
<ide> }
<ide>
<ide> // but at the moment path is just the pages. So when we're in a normal item, it doesn't show.
<ide> // that means that as we do Next between items and pages, when we go to a page it gets pushed
<ide> // on and when we go from a page to an item, the page has to be popped off.
<del> public void addNextLink(UIContainer tofill, SimplePageItem item) {
<del> SimplePageItem nextItem = findNextPage(item);
<del> if (nextItem == item) { // that we need to go up a level
<del> List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
<del> int top;
<del> if (path == null)
<del> top = -1;
<del> else
<del> top = path.size()-1;
<add> public void addNextLink(UIContainer tofill, SimplePageItem item) {
<add> SimplePageItem nextItem = findNextPage(item);
<add> if (nextItem == item) { // that we need to go up a level
<add> List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
<add> int top;
<add> if (path == null)
<add> top = -1;
<add> else
<add> top = path.size()-1;
<ide> // if we're on a page, have to pop it off first
<ide> // for a normal item the end of the path already is the page above
<del> if (item.getType() == SimplePageItem.PAGE)
<del> top--;
<del> if (top >= 0) {
<del> PathEntry e = path.get(top);
<del> GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
<del> view.setSendingPage(e.pageId);
<del> view.setItemId(e.pageItemId);
<del> view.setPath(Integer.toString(top));
<del> UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
<del> }
<add> if (item.getType() == SimplePageItem.PAGE)
<add> top--;
<add> if (top >= 0) {
<add> PathEntry e = path.get(top);
<add> GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
<add> view.setSendingPage(e.pageId);
<add> view.setItemId(e.pageItemId);
<add> view.setPath(Integer.toString(top));
<add> UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
<add> }
<ide> } else if (nextItem != null) {
<del> GeneralViewParameters view = new GeneralViewParameters();
<del> int itemType = nextItem.getType();
<del> if (itemType == SimplePageItem.PAGE) {
<del> view.setSendingPage(Long.valueOf(nextItem.getSakaiId()));
<del> view.viewID = ShowPageProducer.VIEW_ID;
<del> if (item.getType() == SimplePageItem.PAGE)
<del> view.setPath("next"); // page to page, just a next
<del> else
<del> view.setPath("push"); // item to page, have to push the page
<del> } else if (itemType == SimplePageItem.RESOURCE) { /// must be a same page resource
<del> view.setSendingPage(Long.valueOf(item.getPageId()));
<del> // to the check. We need the check to set access control appropriately
<del> // if the user has passed.
<del> if (!isItemAvailable(nextItem, nextItem.getPageId()))
<del> view.setRecheck("true");
<del> view.setSource(nextItem.getItemURL());
<del> view.viewID = ShowItemProducer.VIEW_ID;
<del> } else {
<del> view.setSendingPage(Long.valueOf(item.getPageId()));
<del> LessonEntity lessonEntity = null;
<del> switch (nextItem.getType()) {
<del> case SimplePageItem.ASSIGNMENT:
<del> lessonEntity = assignmentEntity.getEntity(nextItem.getSakaiId()); break;
<del> case SimplePageItem.ASSESSMENT:
<del> view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
<del> lessonEntity = quizEntity.getEntity(nextItem.getSakaiId()); break;
<del> case SimplePageItem.FORUM:
<del> lessonEntity = forumEntity.getEntity(nextItem.getSakaiId()); break;
<del> }
<del> // normally we won't send someone to an item that
<del> // isn't available. But if the current item is a test, etc, we can't
<del> // know whether the user will pass it, so we have to ask ShowItem to
<del> // to the check. We need the check to set access control appropriately
<del> // if the user has passed.
<del> if (!isItemAvailable(nextItem, nextItem.getPageId()))
<del> view.setRecheck("true");
<del> view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
<del> if (item.getType() == SimplePageItem.PAGE)
<del> view.setPath("pop"); // now on a have, have to pop it off
<del> view.viewID = ShowItemProducer.VIEW_ID;
<del> }
<del> view.setItemId(nextItem.getId());
<del> view.setBackPath("push");
<del> UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
<add> GeneralViewParameters view = new GeneralViewParameters();
<add> int itemType = nextItem.getType();
<add> if (itemType == SimplePageItem.PAGE) {
<add> view.setSendingPage(Long.valueOf(nextItem.getSakaiId()));
<add> view.viewID = ShowPageProducer.VIEW_ID;
<add> if (item.getType() == SimplePageItem.PAGE)
<add> view.setPath("next"); // page to page, just a next
<add> else
<add> view.setPath("push"); // item to page, have to push the page
<add> } else if (itemType == SimplePageItem.RESOURCE) { /// must be a same page resource
<add> view.setSendingPage(Long.valueOf(item.getPageId()));
<add> // to the check. We need the check to set access control appropriately
<add> // if the user has passed.
<add> if (!isItemAvailable(nextItem, nextItem.getPageId()))
<add> view.setRecheck("true");
<add> view.setSource(nextItem.getItemURL());
<add> view.viewID = ShowItemProducer.VIEW_ID;
<add> } else {
<add> view.setSendingPage(Long.valueOf(item.getPageId()));
<add> LessonEntity lessonEntity = null;
<add> switch (nextItem.getType()) {
<add> case SimplePageItem.ASSIGNMENT:
<add> lessonEntity = assignmentEntity.getEntity(nextItem.getSakaiId()); break;
<add> case SimplePageItem.ASSESSMENT:
<add> view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
<add> lessonEntity = quizEntity.getEntity(nextItem.getSakaiId()); break;
<add> case SimplePageItem.FORUM:
<add> lessonEntity = forumEntity.getEntity(nextItem.getSakaiId()); break;
<add> }
<add> // normally we won't send someone to an item that
<add> // isn't available. But if the current item is a test, etc, we can't
<add> // know whether the user will pass it, so we have to ask ShowItem to
<add> // to the check. We need the check to set access control appropriately
<add> // if the user has passed.
<add> if (!isItemAvailable(nextItem, nextItem.getPageId()))
<add> view.setRecheck("true");
<add> view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
<add> if (item.getType() == SimplePageItem.PAGE)
<add> view.setPath("pop"); // now on a have, have to pop it off
<add> view.viewID = ShowItemProducer.VIEW_ID;
<add> }
<add>
<add> view.setItemId(nextItem.getId());
<add> view.setBackPath("push");
<add> UIInternalLink.make(tofill, "next", messageLocator.getMessage("simplepage.next"), view);
<ide> }
<ide> }
<ide>
<ide>
<ide> public String adjustPath(String op, Long pageId, Long pageItemId, String title) {
<ide>
<del> List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
<del>
<del> // if no current path, op doesn't matter. we can just do the current page
<del> if (path == null || path.size() == 0) {
<del> PathEntry entry = new PathEntry();
<del> entry.pageId = pageId;
<del> entry.pageItemId = pageItemId;
<del> entry.title = title;
<del> path = new ArrayList<PathEntry>();
<del> path.add(entry);
<add> List<PathEntry> path = (List<PathEntry>)sessionManager.getCurrentToolSession().getAttribute(LESSONBUILDER_PATH);
<add>
<add> // if no current path, op doesn't matter. we can just do the current page
<add> if (path == null || path.size() == 0) {
<add> PathEntry entry = new PathEntry();
<add> entry.pageId = pageId;
<add> entry.pageItemId = pageItemId;
<add> entry.title = title;
<add> path = new ArrayList<PathEntry>();
<add> path.add(entry);
<ide> } else if (path.get(path.size()-1).pageId.equals(pageId)) {
<del> // nothing. we're already there. this is to prevent
<del> // oddities if we refresh the page
<add> // nothing. we're already there. this is to prevent
<add> // oddities if we refresh the page
<ide> } else if (op == null || op.equals("") || op.equals("next")) {
<del> PathEntry entry = path.get(path.size()-1); // overwrite last item
<del> entry.pageId = pageId;
<del> entry.pageItemId = pageItemId;
<del> entry.title = title;
<add> PathEntry entry = path.get(path.size()-1); // overwrite last item
<add> entry.pageId = pageId;
<add> entry.pageItemId = pageItemId;
<add> entry.title = title;
<ide> } else if (op.equals("push")) {
<del> // a subpage
<del> PathEntry entry = new PathEntry();
<del> entry.pageId = pageId;
<del> entry.pageItemId = pageItemId;
<del> entry.title = title;
<del> path.add(entry); // put it on the end
<add> // a subpage
<add> PathEntry entry = new PathEntry();
<add> entry.pageId = pageId;
<add> entry.pageItemId = pageItemId;
<add> entry.title = title;
<add> path.add(entry); // put it on the end
<ide> } else if (op.equals("pop")) {
<del> // a subpage
<del> path.remove(path.size()-1);
<add> // a subpage
<add> path.remove(path.size()-1);
<ide> } else if (op.startsWith("log")) {
<del> // set path to what was saved in the last log entry for this item
<del> // this is used for users who go directly to a page from the
<del> // main list of pages.
<del> path = new ArrayList<PathEntry>();
<del> SimplePageLogEntry logEntry = getLogEntry(pageItemId);
<del> if (logEntry != null) {
<del> String items[] = null;
<del> if (logEntry.getPath() != null)
<del> items = logEntry.getPath().split(",");
<del> if (items != null) {
<del> for(String s: items) {
<del> // don't see how this could happen, but it did
<del> if (s.trim().equals("")) {
<del> log.warn("adjustPath attempt to set invalid path: invalid item: " + op + ":" + logEntry.getPath());
<del> return null;
<del> }
<del> SimplePageItem i = findItem(Long.valueOf(s));
<del> if (i == null || i.getType() != SimplePageItem.PAGE) {
<del> log.warn("adjustPath attempt to set invalid path: invalid item: " + op);
<del> return null;
<del> }
<del> SimplePage p = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
<del> if (p == null || !currentPage.getSiteId().equals(p.getSiteId())) {
<del> log.warn("adjustPath attempt to set invalid path: invalid page: " + op);
<del> return null;
<del> }
<del> PathEntry entry = new PathEntry();
<del> entry.pageId = p.getPageId();
<del> entry.pageItemId = i.getId();
<del> entry.title = i.getName();
<del> path.add(entry);
<del> }
<del> }
<del> }
<add> // set path to what was saved in the last log entry for this item
<add> // this is used for users who go directly to a page from the
<add> // main list of pages.
<add> path = new ArrayList<PathEntry>();
<add> SimplePageLogEntry logEntry = getLogEntry(pageItemId);
<add> if (logEntry != null) {
<add> String items[] = null;
<add> if (logEntry.getPath() != null)
<add> items = logEntry.getPath().split(",");
<add> if (items != null) {
<add> for(String s: items) {
<add> // don't see how this could happen, but it did
<add> if (s.trim().equals("")) {
<add> log.warn("adjustPath attempt to set invalid path: invalid item: " + op + ":" + logEntry.getPath());
<add> return null;
<add> }
<add> SimplePageItem i = findItem(Long.valueOf(s));
<add> if (i == null || i.getType() != SimplePageItem.PAGE) {
<add> log.warn("adjustPath attempt to set invalid path: invalid item: " + op);
<add> return null;
<add> }
<add> SimplePage p = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
<add> if (p == null || !currentPage.getSiteId().equals(p.getSiteId())) {
<add> log.warn("adjustPath attempt to set invalid path: invalid page: " + op);
<add> return null;
<add> }
<add> PathEntry entry = new PathEntry();
<add> entry.pageId = p.getPageId();
<add> entry.pageItemId = i.getId();
<add> entry.title = i.getName();
<add> path.add(entry);
<add> }
<add> }
<add> }
<ide> } else {
<del> int index = Integer.valueOf(op); // better be number
<del> if (index < path.size()) {
<del> // if we're going back, this should actually
<del> // be redundant
<del> PathEntry entry = path.get(index); // back to specified item
<del> entry.pageId = pageId;
<del> entry.pageItemId = pageItemId;
<del> entry.title = title;
<del> if (index < (path.size()-1))
<del> path.subList(index+1, path.size()).clear();
<del> }
<add> int index = Integer.valueOf(op); // better be number
<add> if (index < path.size()) {
<add> // if we're going back, this should actually
<add> // be redundant
<add> PathEntry entry = path.get(index); // back to specified item
<add> entry.pageId = pageId;
<add> entry.pageItemId = pageItemId;
<add> entry.title = title;
<add> if (index < (path.size()-1))
<add> path.subList(index+1, path.size()).clear();
<add> }
<ide> }
<ide>
<ide> // have new path; set it in session variable
<ide> // and make string representation to return
<ide> String ret = null;
<ide> for (PathEntry entry: path) {
<del> String itemString = Long.toString(entry.pageItemId);
<del> if (ret == null)
<del> ret = itemString;
<del> else
<del> ret = ret + "," + itemString;
<add> String itemString = Long.toString(entry.pageItemId);
<add> if (ret == null)
<add> ret = itemString;
<add> else
<add> ret = ret + "," + itemString;
<ide> }
<ide> if (ret == null)
<del> ret = "";
<add> ret = "";
<ide> return ret;
<ide> }
<ide>
<ide> page.setTitle(pageTitle);
<ide> update(page);
<ide> }
<add>
<add> if(pageTitle != null) {
<add> pageItem.setName(pageTitle);
<add> update(pageItem);
<add> adjustPath("", pageItem.getPageId(), pageItem.getId(), pageTitle);
<add> }
<ide>
<ide> // have to do this after the page itself is updated
<ide> if (needRecompute) |
|
Java | lgpl-2.1 | a8c1205ec5bfbb27611fafc4f35ba9e2b1170fb7 | 0 | benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc | /*
* TreeTrace.java
*
* Copyright (C) 2002-2007 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.inference.model.Parameter;
import dr.inference.model.ParameterParser;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
*/
public class TreeModelParser extends AbstractXMLObjectParser {
public static final String ROOT_HEIGHT = "rootHeight";
public static final String LEAF_HEIGHT = "leafHeight";
public static final String NODE_HEIGHTS = "nodeHeights";
public static final String NODE_RATES = "nodeRates";
public static final String NODE_TRAITS = "nodeTraits";
public static final String MULTIVARIATE_TRAIT = "traitDimension";
public static final String INITIAL_VALUE = "initialValue";
public static final String ROOT_NODE = "rootNode";
public static final String INTERNAL_NODES = "internalNodes";
public static final String LEAF_NODES = "leafNodes";
public static final String FIRE_TREE_EVENTS = "fireTreeEvents";
public static final String TAXON = "taxon";
public static final String NAME = "name";
public String getParserName() {
return TreeModel.TREE_MODEL;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Tree tree = (Tree) xo.getChild(Tree.class);
TreeModel treeModel = new TreeModel(tree);
Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'");
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof XMLObject) {
XMLObject cxo = (XMLObject) xo.getChild(i);
if (cxo.getName().equals(ROOT_HEIGHT)) {
replaceParameter(cxo, treeModel.getRootHeightParameter());
} else if (cxo.getName().equals(LEAF_HEIGHT)) {
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafHeight element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon " + taxonName + " not found for leafHeight element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
replaceParameter(cxo, treeModel.getLeafHeightParameter(node));
} else if (cxo.getName().equals(NODE_HEIGHTS)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeHeights element");
}
replaceParameter(cxo, treeModel.createNodeHeightsParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_RATES)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
//if (rootNode) {
// throw new XMLParseException("root node does not have a rate parameter");
//}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeRates element");
}
replaceParameter(cxo, treeModel.createNodeRatesParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_TRAITS)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
boolean fireTreeEvents = false;
String name = "trait";
double[] initialValues = null;
int dim = 1;
if (cxo.hasAttribute(MULTIVARIATE_TRAIT)) {
dim = cxo.getIntegerAttribute(MULTIVARIATE_TRAIT);
}
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
if (cxo.hasAttribute(FIRE_TREE_EVENTS)) {
fireTreeEvents = cxo.getBooleanAttribute(FIRE_TREE_EVENTS);
}
if (cxo.hasAttribute(NAME)) {
name = cxo.getStringAttribute(NAME);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeTraits element");
}
replaceParameter(cxo, treeModel.createNodeTraitsParameter(name, dim, initialValues, rootNode, internalNodes, leafNodes, fireTreeEvents));
// AR 26 May 08: This should not be necessary - use <nodeTraits leafNodes="true"> to extract leaf trait parameters...
// } else if (cxo.getName().equals(LEAF_TRAITS)) {
//
// String name = "trait";
//
// String taxonName;
// if (cxo.hasAttribute(TAXON)) {
// taxonName = cxo.getStringAttribute(TAXON);
// } else {
// throw new XMLParseException("taxa element missing from leafTrait element in treeModel element");
// }
//
// int index = treeModel.getTaxonIndex(taxonName);
// if (index == -1) {
// throw new XMLParseException("taxon " + taxonName + " not found for leafTrait element in treeModel element");
// }
// NodeRef node = treeModel.getExternalNode(index);
//
// if (cxo.hasAttribute(NAME)) {
// name = cxo.getStringAttribute(NAME);
// }
//
// Parameter parameter = treeModel.getNodeTraitParameter(node, name);
//
// if( parameter == null )
// throw new XMLParseException("trait "+name+" not found for leafTrait element in treeModel element");
//
// replaceParameter(cxo, parameter);
// // todo This is now broken. Please fix.
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + cxo.getName());
}
} else if (xo.getChild(i) instanceof Tree) {
// do nothing - already handled
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + xo.getChildName(i) + " " + xo.getChild(i));
}
}
treeModel.setupHeightBounds();
System.err.println("done constructing treeModel");
Logger.getLogger("dr.evomodel").info(" initial tree topology = " + Tree.Utils.uniqueNewick(treeModel, treeModel.getRoot()));
return treeModel;
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "This element represents a model of the tree. The tree model includes and attributes of the nodes " +
"including the age (or <i>height</i>) and the rate of evolution at each node in the tree.";
}
public String getExample() {
return
"<!-- the tree model as special sockets for attaching parameters to various aspects of the tree -->\n" +
"<!-- The treeModel below shows the standard setup with a parameter associated with the root height -->\n" +
"<!-- a parameter associated with the internal node heights (minus the root height) and -->\n" +
"<!-- a parameter associates with all the internal node heights -->\n" +
"<!-- Notice that these parameters are overlapping -->\n" +
"<!-- The parameters are subsequently used in operators to propose changes to the tree node heights -->\n" +
"<treeModel id=\"treeModel1\">\n" +
" <tree idref=\"startingTree\"/>\n" +
" <rootHeight>\n" +
" <parameter id=\"treeModel1.rootHeight\"/>\n" +
" </rootHeight>\n" +
" <nodeHeights internalNodes=\"true\" rootNode=\"false\">\n" +
" <parameter id=\"treeModel1.internalNodeHeights\"/>\n" +
" </nodeHeights>\n" +
" <nodeHeights internalNodes=\"true\" rootNode=\"true\">\n" +
" <parameter id=\"treeModel1.allInternalNodeHeights\"/>\n" +
" </nodeHeights>\n" +
"</treeModel>";
}
public Class getReturnType() {
return TreeModel.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
new ElementRule(Tree.class),
new ElementRule(ROOT_HEIGHT, Parameter.class, "A parameter definition with id only (cannot be a reference!)", false),
new ElementRule(NODE_HEIGHTS,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root height is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node heights (minus the root) are included in the parameter"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 1, Integer.MAX_VALUE),
new ElementRule(NODE_TRAITS,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root trait is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node traits (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node traits are included in the parameter"),
AttributeRule.newIntegerRule(MULTIVARIATE_TRAIT, true, "The number of dimensions (if multivariate)"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
AttributeRule.newBooleanRule(FIRE_TREE_EVENTS, true, "Whether to fire tree events if the traits change"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
};
public Parameter getParameter(XMLObject xo) throws XMLParseException {
int paramCount = 0;
Parameter param = null;
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Parameter) {
param = (Parameter) xo.getChild(i);
paramCount += 1;
}
}
if (paramCount == 0) {
throw new XMLParseException("no parameter element in treeModel " + xo.getName() + " element");
} else if (paramCount > 1) {
throw new XMLParseException("More than one parameter element in treeModel " + xo.getName() + " element");
}
return param;
}
public void replaceParameter(XMLObject xo, Parameter newParam) throws XMLParseException {
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Parameter) {
XMLObject rxo;
Object obj = xo.getRawChild(i);
if (obj instanceof Reference) {
rxo = ((Reference) obj).getReferenceObject();
} else if (obj instanceof XMLObject) {
rxo = (XMLObject) obj;
} else {
throw new XMLParseException("object reference not available");
}
if (rxo.getChildCount() > 0) {
throw new XMLParseException("No child elements allowed in parameter element.");
}
if (rxo.hasAttribute(XMLParser.IDREF)) {
throw new XMLParseException("References to " + xo.getName() + " parameters are not allowed in treeModel.");
}
if (rxo.hasAttribute(ParameterParser.VALUE)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have values set automatically.");
}
if (rxo.hasAttribute(ParameterParser.UPPER)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
}
if (rxo.hasAttribute(ParameterParser.LOWER)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
}
if (rxo.hasAttribute(XMLParser.ID)) {
newParam.setId(rxo.getStringAttribute(XMLParser.ID));
}
rxo.setNativeObject(newParam);
return;
}
}
}
}
| src/dr/evomodel/tree/TreeModelParser.java | /*
* TreeTrace.java
*
* Copyright (C) 2002-2007 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.inference.model.Parameter;
import dr.inference.model.ParameterParser;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
*/
public class TreeModelParser extends AbstractXMLObjectParser {
public static final String ROOT_HEIGHT = "rootHeight";
public static final String LEAF_HEIGHT = "leafHeight";
public static final String NODE_HEIGHTS = "nodeHeights";
public static final String NODE_RATES = "nodeRates";
public static final String NODE_TRAITS = "nodeTraits";
public static final String MULTIVARIATE_TRAIT = "traitDimension";
public static final String INITIAL_VALUE = "initialValue";
public static final String ROOT_NODE = "rootNode";
public static final String INTERNAL_NODES = "internalNodes";
public static final String LEAF_NODES = "leafNodes";
public static final String FIRE_TREE_EVENTS = "fireTreeEvents";
public static final String TAXON = "taxon";
public static final String NAME = "name";
public String getParserName() {
return TreeModel.TREE_MODEL;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Tree tree = (Tree) xo.getChild(Tree.class);
TreeModel treeModel = new TreeModel(tree);
Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'");
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof XMLObject) {
XMLObject cxo = (XMLObject) xo.getChild(i);
if (cxo.getName().equals(ROOT_HEIGHT)) {
replaceParameter(cxo, treeModel.getRootHeightParameter());
} else if (cxo.getName().equals(LEAF_HEIGHT)) {
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafHeight element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon " + taxonName + " not found for leafHeight element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
replaceParameter(cxo, treeModel.getLeafHeightParameter(node));
} else if (cxo.getName().equals(NODE_HEIGHTS)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeHeights element");
}
replaceParameter(cxo, treeModel.createNodeHeightsParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_RATES)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
//if (rootNode) {
// throw new XMLParseException("root node does not have a rate parameter");
//}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeRates element");
}
replaceParameter(cxo, treeModel.createNodeRatesParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_TRAITS)) {
boolean rootNode = false;
boolean internalNodes = false;
boolean leafNodes = false;
boolean fireTreeEvents = false;
String name = "trait";
double[] initialValues = null;
int dim = 1;
if (cxo.hasAttribute(MULTIVARIATE_TRAIT)) {
dim = cxo.getIntegerAttribute(MULTIVARIATE_TRAIT);
}
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (cxo.hasAttribute(ROOT_NODE)) {
rootNode = cxo.getBooleanAttribute(ROOT_NODE);
}
if (cxo.hasAttribute(INTERNAL_NODES)) {
internalNodes = cxo.getBooleanAttribute(INTERNAL_NODES);
}
if (cxo.hasAttribute(LEAF_NODES)) {
leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
}
if (cxo.hasAttribute(FIRE_TREE_EVENTS)) {
fireTreeEvents = cxo.getBooleanAttribute(FIRE_TREE_EVENTS);
}
if (cxo.hasAttribute(NAME)) {
name = cxo.getStringAttribute(NAME);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeTraits element");
}
replaceParameter(cxo, treeModel.createNodeTraitsParameter(name, dim, initialValues, rootNode, internalNodes, leafNodes, fireTreeEvents));
// AR 26 May 08: This should not be necessary - use <nodeTraits leafNodes="true"> to extract leaf trait parameters...
// } else if (cxo.getName().equals(LEAF_TRAITS)) {
//
// String name = "trait";
//
// String taxonName;
// if (cxo.hasAttribute(TAXON)) {
// taxonName = cxo.getStringAttribute(TAXON);
// } else {
// throw new XMLParseException("taxa element missing from leafTrait element in treeModel element");
// }
//
// int index = treeModel.getTaxonIndex(taxonName);
// if (index == -1) {
// throw new XMLParseException("taxon " + taxonName + " not found for leafTrait element in treeModel element");
// }
// NodeRef node = treeModel.getExternalNode(index);
//
// if (cxo.hasAttribute(NAME)) {
// name = cxo.getStringAttribute(NAME);
// }
//
// Parameter parameter = treeModel.getNodeTraitParameter(node, name);
//
// if( parameter == null )
// throw new XMLParseException("trait "+name+" not found for leafTrait element in treeModel element");
//
// replaceParameter(cxo, parameter);
// // todo This is now broken. Please fix.
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + cxo.getName());
}
} else if (xo.getChild(i) instanceof Tree) {
// do nothing - already handled
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + xo.getChildName(i) + " " + xo.getChild(i));
}
}
treeModel.setupHeightBounds();
System.err.println("done constructing treeModel");
Logger.getLogger("dr.evomodel").info(" initial tree topology = " + Tree.Utils.uniqueNewick(treeModel, treeModel.getRoot()));
return treeModel;
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "This element represents a model of the tree. The tree model includes and attributes of the nodes " +
"including the age (or <i>height</i>) and the rate of evolution at each node in the tree.";
}
public String getExample() {
return
"<!-- the tree model as special sockets for attaching parameters to various aspects of the tree -->\n" +
"<!-- The treeModel below shows the standard setup with a parameter associated with the root height -->\n" +
"<!-- a parameter associated with the internal node heights (minus the root height) and -->\n" +
"<!-- a parameter associates with all the internal node heights -->\n" +
"<!-- Notice that these parameters are overlapping -->\n" +
"<!-- The parameters are subsequently used in operators to propose changes to the tree node heights -->\n" +
"<treeModel id=\"treeModel1\">\n" +
" <tree idref=\"startingTree\"/>\n" +
" <rootHeight>\n" +
" <parameter id=\"treeModel1.rootHeight\"/>\n" +
" </rootHeight>\n" +
" <nodeHeights internalNodes=\"true\" rootNode=\"false\">\n" +
" <parameter id=\"treeModel1.internalNodeHeights\"/>\n" +
" </nodeHeights>\n" +
" <nodeHeights internalNodes=\"true\" rootNode=\"true\">\n" +
" <parameter id=\"treeModel1.allInternalNodeHeights\"/>\n" +
" </nodeHeights>\n" +
"</treeModel>";
}
public Class getReturnType() {
return TreeModel.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
new ElementRule(Tree.class),
new ElementRule(ROOT_HEIGHT, Parameter.class, "A parameter definition with id only (cannot be a reference!)", false),
new ElementRule(NODE_HEIGHTS,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root height is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node heights (minus the root) are included in the parameter"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 1, Integer.MAX_VALUE),
new ElementRule(NODE_TRAITS,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root trait is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node traits (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node traits are included in the parameter"),
AttributeRule.newIntegerRule(MULTIVARIATE_TRAIT, true, "The number of dimensions (if multivariate)"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
AttributeRule.newBooleanRule(FIRE_TREE_EVENTS, true, "Whether to fire tree events if the traits change"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 1, Integer.MAX_VALUE),
};
public Parameter getParameter(XMLObject xo) throws XMLParseException {
int paramCount = 0;
Parameter param = null;
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Parameter) {
param = (Parameter) xo.getChild(i);
paramCount += 1;
}
}
if (paramCount == 0) {
throw new XMLParseException("no parameter element in treeModel " + xo.getName() + " element");
} else if (paramCount > 1) {
throw new XMLParseException("More than one parameter element in treeModel " + xo.getName() + " element");
}
return param;
}
public void replaceParameter(XMLObject xo, Parameter newParam) throws XMLParseException {
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Parameter) {
XMLObject rxo;
Object obj = xo.getRawChild(i);
if (obj instanceof Reference) {
rxo = ((Reference) obj).getReferenceObject();
} else if (obj instanceof XMLObject) {
rxo = (XMLObject) obj;
} else {
throw new XMLParseException("object reference not available");
}
if (rxo.getChildCount() > 0) {
throw new XMLParseException("No child elements allowed in parameter element.");
}
if (rxo.hasAttribute(XMLParser.IDREF)) {
throw new XMLParseException("References to " + xo.getName() + " parameters are not allowed in treeModel.");
}
if (rxo.hasAttribute(ParameterParser.VALUE)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have values set automatically.");
}
if (rxo.hasAttribute(ParameterParser.UPPER)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
}
if (rxo.hasAttribute(ParameterParser.LOWER)) {
throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
}
if (rxo.hasAttribute(XMLParser.ID)) {
newParam.setId(rxo.getStringAttribute(XMLParser.ID));
}
rxo.setNativeObject(newParam);
return;
}
}
}
}
| Made a small mistake in my last commit: Fixed a couple of parser definitions that were giving warnings of unrecognized elements (thanks, Joseph, for putting this checking in).
| src/dr/evomodel/tree/TreeModelParser.java | Made a small mistake in my last commit: Fixed a couple of parser definitions that were giving warnings of unrecognized elements (thanks, Joseph, for putting this checking in). | <ide><path>rc/dr/evomodel/tree/TreeModelParser.java
<ide> AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
<ide> AttributeRule.newBooleanRule(FIRE_TREE_EVENTS, true, "Whether to fire tree events if the traits change"),
<ide> new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
<del> }, 1, Integer.MAX_VALUE),
<add> }, 0, Integer.MAX_VALUE),
<ide> };
<ide>
<ide> public Parameter getParameter(XMLObject xo) throws XMLParseException { |
|
Java | apache-2.0 | 93cae84d8b36d015016ae04127d627ee78911354 | 0 | chengaomin/ngrinder,nanpa83/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,songeunwoo/ngrinder,chengaomin/ngrinder,nanpa83/ngrinder,naver/ngrinder,naver/ngrinder,songeunwoo/ngrinder,ropik/ngrinder,chengaomin/ngrinder,bwahn/ngrinder,SRCB-CloudPart/ngrinder,bwahn/ngrinder,nanpa83/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,GwonGisoo/ngrinder,nanpa83/ngrinder,naver/ngrinder,songeunwoo/ngrinder,naver/ngrinder,ropik/ngrinder,SRCB-CloudPart/ngrinder,nanpa83/ngrinder,SRCB-CloudPart/ngrinder,GwonGisoo/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,naver/ngrinder,ropik/ngrinder,bwahn/ngrinder,bwahn/ngrinder,SRCB-CloudPart/ngrinder,chengaomin/ngrinder,GwonGisoo/ngrinder,chengaomin/ngrinder,bwahn/ngrinder | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.agent.controller;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.apache.commons.lang.StringUtils;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.agent.service.AgentPackageService;
import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.region.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.ngrinder.common.util.CollectionUtils.newArrayList;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
/**
* Agent management controller.
*
* @author JunHo Yoon
* @since 3.1
*/
@Controller
@RequestMapping("/agent")
@PreAuthorize("hasAnyRole('A', 'S')")
public class AgentManagerController extends BaseController {
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private RegionService regionService;
@Autowired
private AgentPackageService agentPackageService;
/**
* Get the agents.
*
* @param region the region to search. If null, it returns all the attached
* agents.
* @param model model
* @return agent/list
*/
@RequestMapping({"", "/", "/list"})
public String getAll(@RequestParam(value = "region", required = false) final String region, ModelMap model) {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
model.addAttribute("agents", Collections2.filter(agents, new Predicate<AgentInfo>() {
@Override
public boolean apply(AgentInfo agentInfo) {
if (StringUtils.equals(region, "all") || StringUtils.isEmpty(region)) {
return true;
}
final String eachAgentRegion = agentInfo.getRegion();
return eachAgentRegion.startsWith(region + "_owned") || region.equals(eachAgentRegion);
}
}));
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAllVisibleRegionNames());
File agentPackage = null;
if (isClustered()) {
if (StringUtils.isNotBlank(region)) {
final String ip = regionService.getOne(region).getIp();
agentPackage = agentPackageService.createAgentPackage(ip, region, null);
}
} else {
agentPackage = agentPackageService.createAgentPackage("", "", null);
}
if (agentPackage != null) {
model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName());
}
return "agent/list";
}
/**
* Get the agent detail info for the given agent id.
*
* @param id agent id
* @param model model
* @return agent/agentDetail
*/
@RequestMapping("/{id}")
public String getOne(@PathVariable Long id, ModelMap model) {
model.addAttribute("agent", agentManagerService.getOne(id));
return "agent/detail";
}
/**
* Get the current performance of the given agent.
*
* @param id agent id
* @param ip agent ip
* @param name agent name
* @return json message
*/
@PreAuthorize("hasAnyRole('A')")
@RequestMapping("/api/{id}/state")
public HttpEntity<String> getState(@PathVariable Long id, @RequestParam String ip, @RequestParam String name) {
agentManagerService.requestShareAgentSystemDataModel(id);
return toJsonHttpEntity(agentManagerService.getAgentSystemDataModel(ip, name));
}
/**
* Get the current all agents state.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/states/", "/api/states"}, method = RequestMethod.GET)
public HttpEntity<String> getStates() {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
return toJsonHttpEntity(getAgentStatus(agents));
}
/**
* Get all agents from database.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/", "/api"}, method = RequestMethod.GET)
public HttpEntity<String> getAll() {
return toJsonHttpEntity(agentManagerService.getAllVisibleAgentInfoFromDB());
}
/**
* Get the agent for the given agent id.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public HttpEntity<String> getOne(@PathVariable("id") Long id) {
return toJsonHttpEntity(agentManagerService.getOne(id));
}
/**
* Approve an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=approve", method = RequestMethod.PUT)
public HttpEntity<String> approve(@PathVariable("id") Long id) {
agentManagerService.approve(id, true);
return successJsonHttpEntity();
}
/**
* Disapprove an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=disapprove", method = RequestMethod.PUT)
public HttpEntity<String> disapprove(@PathVariable("id") Long id) {
agentManagerService.approve(id, false);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@PathVariable("id") Long id) {
agentManagerService.stopAgent(id);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
stop(Long.parseLong(each));
}
return successJsonHttpEntity();
}
/**
* Update the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@PathVariable("id") Long id) {
agentManagerService.update(id);
return successJsonHttpEntity();
}
/**
* Send update message to agent side
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
update(Long.parseLong(each));
}
return successJsonHttpEntity();
}
private List<Map<String, Object>> getAgentStatus(List<AgentInfo> agents) {
List<Map<String, Object>> statuses = newArrayList(agents.size());
for (AgentInfo each : agents) {
Map<String, Object> result = newHashMap();
result.put("id", each.getId());
result.put("port", each.getPort());
result.put("icon", each.getState().getCategory().getIconName());
result.put("state", each.getState());
statuses.add(result);
}
return statuses;
}
}
| ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.agent.controller;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.apache.commons.lang.StringUtils;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.agent.service.AgentPackageService;
import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.region.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.ngrinder.common.util.CollectionUtils.newArrayList;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
/**
* Agent management controller.
*
* @author JunHo Yoon
* @since 3.1
*/
@Controller
@RequestMapping("/agent")
@PreAuthorize("hasAnyRole('A', 'S')")
public class AgentManagerController extends BaseController {
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private RegionService regionService;
@Autowired
private AgentPackageService agentPackageService;
/**
* Get the agents.
*
* @param region the region to search. If null, it returns all the attached
* agents.
* @param request servlet request
* @param model model
* @return agent/list
*/
@RequestMapping({"", "/", "/list"})
public String getAll(@RequestParam(value = "region", required = false) final String region, ModelMap model) {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
model.addAttribute("agents", Collections2.filter(agents, new Predicate<AgentInfo>() {
@Override
public boolean apply(AgentInfo agentInfo) {
if (StringUtils.equals(region, "all") || StringUtils.isEmpty(region)) {
return true;
}
final String eachAgentRegion = agentInfo.getRegion();
return eachAgentRegion.startsWith(region + "_owned") || region.equals(eachAgentRegion);
}
}));
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAllVisibleRegionNames());
File agentPackage = null;
if (isClustered()) {
if (StringUtils.isNotBlank(region)) {
final String ip = regionService.getOne(region).getIp();
agentPackage = agentPackageService.createAgentPackage(ip, region, null);
}
} else {
agentPackage = agentPackageService.createAgentPackage("", "", null);
}
if (agentPackage != null) {
model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName());
}
return "agent/list";
}
/**
* Get the agent detail info for the given agent id.
*
* @param id agent id
* @param model model
* @return agent/agentDetail
*/
@RequestMapping("/{id}")
public String getOne(@PathVariable Long id, ModelMap model) {
model.addAttribute("agent", agentManagerService.getOne(id));
return "agent/detail";
}
/**
* Get the current performance of the given agent.
*
* @param id agent id
* @param ip agent ip
* @param name agent name
* @return json message
*/
@PreAuthorize("hasAnyRole('A')")
@RequestMapping("/api/{id}/state")
public HttpEntity<String> getState(@PathVariable Long id, @RequestParam String ip, @RequestParam String name) {
agentManagerService.requestShareAgentSystemDataModel(id);
return toJsonHttpEntity(agentManagerService.getAgentSystemDataModel(ip, name));
}
/**
* Get the current all agents state.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/states/", "/api/states"}, method = RequestMethod.GET)
public HttpEntity<String> getStates() {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
return toJsonHttpEntity(getAgentStatus(agents));
}
/**
* Get all agents from database.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/", "/api"}, method = RequestMethod.GET)
public HttpEntity<String> getAll() {
return toJsonHttpEntity(agentManagerService.getAllVisibleAgentInfoFromDB());
}
/**
* Get the agent for the given agent id.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public HttpEntity<String> getOne(@PathVariable("id") Long id) {
return toJsonHttpEntity(agentManagerService.getOne(id));
}
/**
* Approve an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=approve", method = RequestMethod.PUT)
public HttpEntity<String> approve(@PathVariable("id") Long id) {
agentManagerService.approve(id, true);
return successJsonHttpEntity();
}
/**
* Disapprove an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=disapprove", method = RequestMethod.PUT)
public HttpEntity<String> disapprove(@PathVariable("id") Long id) {
agentManagerService.approve(id, false);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@PathVariable("id") Long id) {
agentManagerService.stopAgent(id);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
stop(Long.parseLong(each));
}
return successJsonHttpEntity();
}
/**
* Update the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@PathVariable("id") Long id) {
agentManagerService.update(id);
return successJsonHttpEntity();
}
/**
* Send update message to agent side
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
update(Long.parseLong(each));
}
return successJsonHttpEntity();
}
private List<Map<String, Object>> getAgentStatus(List<AgentInfo> agents) {
List<Map<String, Object>> statuses = newArrayList(agents.size());
for (AgentInfo each : agents) {
Map<String, Object> result = newHashMap();
result.put("id", each.getId());
result.put("port", each.getPort());
result.put("icon", each.getState().getCategory().getIconName());
result.put("state", each.getState());
statuses.add(result);
}
return statuses;
}
}
| [NGRINDER-486] Make the agent version in db updated.
| ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java | [NGRINDER-486] Make the agent version in db updated. | <ide><path>grinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java
<ide> *
<ide> * @param region the region to search. If null, it returns all the attached
<ide> * agents.
<del> * @param request servlet request
<ide> * @param model model
<ide> * @return agent/list
<ide> */ |
|
Java | epl-1.0 | 912729de13561ee380221758bb38e5fbf3ec1b8e | 0 | cwi-swat/pdb.values,cwi-swat/pdb.values,usethesource/rascal-value | package org.eclipse.imp.pdb.facts.type;
import java.util.HashMap;
import java.util.Map;
/**
* Use this class to substitute type parameters for other types.
*/
public class TypeInstantiator implements ITypeVisitor<Type> {
private final Type[] fActuals;
private int fActualIndex;
private final Map<String, Type> fBindings;
private final TypeFactory tf = TypeFactory.getInstance();
/**
* When this constructor is used the parameter types will
* be bound in order of appearance to the actual types.
*
* @param actuals an array of actual types, with equal length to the number of
* type parameters embedded in the type to be instantiated.
*/
private TypeInstantiator(Type... actuals) {
fActuals = actuals;
fBindings = new HashMap<String,Type>();
fActualIndex = 0;
}
private TypeInstantiator(Map<String, Type> bindings) {
fActuals = null;
fActualIndex = -1;
fBindings = bindings;
}
/**
* Instantiate a parameterized type with actual types
* @param abstractType the type to find embedded parameterized types in
* @param actuals the actual types to replace the parameterized types with
* @return a new type with the parameter types replaced by the given actual types.
*/
public static Type instantiate(Type abstractType, Type... actuals) {
return abstractType.accept(new TypeInstantiator(actuals));
}
public static Type instantiate(Type abstractType, Map<String, Type> bindings) {
return abstractType.accept(new TypeInstantiator(bindings));
}
public Type visitBool(BoolType boolType) {
return boolType;
}
public Type visitDouble(DoubleType type) {
return type;
}
public Type visitInteger(IntegerType type) {
return type;
}
public Type visitList(ListType type) {
return tf.listType(type.getElementType().accept(this));
}
public Type visitMap(MapType type) {
return tf.mapType(type.getKeyType().accept(this), type.getValueType().accept(this));
}
public Type visitNamed(NamedType type) {
return type;
}
public Type visitNamedTree(NamedTreeType type) {
return type;
}
public Type visitParameter(ParameterType parameterType) {
Type boundTo = fBindings.get(parameterType);
if (boundTo == null) {
if (fActuals == null) {
throw new FactTypeError("Unbound parameter type: " + parameterType);
}
else if (fActualIndex >= fActuals.length) {
throw new FactTypeError("Not enough actual types to instantiate " + parameterType);
}
boundTo = fActuals[fActualIndex++];
fBindings.put(parameterType.getName(), boundTo);
}
if (!boundTo.isSubtypeOf(parameterType.getBound())) {
throw new FactTypeError("Actual type " + boundTo + " is not a subtype of the bound " + parameterType.getBound() + " of the parameter type " + parameterType);
}
return boundTo;
}
public Type visitRelationType(RelationType type) {
return tf.relType(type.getFieldTypes().accept(this));
}
public Type visitSet(SetType type) {
return tf.setType(type.getElementType().accept(this));
}
public Type visitSourceLocation(SourceLocationType type) {
return type;
}
public Type visitSourceRange(SourceRangeType type) {
return type;
}
public Type visitString(StringType type) {
return type;
}
public Type visitTree(TreeType type) {
return type;
}
public Type visitTreeNode(TreeNodeType type) {
return tf.treeNodeType((NamedTreeType) type.getSuperType().accept(this), type.getName(), type.getChildrenTypes().accept(this));
}
public Type visitTuple(TupleType type) {
if (type.hasFieldNames()) {
Type[] fTypes = new Type[type.getArity()];
String[] fLabels = new String[type.getArity()];
for (int i = 0; i < fTypes.length; i++) {
fTypes[i] = type.getFieldType(i).accept(this);
fLabels[i] = type.getFieldName(i);
}
return tf.tupleType(fTypes, fLabels);
}
else {
Type[] fChildren = new Type[type.getArity()];
for (int i = 0; i < fChildren.length; i++) {
fChildren[i] = type.getFieldType(i).accept(this);
}
return tf.tupleType(fChildren);
}
}
public Type visitValue(ValueType type) {
return type;
}
public Type visitVoid(VoidType type) {
return type;
}
}
| src/org/eclipse/imp/pdb/facts/type/TypeInstantiator.java | package org.eclipse.imp.pdb.facts.type;
import java.util.HashMap;
import java.util.Map;
/**
* Use this class to substitute type parameters for other types.
*/
public class TypeInstantiator implements ITypeVisitor<Type> {
private final Type[] fActuals;
private int fActualIndex;
private final Map<String, Type> fBindings;
private final TypeFactory tf = TypeFactory.getInstance();
/**
* When this constructor is used the parameter types will
* be bound in order of appearance to the actual types.
*
* @param actuals an array of actual types, with equal length to the number of
* type parameters embedded in the type to be instantiated.
*/
private TypeInstantiator(Type... actuals) {
fActuals = actuals;
fBindings = new HashMap<String,Type>();
fActualIndex = 0;
}
private TypeInstantiator(Map<String, Type> bindings) {
fActuals = null;
fActualIndex = -1;
fBindings = bindings;
}
/**
* Instantiate a parameterized type with actual types
* @param abstractType the type to find embedded parameterized types in
* @param actuals the actual types to replace the parameterized types with
* @return a new type with the parameter types replaced by the given actual types.
*/
public static Type instantiate(Type abstractType, Type... actuals) {
return abstractType.accept(new TypeInstantiator(actuals));
}
public static Type instantiate(Type abstractType, Map<String, Type> bindings) {
return abstractType.accept(new TypeInstantiator(bindings));
}
public Type visitBool(BoolType boolType) {
return boolType;
}
public Type visitDouble(DoubleType type) {
return type;
}
public Type visitInteger(IntegerType type) {
return type;
}
public Type visitList(ListType type) {
return tf.listType(type.getElementType().accept(this));
}
public Type visitMap(MapType type) {
return tf.mapType(type.getKeyType().accept(this), type.getValueType().accept(this));
}
public Type visitNamed(NamedType type) {
return type;
}
public Type visitNamedTree(NamedTreeType type) {
return type;
}
public Type visitParameter(ParameterType parameterType) {
Type boundTo = fBindings.get(parameterType);
if (boundTo == null) {
if (fActuals == null) {
throw new FactTypeError("Unbound parameter type: " + parameterType);
}
else if (fActualIndex >= fActuals.length) {
throw new FactTypeError("Not enough actual types to instantiate " + parameterType);
}
boundTo = fActuals[fActualIndex++];
fBindings.put(parameterType.getName(), boundTo);
}
if (!boundTo.isSubtypeOf(parameterType.getBound())) {
throw new FactTypeError("Actual type " + boundTo + " is not a subtype of the bound " + parameterType.getBound() + " of the parameter type " + parameterType);
}
return boundTo;
}
public Type visitRelationType(RelationType type) {
return tf.relType(type.getFieldTypes().accept(this));
}
public Type visitSet(SetType type) {
return tf.setType(type.getElementType().accept(this));
}
public Type visitSourceLocation(SourceLocationType type) {
return type;
}
public Type visitSourceRange(SourceRangeType type) {
return type;
}
public Type visitString(StringType type) {
return type;
}
public Type visitTree(TreeType type) {
return type;
}
public Type visitTreeNode(TreeNodeType type) {
return tf.treeNodeType((NamedTreeType) type.getSuperType().accept(this), type.getName(), type.getChildrenTypes().accept(this));
}
public Type visitTuple(TupleType type) {
if (type.hasFieldNames()) {
Object[] fChildren = new Type[2 * type.getArity()];
for (int i = 0, j = 0; i < fChildren.length; i++, j++) {
fChildren[i++] = type.getFieldType(j).accept(this);
fChildren[i] = type.getFieldName(i);
}
return tf.tupleType(fChildren);
}
else {
Type[] fChildren = new Type[type.getArity()];
for (int i = 0; i < fChildren.length; i++) {
fChildren[i] = type.getFieldType(i).accept(this);
}
return tf.tupleType(fChildren);
}
}
public Type visitValue(ValueType type) {
return type;
}
public Type visitVoid(VoidType type) {
return type;
}
}
| slight simplification of implementation of visitTuple
| src/org/eclipse/imp/pdb/facts/type/TypeInstantiator.java | slight simplification of implementation of visitTuple | <ide><path>rc/org/eclipse/imp/pdb/facts/type/TypeInstantiator.java
<ide>
<ide> public Type visitTuple(TupleType type) {
<ide> if (type.hasFieldNames()) {
<del> Object[] fChildren = new Type[2 * type.getArity()];
<del>
<del> for (int i = 0, j = 0; i < fChildren.length; i++, j++) {
<del> fChildren[i++] = type.getFieldType(j).accept(this);
<del> fChildren[i] = type.getFieldName(i);
<del> }
<del>
<del> return tf.tupleType(fChildren);
<add> Type[] fTypes = new Type[type.getArity()];
<add> String[] fLabels = new String[type.getArity()];
<add>
<add> for (int i = 0; i < fTypes.length; i++) {
<add> fTypes[i] = type.getFieldType(i).accept(this);
<add> fLabels[i] = type.getFieldName(i);
<add> }
<add>
<add> return tf.tupleType(fTypes, fLabels);
<ide> }
<ide> else {
<ide> Type[] fChildren = new Type[type.getArity()];
<ide> for (int i = 0; i < fChildren.length; i++) {
<ide> fChildren[i] = type.getFieldType(i).accept(this);
<ide> }
<del>
<add>
<ide> return tf.tupleType(fChildren);
<ide> }
<ide> } |
|
Java | apache-2.0 | 9d29089d98fe8af02c8ce0923d07d879366aa489 | 0 | kageiit/buck,Addepar/buck,JoelMarcey/buck,facebook/buck,facebook/buck,JoelMarcey/buck,JoelMarcey/buck,nguyentruongtho/buck,JoelMarcey/buck,facebook/buck,nguyentruongtho/buck,facebook/buck,JoelMarcey/buck,JoelMarcey/buck,kageiit/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,JoelMarcey/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,facebook/buck,nguyentruongtho/buck,nguyentruongtho/buck,Addepar/buck,nguyentruongtho/buck,kageiit/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,kageiit/buck,kageiit/buck,Addepar/buck,JoelMarcey/buck,JoelMarcey/buck,Addepar/buck,Addepar/buck,kageiit/buck,nguyentruongtho/buck,Addepar/buck,facebook/buck,Addepar/buck,Addepar/buck,facebook/buck | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.parser.spec;
import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.cell.name.CanonicalCellName;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.CellRelativePath;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.parser.buildtargetpattern.BuildTargetLanguageConstants;
import com.facebook.buck.core.parser.buildtargetpattern.BuildTargetPattern;
import com.facebook.buck.core.parser.buildtargetpattern.ImmutableBuildTargetPattern;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.google.common.collect.ImmutableMap;
/** Matches all {@link TargetNode} objects in a repository that match the specification. */
@BuckStyleValue
public abstract class TargetNodePredicateSpec implements TargetNodeSpec {
@Override
public abstract BuildFileSpec getBuildFileSpec();
public abstract boolean onlyTests();
@Override
public TargetType getTargetType() {
return TargetType.MULTIPLE_TARGETS;
}
@Override
public ImmutableMap<BuildTarget, TargetNode<?>> filter(Iterable<TargetNode<?>> nodes) {
ImmutableMap.Builder<BuildTarget, TargetNode<?>> resultBuilder = ImmutableMap.builder();
for (TargetNode<?> node : nodes) {
if (!onlyTests() || node.getRuleType().isTestRule()) {
resultBuilder.put(node.getBuildTarget(), node);
}
}
return resultBuilder.build();
}
@Override
public BuildTargetPattern getBuildTargetPattern(Cell cell) {
BuildFileSpec buildFileSpec = getBuildFileSpec();
if (!cell.getCanonicalName().equals(buildFileSpec.getCellRelativeBaseName().getCellName())) {
throw new IllegalArgumentException(
String.format(
"%s: Root of cell should agree with build file spec: %s vs %s",
toString(), cell.getRoot(), buildFileSpec.getCellRelativeBaseName().getCellName()));
}
CanonicalCellName cellName = cell.getCanonicalName();
ForwardRelativePath basePath = buildFileSpec.getCellRelativeBaseName().getPath();
return ImmutableBuildTargetPattern.of(
CellRelativePath.of(cellName, basePath),
buildFileSpec.isRecursive()
? BuildTargetPattern.Kind.RECURSIVE
: BuildTargetPattern.Kind.PACKAGE,
"");
}
public static TargetNodePredicateSpec of(BuildFileSpec buildFileSpec) {
return of(buildFileSpec, false);
}
public static TargetNodePredicateSpec of(BuildFileSpec buildFileSpec, boolean onlyTests) {
return ImmutableTargetNodePredicateSpec.of(buildFileSpec, onlyTests);
}
@Override
public String toString() {
StringBuilder builder =
new StringBuilder(getBuildFileSpec().getCellRelativeBaseName().toString());
if (getBuildFileSpec().isRecursive()) {
builder
.append(BuildTargetLanguageConstants.PATH_SYMBOL)
.append(BuildTargetLanguageConstants.RECURSIVE_SYMBOL);
} else {
builder.append(BuildTargetLanguageConstants.TARGET_SYMBOL);
}
return builder.toString();
}
}
| src/com/facebook/buck/parser/spec/TargetNodePredicateSpec.java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.parser.spec;
import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.cell.name.CanonicalCellName;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.CellRelativePath;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.parser.buildtargetpattern.BuildTargetPattern;
import com.facebook.buck.core.parser.buildtargetpattern.ImmutableBuildTargetPattern;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.google.common.collect.ImmutableMap;
/** Matches all {@link TargetNode} objects in a repository that match the specification. */
@BuckStyleValue
public abstract class TargetNodePredicateSpec implements TargetNodeSpec {
@Override
public abstract BuildFileSpec getBuildFileSpec();
public abstract boolean onlyTests();
@Override
public TargetType getTargetType() {
return TargetType.MULTIPLE_TARGETS;
}
@Override
public ImmutableMap<BuildTarget, TargetNode<?>> filter(Iterable<TargetNode<?>> nodes) {
ImmutableMap.Builder<BuildTarget, TargetNode<?>> resultBuilder = ImmutableMap.builder();
for (TargetNode<?> node : nodes) {
if (!onlyTests() || node.getRuleType().isTestRule()) {
resultBuilder.put(node.getBuildTarget(), node);
}
}
return resultBuilder.build();
}
@Override
public BuildTargetPattern getBuildTargetPattern(Cell cell) {
BuildFileSpec buildFileSpec = getBuildFileSpec();
if (!cell.getCanonicalName().equals(buildFileSpec.getCellRelativeBaseName().getCellName())) {
throw new IllegalArgumentException(
String.format(
"%s: Root of cell should agree with build file spec: %s vs %s",
toString(), cell.getRoot(), buildFileSpec.getCellRelativeBaseName().getCellName()));
}
CanonicalCellName cellName = cell.getCanonicalName();
ForwardRelativePath basePath = buildFileSpec.getCellRelativeBaseName().getPath();
return ImmutableBuildTargetPattern.of(
CellRelativePath.of(cellName, basePath),
buildFileSpec.isRecursive()
? BuildTargetPattern.Kind.RECURSIVE
: BuildTargetPattern.Kind.PACKAGE,
"");
}
public static TargetNodePredicateSpec of(BuildFileSpec buildFileSpec) {
return of(buildFileSpec, false);
}
public static TargetNodePredicateSpec of(BuildFileSpec buildFileSpec, boolean onlyTests) {
return ImmutableTargetNodePredicateSpec.of(buildFileSpec, onlyTests);
}
}
| Add toString to TargetNodePredicateSpec
Summary: TargetNodePredicateSpec's default toString could lead to ugly messages before. Update this.
Reviewed By: rajyengi
shipit-source-id: 49d20a4ea542d77e2ec090084a2690f7ec3f8d19
| src/com/facebook/buck/parser/spec/TargetNodePredicateSpec.java | Add toString to TargetNodePredicateSpec | <ide><path>rc/com/facebook/buck/parser/spec/TargetNodePredicateSpec.java
<ide> import com.facebook.buck.core.model.BuildTarget;
<ide> import com.facebook.buck.core.model.CellRelativePath;
<ide> import com.facebook.buck.core.model.targetgraph.TargetNode;
<add>import com.facebook.buck.core.parser.buildtargetpattern.BuildTargetLanguageConstants;
<ide> import com.facebook.buck.core.parser.buildtargetpattern.BuildTargetPattern;
<ide> import com.facebook.buck.core.parser.buildtargetpattern.ImmutableBuildTargetPattern;
<ide> import com.facebook.buck.core.path.ForwardRelativePath;
<ide> public static TargetNodePredicateSpec of(BuildFileSpec buildFileSpec, boolean onlyTests) {
<ide> return ImmutableTargetNodePredicateSpec.of(buildFileSpec, onlyTests);
<ide> }
<add>
<add> @Override
<add> public String toString() {
<add> StringBuilder builder =
<add> new StringBuilder(getBuildFileSpec().getCellRelativeBaseName().toString());
<add> if (getBuildFileSpec().isRecursive()) {
<add> builder
<add> .append(BuildTargetLanguageConstants.PATH_SYMBOL)
<add> .append(BuildTargetLanguageConstants.RECURSIVE_SYMBOL);
<add> } else {
<add> builder.append(BuildTargetLanguageConstants.TARGET_SYMBOL);
<add> }
<add> return builder.toString();
<add> }
<ide> } |
|
Java | apache-2.0 | cb45b336201ea749e0c2d776353bedfa622bfc2f | 0 | jmrozanec/cron-utils,meincs/cron-utils | package com.cronutils.model.time;
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
import org.threeten.bp.*;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.cronutils.model.CronType.QUARTZ;
import static org.junit.Assert.*;
import static org.threeten.bp.ZoneOffset.UTC;
/*
* Copyright 2015 jmrozanec
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class ExecutionTimeQuartzIntegrationTest {
private CronParser parser;
private static final String EVERY_SECOND = "* * * * * ? *";
@Before
public void setUp() throws Exception {
parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
}
@Test
public void testForCron() throws Exception {
assertEquals(ExecutionTime.class, ExecutionTime.forCron(parser.parse(EVERY_SECOND)).getClass());
}
@Test
public void testNextExecutionEverySecond() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.plusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(expected, executionTime.nextExecution(now).get());
}
@Test
public void testTimeToNextExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.plusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(Duration.between(now, expected), executionTime.timeToNextExecution(now).get());
}
@Test
public void testLastExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.minusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(expected, executionTime.lastExecution(now).get());
}
@Test
public void testTimeFromLastExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.minusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(Duration.between(expected, now), executionTime.timeToNextExecution(now).get());
}
/**
* Test for issue #9
* https://github.com/jmrozanec/cron-utils/issues/9
* Reported case: If you write a cron expression that contains a month or day of week, nextExection() ignores it.
* Expected: should not ignore month or day of week field
*/
@Test
public void testDoesNotIgnoreMonthOrDayOfWeek(){
//seconds, minutes, hours, dayOfMonth, month, dayOfWeek
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 11 11 11 11 ?"));
ZonedDateTime now = ZonedDateTime.of(2015, 4, 15, 0, 0, 0, 0, UTC);
ZonedDateTime whenToExecuteNext = executionTime.nextExecution(now).get();
assertEquals(2015, whenToExecuteNext.getYear());
assertEquals(11, whenToExecuteNext.getMonthValue());
assertEquals(11, whenToExecuteNext.getDayOfMonth());
assertEquals(11, whenToExecuteNext.getHour());
assertEquals(11, whenToExecuteNext.getMinute());
assertEquals(0, whenToExecuteNext.getSecond());
}
/**
* Test for issue #18
* @throws Exception
*/
@Test
public void testHourlyIntervalTimeFromLastExecution() throws Exception {
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime previousHour = now.minusHours(1);
String quartzCronExpression = String.format("0 0 %s * * ?", previousHour.getHour());
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(quartzCronExpression));
assertTrue(executionTime.timeFromLastExecution(now).get().toMinutes() <= 120);
}
/**
* Test for issue #19
* https://github.com/jmrozanec/cron-utils/issues/19
* Reported case: When nextExecution shifts to the 24th hour (e.g. 23:59:59 + 00:00:01), JodaTime will throw an exception
* Expected: should shift one day
*/
@Test
public void testShiftTo24thHour() {
String expression = "0/1 * * 1/1 * ? *"; // every second every day
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
ZonedDateTime now = ZonedDateTime.of(LocalDate.of(2016, 8, 5), LocalTime.of(23, 59, 59, 0), UTC);
ZonedDateTime expected = now.plusSeconds(1);
ZonedDateTime nextExecution = executionTime.nextExecution(now).get();
assertEquals(expected, nextExecution);
}
/**
* Test for issue #19
* https://github.com/jmrozanec/cron-utils/issues/19
* Reported case: When nextExecution shifts to 32nd day (e.g. 2015-01-31 23:59:59 + 00:00:01), JodaTime will throw an exception
* Expected: should shift one month
*/
@Test
public void testShiftTo32ndDay() {
String expression = "0/1 * * 1/1 * ? *"; // every second every day
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
ZonedDateTime now = ZonedDateTime.of(2015, 1, 31, 23, 59, 59, 0, UTC);
ZonedDateTime expected = now.plusSeconds(1);
ZonedDateTime nextExecution = executionTime.nextExecution(now).get();
assertEquals(expected, nextExecution);
}
/**
* Issue #24: next execution not properly calculated
*/
@Test
public void testTimeShiftingProperlyDone() throws Exception {
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0/10 22 ? * *"));
ZonedDateTime nextExecution = executionTime.nextExecution(ZonedDateTime.now().withHour(15).withMinute(27)).get();
assertEquals(22, nextExecution.getHour());
assertEquals(0, nextExecution.getMinute());
}
/**
* Issue #27: execution time properly calculated
*/
@Test
public void testMonthRangeExecutionTime(){
assertNotNull(ExecutionTime.forCron(parser.parse("0 0 0 * JUL-AUG ? *")));
}
/**
* Issue #30: execution time properly calculated
*/
@Test
public void testSaturdayExecutionTime(){
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0 3 ? * 6"));
ZonedDateTime last = executionTime.lastExecution(now).get();
ZonedDateTime next = executionTime.nextExecution(now).get();
assertNotEquals(last, next);
}
/**
* Issue: execution time properly calculated
*/
@Test
public void testWeekdayExecutionTime(){
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0 3 ? * *"));
ZonedDateTime last = executionTime.lastExecution(now).get();
ZonedDateTime next = executionTime.nextExecution(now).get();
assertNotEquals(last, next);
}
/**
* Issue #64: Incorrect next execution time for ranges
*/
@Test
public void testExecutionTimeForRanges(){
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* 10-20 * * * ? 2099"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-02-29T11:00:00.000-06:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(10, nextTime.getMinute());
}
/**
* Issue #65: Incorrect last execution time for fixed month
*/
@Test
public void testLastExecutionTimeForFixedMonth(){
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 30 12 1 9 ? 2010"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-01-08T11:00:00.000-06:00");
ZonedDateTime lastTime = executionTime.lastExecution(scanTime).get();
assertNotNull(lastTime);
assertEquals(9, lastTime.getMonthValue());
}
/**
* Issue #66: Incorrect Day Of Week processing for Quartz when Month or Year isn't '*'.
*/
@Test
public void testNextExecutionRightDoWForFixedMonth(){
//cron format: s,m,H,DoM,M,DoW,Y
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 * * ? 5 1 *"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-03-06T20:17:28.000-03:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(DayOfWeek.SUNDAY, nextTime.getDayOfWeek());
}
/**
* Issue #66: Incorrect Day Of Week processing for Quartz when Month or Year isn't '*'.
*/
@Test
public void testNextExecutionRightDoWForFixedYear(){
//cron format: s,m,H,DoM,M,DoW,Y
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 * * ? * 1 2099"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-03-06T20:17:28.000-03:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(DayOfWeek.SUNDAY, nextTime.getDayOfWeek());
}
/**
* Issue #70: Illegal question mark value on cron pattern assumed valid.
*/
@Test(expected = IllegalArgumentException.class)
public void testIllegalQuestionMarkValue(){
ExecutionTime.forCron(parser.parse("0 0 12 1W ? *"));//s,m,H,DoM,M,DoW
}
/**
* Issue #72: Stacktrace printed.
* TODO: Although test is passing, there is some stacktrace printed indicating there may be something wrong.
* TODO: We should analyze it and fix the eventual issue.
*/
@Test//TODO
public void testNextExecutionProducingInvalidPrintln(){
String cronText = "0 0/15 * * * ?";
Cron cron = parser.parse(cronText);
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
}
/**
* Issue #73: NextExecution not working as expected
*/
@Test
public void testNextExecutionProducingInvalidValues(){
String cronText = "0 0 18 ? * MON";
Cron cron = parser.parse(cronText);
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.parse("2016-03-18T19:02:51.424+09:00");
ZonedDateTime next = executionTime.nextExecution(now).get();
ZonedDateTime nextNext = executionTime.nextExecution(next).get();
assertEquals(DayOfWeek.MONDAY, next.getDayOfWeek());
assertEquals(DayOfWeek.MONDAY, nextNext.getDayOfWeek());
assertEquals(18, next.getHour());
assertEquals(18, nextNext.getHour());
}
/**
* Test for issue #83
* https://github.com/jmrozanec/cron-utils/issues/83
* Reported case: Candidate values are false when combining range and multiple patterns
* Expected: Candidate values should be correctly identified
* @throws Exception
*/
@Test
public void testMultipleMinuteIntervalTimeFromLastExecution() {
String expression = "* 8-10,23-25,38-40,53-55 * * * ? *"; // every second for intervals of minutes
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
assertEquals(301, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(3, 1, 0, 0), UTC)).get().getSeconds());
assertEquals(1, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 8, 4, 0), UTC)).get().getSeconds());
assertEquals(1, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 11, 0, 0), UTC)).get().getSeconds());
assertEquals(63, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 12, 2, 0), UTC)).get().getSeconds());
}
/**
* Test for issue #83
* https://github.com/jmrozanec/cron-utils/issues/83
* Reported case: Candidate values are false when combining range and multiple patterns
* Expected: Candidate values should be correctly identified
* @throws Exception
*/
@Test
public void testMultipleMinuteIntervalMatch() {
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 20, 0, 0, 0, UTC)), false);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 21, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 0, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 4, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 5, 0, 0, 0, UTC)), false);
}
@Test
public void testDayLightSavingsSwitch() {
//every 2 minutes
String expression = "* 0/2 * * * ?";
Cron cron = parser.parse(expression);
// SIMULATE SCHEDULE JUST PRIOR TO DST
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd HH:mm:ss")
.withZone(ZoneId.of("America/Denver"));
ZonedDateTime prevRun = ZonedDateTime.parse("2016 03 13 01:59:59", formatter);
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime nextRun = executionTime.nextExecution(prevRun).get();
// Assert we got 3:00am
assertEquals("Incorrect Hour", 3, nextRun.getHour());
assertEquals("Incorrect Minute", 0, nextRun.getMinute());
// SIMULATE SCHEDULE POST DST - simulate a schedule after DST 3:01 with the same cron, expect 3:02
nextRun = nextRun.plusMinutes(1);
nextRun = executionTime.nextExecution(nextRun).get();
assertEquals("Incorrect Hour", 3, nextRun.getHour());
assertEquals("Incorrect Minute", 2, nextRun.getMinute());
// SIMULATE SCHEDULE NEXT DAY DST - verify after midnight on DST switch things still work as expected
prevRun = ZonedDateTime.parse("2016-03-14T00:00:59Z");
nextRun = executionTime.nextExecution(prevRun).get();
assertEquals("incorrect hour", nextRun.getHour(), 0);
assertEquals("incorrect minute", nextRun.getMinute(), 2);
}
@Test
public void bigNumbersOnDayOfMonthField(){
Cron cron = parser.parse("0 0 0 31 * ?");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 11, 1, 0, 0, 0, 0, ZoneId.of("UTC"));
//nextRun expected to be 2016-12-31 00:00:00 000
//quartz-2.2.3 return the right date
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 12, 31, 0, 0, 0, 0, ZoneId.of("UTC")), nextRun);
}
@Test
public void noSpecificDayOfMonthEvaluatedOnLastDay() {
Cron cron = parser.parse("0 * * ? * *");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 8, 31, 10, 10, 0,0,ZoneId.of("UTC"));
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 8, 31, 10, 11, 0, 0, ZoneId.of("UTC")), nextRun);
}
/**
* Issue #75: W flag not behaving as expected: did not return first workday of month, but an exception
*/
@Test
public void testCronWithFirstWorkDayOfWeek() {
String cronText = "0 0 12 1W * ? *";
Cron cron = parser.parse(cronText);
ZonedDateTime dt = ZonedDateTime.parse("2016-03-29T00:00:59Z");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime nextRun = executionTime.nextExecution(dt).get();
assertEquals("incorrect Day", nextRun.getDayOfMonth(), 1); // should be April 1st (Friday)
}
/**
* Issue #81: MON-SUN flags are not mapped correctly to 1-7 number representations
* Fixed by adding shifting function when changing monday position.
*/
@Test
public void testDayOfWeekMapping() {
ZonedDateTime fridayMorning = ZonedDateTime.of(2016, 4, 22, 0, 0, 0, 0, UTC);
ExecutionTime numberExec = ExecutionTime.forCron(parser.parse("0 0 12 ? * 2,3,4,5,6 *"));
ExecutionTime nameExec = ExecutionTime.forCron(parser.parse("0 0 12 ? * MON,TUE,WED,THU,FRI *"));
assertEquals("same generated dates", numberExec.nextExecution(fridayMorning),
nameExec.nextExecution(fridayMorning));
}
/**
* Issue #91: Calculating the minimum interval for a cron expression.
*/
@Test
public void testMinimumInterval() {
Duration s1 = Duration.ofSeconds(1);
assertEquals(getMinimumInterval("* * * * * ?"), s1);
assertEquals("Should ignore whitespace", getMinimumInterval("* * * * * ?"), s1);
assertEquals(getMinimumInterval("0/1 * * * * ?"), s1);
assertEquals(getMinimumInterval("*/1 * * * * ?"), s1);
Duration s60 = Duration.ofSeconds(60);
assertEquals(getMinimumInterval("0 * * * * ?"), s60);
assertEquals(getMinimumInterval("0 */1 * * * ?"), s60);
assertEquals(getMinimumInterval("0 */5 * * * ?"), Duration.ofSeconds(300));
assertEquals(getMinimumInterval("0 0 * * * ?"), Duration.ofSeconds(3600));
assertEquals(getMinimumInterval("0 0 */3 * * ?"), Duration.ofSeconds(10800));
assertEquals(getMinimumInterval("0 0 0 * * ?"), Duration.ofSeconds(86400));
}
/**
* Issue #110: DateTimeException thrown from ExecutionTime.nextExecution
*/
@Test
public void noDateTimeExceptionIsThrownGeneratingNextExecutionWithDayOfWeekFilters() {
ZonedDateTime wednesdayNov9 = ZonedDateTime.of(2016, 11, 9, 1, 1, 0, 0, ZoneId.of("UTC"));
ZonedDateTime startOfThursdayNov10 = wednesdayNov9.plusDays(1).truncatedTo(ChronoUnit.DAYS);
ZonedDateTime thursdayOct27 = ZonedDateTime.of(2016, 10, 27, 23, 55, 0, 0, ZoneId.of("UTC"));
String[] cronExpressionsExcludingWednesdayAndIncludingThursday = {
// Non-range type day-of-week filters function as expected...
"0 0/1 * ? * 5",
"0 0/1 * ? * 2,5",
"0 0/1 * ? * THU",
"0 0/1 * ? * THU,SAT",
/* Range-based day-of-week filters are consitently broken. Exception thrown:
* DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 0
*/
"0 0/1 * ? * 5-6",
"0 0/1 * ? * THU-FRI"
};
for(String cronExpression : cronExpressionsExcludingWednesdayAndIncludingThursday) {
assertExpectedNextExecution(cronExpression, wednesdayNov9, startOfThursdayNov10);
assertExpectedNextExecution(cronExpression, thursdayOct27, thursdayOct27.plusMinutes(1));
}
ZonedDateTime endOfThursdayNov3 = ZonedDateTime.of(2016, 11, 3, 23, 59, 0, 0, ZoneId.of("UTC"));
ZonedDateTime endOfFridayNov4 = endOfThursdayNov3.plusDays(1);
ZonedDateTime endOfSaturdayNov5 = endOfThursdayNov3.plusDays(2);
ZonedDateTime endOfMondayNov7 = endOfThursdayNov3.plusDays(4);
assertExpectedNextExecution("0 0/1 * ? * 5", endOfThursdayNov3, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * 2,5", endOfMondayNov7, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * THU", endOfThursdayNov3, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * THU,SAT", endOfSaturdayNov5, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * 5-6", endOfFridayNov4, startOfThursdayNov10); //110
assertExpectedNextExecution("0 0/1 * ? * THU-FRI", endOfFridayNov4, startOfThursdayNov10); //110
}
/**
* Issue #114: Describe day of week is incorrect
*/
@Test
public void descriptionForExpressionTellsWrongDoW(){
//CronDescriptor descriptor = CronDescriptor.instance();
//Cron quartzCron = parser.parse("0 0 8 ? * SUN *");
//TODO enable: assertEquals("at 08:00 at Sunday day", descriptor.describe(quartzCron));
}
/**
* Issue #117: Last Day of month Skipped on Quartz Expression: 0 * * ? * *
*/
@Test
public void noSpecificDayOfMonth() {
Cron cron = parser.parse("0 * * ? * *");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 8, 30, 23, 59, 0,0,ZoneId.of("UTC"));
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 8, 31, 0, 0, 0,0, ZoneId.of("UTC")), nextRun);
}
/**
* Issue #123:
* https://github.com/jmrozanec/cron-utils/issues/123
* Reported case: next execution time is set improperly
* Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/124
*/
@Test
public void testNextExecutionTimeProperlySet(){
CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
String quartzCronExpression2 = "0 5/15 * * * ? *";
Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);
ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);
ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 7, 30, 15, 0, 0, 527).atZone(ZoneOffset.UTC);
ZonedDateTime nextExecution = executionTime.nextExecution(zonedDateTime).get();
ZonedDateTime lastExecution = executionTime.lastExecution(zonedDateTime).get();
assertEquals("2016-07-30T14:50Z", lastExecution.toString());
assertEquals("2016-07-30T15:05Z", nextExecution.toString());
}
/**
* Issue #124:
* https://github.com/jmrozanec/cron-utils/issues/124
* Reported case: next execution time is set improperly
* Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/123
*/
@Test
public void testNextExecutionTimeProperlySet2(){
CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
String quartzCronExpression2 = "0 3/27 10-14 * * ? *";
Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);
ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);
ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 1, 1, 10, 0, 0, 0).atZone(ZoneOffset.UTC);
ZonedDateTime nextExecution = executionTime.nextExecution(zonedDateTime).get();
assertEquals("2016-01-01T10:03Z", nextExecution.toString());
}
/**
* Issue #133:
* https://github.com/jmrozanec/cron-utils/issues/133
* Reported case: QUARTZ cron definition: 31 not supported on the day-of-month field
*/
@Test
public void validate31IsSupportedForDoM(){
parser.parse("0 0 0 31 * ?");
}
/**
* Issue #136: Bug exposed at PR #136
* https://github.com/jmrozanec/cron-utils/pull/136
* Reported case: when executing isMatch for a given range of dates,
* if date is invalid, we get an exception, not a boolean as response.
*/
@Test
public void validateIsMatchForRangeOfDates(){
Cron cron = parser.parse("* * * 05 05 ? 2004");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime start = ZonedDateTime.of(2004, 5, 5, 23, 55, 0, 0, ZoneId.of("UTC"));
ZonedDateTime end = ZonedDateTime.of(2004, 5, 6, 1, 0, 0, 0, ZoneId.of("UTC"));
while(start.compareTo(end)<0){
executionTime.isMatch(start);
start = start.plusMinutes(1);
}
}
/**
* Issue #140: https://github.com/jmrozanec/cron-utils/pull/140
* IllegalArgumentException: Values must not be empty
*/
@Test
public void nextExecutionNotFail(){
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDefinition);
Cron parsed = parser.parse("0 0 10 ? * SAT-SUN");
ExecutionTime executionTime = ExecutionTime.forCron(parsed);
Optional<ZonedDateTime> next = executionTime.nextExecution(ZonedDateTime.now());
}
/**
* Issue #142: https://github.com/jmrozanec/cron-utils/pull/142
* Special Character L for day of week behaves differently in Quartz
*/
@Test
public void lastDayOfTheWeek() throws Exception {
Cron cron = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ)).parse("0 0 0 L * ? *");
ZoneId utc = ZoneId.of("UTC");
ZonedDateTime date = LocalDate.parse("2016-12-22").atStartOfDay(utc);
ZonedDateTime cronUtilsNextTime = ExecutionTime.forCron(cron).nextExecution(date).get();// 2016-12-30T00:00:00Z
org.quartz.CronExpression cronExpression = new org.quartz.CronExpression(cron.asString());
cronExpression.setTimeZone(DateTimeUtils.toTimeZone(utc));
Date quartzNextTime = cronExpression.getNextValidTimeAfter(DateTimeUtils.toDate(date.toInstant()));// 2016-12-24T00:00:00Z
assertEquals(DateTimeUtils.toInstant(quartzNextTime), cronUtilsNextTime.toInstant()); // false
}
/**
* Issue #143: https://github.com/jmrozanec/cron-utils/pull/143
* ExecutionTime.lastExecution() throws Exception when cron defines at 31 Dec
*/
@Test
public void lastExecutionDec31NotFail(){
CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime et = ExecutionTime.forCron(parser.parse("0 0 12 31 12 ? *"));
System.out.println(et.lastExecution(ZonedDateTime.now()));
}
/**
* Issue #144
* https://github.com/jmrozanec/cron-utils/issues/144
* Reported case: periodic incremental hours does not start and end
* at beginning and end of given period
*/
// @Test//TODO
public void testPeriodicIncrementalHoursIgnorePeriodBounds() {
Cron cron = parser.parse("0 0 16-19/2 * * ?");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime start = ZonedDateTime.of(2016, 12, 27, 8, 15, 0, 0, ZoneId.of("UTC"));
ZonedDateTime[] expected = new ZonedDateTime[]{
ZonedDateTime.of(2016, 12, 27, 16, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 27, 18, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 28, 16, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 28, 18, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 29, 16, 0, 0, 0, ZoneId.of("UTC")),
};
List<ZonedDateTime> actualList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
ZonedDateTime next = executionTime.nextExecution(start).get();
start = next;
actualList.add(next);
}
Object[] actual = actualList.toArray();
assertArrayEquals(expected, actual);
}
/**
* Issue #153
* https://github.com/jmrozanec/cron-utils/issues/153
* Reported case: executionTime.nextExecution fails to find when current month does not have desired day
*/
@Test
public void mustJumpToNextMonthIfCurrentMonthDoesNotHaveDesiredDay() {
CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 8 31 * ?" ) );//8:00 on every 31th of Month
ZonedDateTime start = ZonedDateTime.of(2017, 04, 10, 0, 0, 0, 0, ZoneId.systemDefault() );
ZonedDateTime next = executionTime.nextExecution(start).get();
ZonedDateTime expected = ZonedDateTime.of(2017, 05, 31, 8, 0, 0, 0, ZoneId.systemDefault() );
assertEquals( expected, next );
}
/**
* Issue #153
* https://github.com/jmrozanec/cron-utils/issues/153
* Reported case: executionTime.nextExecution fails to find when current month does not have desired day
*/
@Test
public void mustJumpToEndOfMonthIfCurrentMonthHasDesiredDay() {
CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 8 31 * ?" ) );//8:00 on every 31th of Month
ZonedDateTime start = ZonedDateTime.of( 2017, 01, 10, 0, 0, 0, 0, ZoneId.systemDefault() );
ZonedDateTime next = executionTime.nextExecution(start).get();
ZonedDateTime expected = ZonedDateTime.of( 2017, 01, 31, 8, 0, 0, 0, ZoneId.systemDefault() );
assertEquals( expected, next );
}
@Test //#192
public void mustMatchLowerBoundDateMatchingCronExpressionRequirements() {
CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ZonedDateTime start = ZonedDateTime.of( 2017, 01, 1, 0, 0, 0, 0, ZoneId.systemDefault() );
ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 0 1 * ?" ) ); // every 1st of Month 1970-2099
ExecutionTime constraintExecutionTime = ExecutionTime.forCron( parser.parse( "0 0 0 1 * ? 2017" ) ); // every 1st of Month for 2017
assertEquals("year constraint shouldn't have an impact on next execution", executionTime.nextExecution(start.minusSeconds(1)), constraintExecutionTime.nextExecution(start.minusSeconds(1)));
assertEquals("year constraint shouldn't have an impact on match result", executionTime.isMatch(start), constraintExecutionTime.isMatch(start));
}
private Duration getMinimumInterval(String quartzPattern) {
ExecutionTime et = ExecutionTime.forCron(parser.parse(quartzPattern));
ZonedDateTime coolDay = ZonedDateTime.of(2016, 1, 1, 0, 0, 0, 0, UTC);
// Find next execution time #1
ZonedDateTime t1 = et.nextExecution(coolDay).get();
// Find next execution time #2 right after #1, the interval between them is minimum
return et.timeToNextExecution(t1).get();
}
private ZonedDateTime truncateToSeconds(ZonedDateTime dateTime){
return dateTime.truncatedTo(ChronoUnit.SECONDS);
}
private void assertExpectedNextExecution(String cronExpression, ZonedDateTime lastRun,
ZonedDateTime expectedNextRun) {
String testCaseDescription = "cron expression '" + cronExpression + "' with zdt " + lastRun;
System.out.println("TESTING: " + testCaseDescription);
CronDefinition cronDef = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDef);
Cron cron = parser.parse(cronExpression);
ExecutionTime executionTime = ExecutionTime.forCron(cron);
try {
ZonedDateTime nextRun = executionTime.nextExecution(lastRun).get();
assertEquals(testCaseDescription, expectedNextRun, nextRun);
}
catch(DateTimeException e) {
fail("Issue #110: " + testCaseDescription + " led to " + e);
}
}
}
| src/test/java/com/cronutils/model/time/ExecutionTimeQuartzIntegrationTest.java | package com.cronutils.model.time;
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
import org.threeten.bp.*;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.cronutils.model.CronType.QUARTZ;
import static org.junit.Assert.*;
import static org.threeten.bp.ZoneOffset.UTC;
/*
* Copyright 2015 jmrozanec
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class ExecutionTimeQuartzIntegrationTest {
private CronParser parser;
private static final String EVERY_SECOND = "* * * * * ? *";
@Before
public void setUp() throws Exception {
parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
}
@Test
public void testForCron() throws Exception {
assertEquals(ExecutionTime.class, ExecutionTime.forCron(parser.parse(EVERY_SECOND)).getClass());
}
@Test
public void testNextExecutionEverySecond() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.plusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(expected, executionTime.nextExecution(now).get());
}
@Test
public void testTimeToNextExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.plusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(Duration.between(now, expected), executionTime.timeToNextExecution(now).get());
}
@Test
public void testLastExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.minusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(expected, executionTime.lastExecution(now).get());
}
@Test
public void testTimeFromLastExecution() throws Exception {
ZonedDateTime now = truncateToSeconds(ZonedDateTime.now());
ZonedDateTime expected = truncateToSeconds(now.minusSeconds(1));
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(EVERY_SECOND));
assertEquals(Duration.between(expected, now), executionTime.timeToNextExecution(now).get());
}
/**
* Test for issue #9
* https://github.com/jmrozanec/cron-utils/issues/9
* Reported case: If you write a cron expression that contains a month or day of week, nextExection() ignores it.
* Expected: should not ignore month or day of week field
*/
@Test
public void testDoesNotIgnoreMonthOrDayOfWeek(){
//seconds, minutes, hours, dayOfMonth, month, dayOfWeek
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 11 11 11 11 ?"));
ZonedDateTime now = ZonedDateTime.of(2015, 4, 15, 0, 0, 0, 0, UTC);
ZonedDateTime whenToExecuteNext = executionTime.nextExecution(now).get();
assertEquals(2015, whenToExecuteNext.getYear());
assertEquals(11, whenToExecuteNext.getMonthValue());
assertEquals(11, whenToExecuteNext.getDayOfMonth());
assertEquals(11, whenToExecuteNext.getHour());
assertEquals(11, whenToExecuteNext.getMinute());
assertEquals(0, whenToExecuteNext.getSecond());
}
/**
* Test for issue #18
* @throws Exception
*/
@Test
public void testHourlyIntervalTimeFromLastExecution() throws Exception {
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime previousHour = now.minusHours(1);
String quartzCronExpression = String.format("0 0 %s * * ?", previousHour.getHour());
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(quartzCronExpression));
assertTrue(executionTime.timeFromLastExecution(now).get().toMinutes() <= 120);
}
/**
* Test for issue #19
* https://github.com/jmrozanec/cron-utils/issues/19
* Reported case: When nextExecution shifts to the 24th hour (e.g. 23:59:59 + 00:00:01), JodaTime will throw an exception
* Expected: should shift one day
*/
@Test
public void testShiftTo24thHour() {
String expression = "0/1 * * 1/1 * ? *"; // every second every day
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
ZonedDateTime now = ZonedDateTime.of(LocalDate.of(2016, 8, 5), LocalTime.of(23, 59, 59, 0), UTC);
ZonedDateTime expected = now.plusSeconds(1);
ZonedDateTime nextExecution = executionTime.nextExecution(now).get();
assertEquals(expected, nextExecution);
}
/**
* Test for issue #19
* https://github.com/jmrozanec/cron-utils/issues/19
* Reported case: When nextExecution shifts to 32nd day (e.g. 2015-01-31 23:59:59 + 00:00:01), JodaTime will throw an exception
* Expected: should shift one month
*/
@Test
public void testShiftTo32ndDay() {
String expression = "0/1 * * 1/1 * ? *"; // every second every day
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
ZonedDateTime now = ZonedDateTime.of(2015, 1, 31, 23, 59, 59, 0, UTC);
ZonedDateTime expected = now.plusSeconds(1);
ZonedDateTime nextExecution = executionTime.nextExecution(now).get();
assertEquals(expected, nextExecution);
}
/**
* Issue #24: next execution not properly calculated
*/
@Test
public void testTimeShiftingProperlyDone() throws Exception {
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0/10 22 ? * *"));
ZonedDateTime nextExecution = executionTime.nextExecution(ZonedDateTime.now().withHour(15).withMinute(27)).get();
assertEquals(22, nextExecution.getHour());
assertEquals(0, nextExecution.getMinute());
}
/**
* Issue #27: execution time properly calculated
*/
@Test
public void testMonthRangeExecutionTime(){
assertNotNull(ExecutionTime.forCron(parser.parse("0 0 0 * JUL-AUG ? *")));
}
/**
* Issue #30: execution time properly calculated
*/
@Test
public void testSaturdayExecutionTime(){
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0 3 ? * 6"));
ZonedDateTime last = executionTime.lastExecution(now).get();
ZonedDateTime next = executionTime.nextExecution(now).get();
assertNotEquals(last, next);
}
/**
* Issue: execution time properly calculated
*/
@Test
public void testWeekdayExecutionTime(){
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0 3 ? * *"));
ZonedDateTime last = executionTime.lastExecution(now).get();
ZonedDateTime next = executionTime.nextExecution(now).get();
assertNotEquals(last, next);
}
/**
* Issue #64: Incorrect next execution time for ranges
*/
@Test
public void testExecutionTimeForRanges(){
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* 10-20 * * * ? 2099"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-02-29T11:00:00.000-06:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(10, nextTime.getMinute());
}
/**
* Issue #65: Incorrect last execution time for fixed month
*/
@Test
public void testLastExecutionTimeForFixedMonth(){
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 30 12 1 9 ? 2010"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-01-08T11:00:00.000-06:00");
ZonedDateTime lastTime = executionTime.lastExecution(scanTime).get();
assertNotNull(lastTime);
assertEquals(9, lastTime.getMonthValue());
}
/**
* Issue #66: Incorrect Day Of Week processing for Quartz when Month or Year isn't '*'.
*/
@Test
public void testNextExecutionRightDoWForFixedMonth(){
//cron format: s,m,H,DoM,M,DoW,Y
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 * * ? 5 1 *"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-03-06T20:17:28.000-03:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(DayOfWeek.SUNDAY, nextTime.getDayOfWeek());
}
/**
* Issue #66: Incorrect Day Of Week processing for Quartz when Month or Year isn't '*'.
*/
@Test
public void testNextExecutionRightDoWForFixedYear(){
//cron format: s,m,H,DoM,M,DoW,Y
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 * * ? * 1 2099"));
ZonedDateTime scanTime = ZonedDateTime.parse("2016-03-06T20:17:28.000-03:00");
ZonedDateTime nextTime = executionTime.nextExecution(scanTime).get();
assertNotNull(nextTime);
assertEquals(DayOfWeek.SUNDAY, nextTime.getDayOfWeek());
}
/**
* Issue #70: Illegal question mark value on cron pattern assumed valid.
*/
@Test(expected = IllegalArgumentException.class)
public void testIllegalQuestionMarkValue(){
ExecutionTime.forCron(parser.parse("0 0 12 1W ? *"));//s,m,H,DoM,M,DoW
}
/**
* Issue #72: Stacktrace printed.
* TODO: Although test is passing, there is some stacktrace printed indicating there may be something wrong.
* TODO: We should analyze it and fix the eventual issue.
*/
@Test//TODO
public void testNextExecutionProducingInvalidPrintln(){
String cronText = "0 0/15 * * * ?";
Cron cron = parser.parse(cronText);
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
}
/**
* Issue #73: NextExecution not working as expected
*/
@Test
public void testNextExecutionProducingInvalidValues(){
String cronText = "0 0 18 ? * MON";
Cron cron = parser.parse(cronText);
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.parse("2016-03-18T19:02:51.424+09:00");
ZonedDateTime next = executionTime.nextExecution(now).get();
ZonedDateTime nextNext = executionTime.nextExecution(next).get();
assertEquals(DayOfWeek.MONDAY, next.getDayOfWeek());
assertEquals(DayOfWeek.MONDAY, nextNext.getDayOfWeek());
assertEquals(18, next.getHour());
assertEquals(18, nextNext.getHour());
}
/**
* Test for issue #83
* https://github.com/jmrozanec/cron-utils/issues/83
* Reported case: Candidate values are false when combining range and multiple patterns
* Expected: Candidate values should be correctly identified
* @throws Exception
*/
@Test
public void testMultipleMinuteIntervalTimeFromLastExecution() {
String expression = "* 8-10,23-25,38-40,53-55 * * * ? *"; // every second for intervals of minutes
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(expression));
assertEquals(301, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(3, 1, 0, 0), UTC)).get().getSeconds());
assertEquals(1, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 8, 4, 0), UTC)).get().getSeconds());
assertEquals(1, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 11, 0, 0), UTC)).get().getSeconds());
assertEquals(63, executionTime.timeFromLastExecution(ZonedDateTime.of(LocalDate.now(), LocalTime.of(13, 12, 2, 0), UTC)).get().getSeconds());
}
/**
* Test for issue #83
* https://github.com/jmrozanec/cron-utils/issues/83
* Reported case: Candidate values are false when combining range and multiple patterns
* Expected: Candidate values should be correctly identified
* @throws Exception
*/
@Test
public void testMultipleMinuteIntervalMatch() {
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 20, 0, 0, 0, UTC)), false);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 21, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 0, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 4, 0, 0, 0, UTC)), true);
assertEquals(ExecutionTime.forCron(parser.parse("* * 21-23,0-4 * * ?")).isMatch(ZonedDateTime.of(2014, 9, 20, 5, 0, 0, 0, UTC)), false);
}
@Test
public void testDayLightSavingsSwitch() {
//every 2 minutes
String expression = "* 0/2 * * * ?";
Cron cron = parser.parse(expression);
// SIMULATE SCHEDULE JUST PRIOR TO DST
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd HH:mm:ss")
.withZone(ZoneId.of("America/Denver"));
ZonedDateTime prevRun = ZonedDateTime.parse("2016 03 13 01:59:59", formatter);
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime nextRun = executionTime.nextExecution(prevRun).get();
// Assert we got 3:00am
assertEquals("Incorrect Hour", 3, nextRun.getHour());
assertEquals("Incorrect Minute", 0, nextRun.getMinute());
// SIMULATE SCHEDULE POST DST - simulate a schedule after DST 3:01 with the same cron, expect 3:02
nextRun = nextRun.plusMinutes(1);
nextRun = executionTime.nextExecution(nextRun).get();
assertEquals("Incorrect Hour", 3, nextRun.getHour());
assertEquals("Incorrect Minute", 2, nextRun.getMinute());
// SIMULATE SCHEDULE NEXT DAY DST - verify after midnight on DST switch things still work as expected
prevRun = ZonedDateTime.parse("2016-03-14T00:00:59Z");
nextRun = executionTime.nextExecution(prevRun).get();
assertEquals("incorrect hour", nextRun.getHour(), 0);
assertEquals("incorrect minute", nextRun.getMinute(), 2);
}
@Test
public void bigNumbersOnDayOfMonthField(){
Cron cron = parser.parse("0 0 0 31 * ?");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 11, 1, 0, 0, 0, 0, ZoneId.of("UTC"));
//nextRun expected to be 2016-12-31 00:00:00 000
//quartz-2.2.3 return the right date
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 12, 31, 0, 0, 0, 0, ZoneId.of("UTC")), nextRun);
}
@Test
public void noSpecificDayOfMonthEvaluatedOnLastDay() {
Cron cron = parser.parse("0 * * ? * *");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 8, 31, 10, 10, 0,0,ZoneId.of("UTC"));
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 8, 31, 10, 11, 0, 0, ZoneId.of("UTC")), nextRun);
}
/**
* Issue #75: W flag not behaving as expected: did not return first workday of month, but an exception
*/
@Test
public void testCronWithFirstWorkDayOfWeek() {
String cronText = "0 0 12 1W * ? *";
Cron cron = parser.parse(cronText);
ZonedDateTime dt = ZonedDateTime.parse("2016-03-29T00:00:59Z");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime nextRun = executionTime.nextExecution(dt).get();
assertEquals("incorrect Day", nextRun.getDayOfMonth(), 1); // should be April 1st (Friday)
}
/**
* Issue #81: MON-SUN flags are not mapped correctly to 1-7 number representations
* Fixed by adding shifting function when changing monday position.
*/
@Test
public void testDayOfWeekMapping() {
ZonedDateTime fridayMorning = ZonedDateTime.of(2016, 4, 22, 0, 0, 0, 0, UTC);
ExecutionTime numberExec = ExecutionTime.forCron(parser.parse("0 0 12 ? * 2,3,4,5,6 *"));
ExecutionTime nameExec = ExecutionTime.forCron(parser.parse("0 0 12 ? * MON,TUE,WED,THU,FRI *"));
assertEquals("same generated dates", numberExec.nextExecution(fridayMorning),
nameExec.nextExecution(fridayMorning));
}
/**
* Issue #91: Calculating the minimum interval for a cron expression.
*/
@Test
public void testMinimumInterval() {
Duration s1 = Duration.ofSeconds(1);
assertEquals(getMinimumInterval("* * * * * ?"), s1);
assertEquals("Should ignore whitespace", getMinimumInterval("* * * * * ?"), s1);
assertEquals(getMinimumInterval("0/1 * * * * ?"), s1);
assertEquals(getMinimumInterval("*/1 * * * * ?"), s1);
Duration s60 = Duration.ofSeconds(60);
assertEquals(getMinimumInterval("0 * * * * ?"), s60);
assertEquals(getMinimumInterval("0 */1 * * * ?"), s60);
assertEquals(getMinimumInterval("0 */5 * * * ?"), Duration.ofSeconds(300));
assertEquals(getMinimumInterval("0 0 * * * ?"), Duration.ofSeconds(3600));
assertEquals(getMinimumInterval("0 0 */3 * * ?"), Duration.ofSeconds(10800));
assertEquals(getMinimumInterval("0 0 0 * * ?"), Duration.ofSeconds(86400));
}
/**
* Issue #110: DateTimeException thrown from ExecutionTime.nextExecution
*/
@Test
public void noDateTimeExceptionIsThrownGeneratingNextExecutionWithDayOfWeekFilters() {
ZonedDateTime wednesdayNov9 = ZonedDateTime.of(2016, 11, 9, 1, 1, 0, 0, ZoneId.of("UTC"));
ZonedDateTime startOfThursdayNov10 = wednesdayNov9.plusDays(1).truncatedTo(ChronoUnit.DAYS);
ZonedDateTime thursdayOct27 = ZonedDateTime.of(2016, 10, 27, 23, 55, 0, 0, ZoneId.of("UTC"));
String[] cronExpressionsExcludingWednesdayAndIncludingThursday = {
// Non-range type day-of-week filters function as expected...
"0 0/1 * ? * 5",
"0 0/1 * ? * 2,5",
"0 0/1 * ? * THU",
"0 0/1 * ? * THU,SAT",
/* Range-based day-of-week filters are consitently broken. Exception thrown:
* DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 0
*/
"0 0/1 * ? * 5-6",
"0 0/1 * ? * THU-FRI"
};
for(String cronExpression : cronExpressionsExcludingWednesdayAndIncludingThursday) {
assertExpectedNextExecution(cronExpression, wednesdayNov9, startOfThursdayNov10);
assertExpectedNextExecution(cronExpression, thursdayOct27, thursdayOct27.plusMinutes(1));
}
ZonedDateTime endOfThursdayNov3 = ZonedDateTime.of(2016, 11, 3, 23, 59, 0, 0, ZoneId.of("UTC"));
ZonedDateTime endOfFridayNov4 = endOfThursdayNov3.plusDays(1);
ZonedDateTime endOfSaturdayNov5 = endOfThursdayNov3.plusDays(2);
ZonedDateTime endOfMondayNov7 = endOfThursdayNov3.plusDays(4);
assertExpectedNextExecution("0 0/1 * ? * 5", endOfThursdayNov3, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * 2,5", endOfMondayNov7, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * THU", endOfThursdayNov3, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * THU,SAT", endOfSaturdayNov5, startOfThursdayNov10);
assertExpectedNextExecution("0 0/1 * ? * 5-6", endOfFridayNov4, startOfThursdayNov10); //110
assertExpectedNextExecution("0 0/1 * ? * THU-FRI", endOfFridayNov4, startOfThursdayNov10); //110
}
/**
* Issue #114: Describe day of week is incorrect
*/
@Test
public void descriptionForExpressionTellsWrongDoW(){
//CronDescriptor descriptor = CronDescriptor.instance();
//Cron quartzCron = parser.parse("0 0 8 ? * SUN *");
//TODO enable: assertEquals("at 08:00 at Sunday day", descriptor.describe(quartzCron));
}
/**
* Issue #117: Last Day of month Skipped on Quartz Expression: 0 * * ? * *
*/
@Test
public void noSpecificDayOfMonth() {
Cron cron = parser.parse("0 * * ? * *");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime now = ZonedDateTime.of(2016, 8, 30, 23, 59, 0,0,ZoneId.of("UTC"));
ZonedDateTime nextRun = executionTime.nextExecution(now).get();
assertEquals(ZonedDateTime.of(2016, 8, 31, 0, 0, 0,0, ZoneId.of("UTC")), nextRun);
}
/**
* Issue #123:
* https://github.com/jmrozanec/cron-utils/issues/123
* Reported case: next execution time is set improperly
* Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/124
*/
@Test
public void testNextExecutionTimeProperlySet(){
CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
String quartzCronExpression2 = "0 5/15 * * * ? *";
Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);
ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);
ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 7, 30, 15, 0, 0, 527).atZone(ZoneOffset.UTC);
ZonedDateTime nextExecution = executionTime.nextExecution(zonedDateTime).get();
ZonedDateTime lastExecution = executionTime.lastExecution(zonedDateTime).get();
assertEquals("2016-07-30T14:50Z", lastExecution.toString());
assertEquals("2016-07-30T15:05Z", nextExecution.toString());
}
/**
* Issue #124:
* https://github.com/jmrozanec/cron-utils/issues/124
* Reported case: next execution time is set improperly
* Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/123
*/
@Test
public void testNextExecutionTimeProperlySet2(){
CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
String quartzCronExpression2 = "0 3/27 10-14 * * ? *";
Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);
ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);
ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 1, 1, 10, 0, 0, 0).atZone(ZoneOffset.UTC);
ZonedDateTime nextExecution = executionTime.nextExecution(zonedDateTime).get();
assertEquals("2016-01-01T10:03Z", nextExecution.toString());
}
/**
* Issue #133:
* https://github.com/jmrozanec/cron-utils/issues/133
* Reported case: QUARTZ cron definition: 31 not supported on the day-of-month field
*/
@Test
public void validate31IsSupportedForDoM(){
parser.parse("0 0 0 31 * ?");
}
/**
* Issue #136: Bug exposed at PR #136
* https://github.com/jmrozanec/cron-utils/pull/136
* Reported case: when executing isMatch for a given range of dates,
* if date is invalid, we get an exception, not a boolean as response.
*/
@Test
public void validateIsMatchForRangeOfDates(){
Cron cron = parser.parse("* * * 05 05 ? 2004");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime start = ZonedDateTime.of(2004, 5, 5, 23, 55, 0, 0, ZoneId.of("UTC"));
ZonedDateTime end = ZonedDateTime.of(2004, 5, 6, 1, 0, 0, 0, ZoneId.of("UTC"));
while(start.compareTo(end)<0){
executionTime.isMatch(start);
start = start.plusMinutes(1);
}
}
/**
* Issue #140: https://github.com/jmrozanec/cron-utils/pull/140
* IllegalArgumentException: Values must not be empty
*/
@Test
public void nextExecutionNotFail(){
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDefinition);
Cron parsed = parser.parse("0 0 10 ? * SAT-SUN");
ExecutionTime executionTime = ExecutionTime.forCron(parsed);
Optional<ZonedDateTime> next = executionTime.nextExecution(ZonedDateTime.now());
}
/**
* Issue #142: https://github.com/jmrozanec/cron-utils/pull/142
* Special Character L for day of week behaves differently in Quartz
*/
@Test
public void lastDayOfTheWeek() throws Exception {
Cron cron = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ)).parse("0 0 0 L * ? *");
ZoneId utc = ZoneId.of("UTC");
ZonedDateTime date = LocalDate.parse("2016-12-22").atStartOfDay(utc);
ZonedDateTime cronUtilsNextTime = ExecutionTime.forCron(cron).nextExecution(date).get();// 2016-12-30T00:00:00Z
org.quartz.CronExpression cronExpression = new org.quartz.CronExpression(cron.asString());
cronExpression.setTimeZone(DateTimeUtils.toTimeZone(utc));
Date quartzNextTime = cronExpression.getNextValidTimeAfter(DateTimeUtils.toDate(date.toInstant()));// 2016-12-24T00:00:00Z
assertEquals(DateTimeUtils.toInstant(quartzNextTime), cronUtilsNextTime.toInstant()); // false
}
/**
* Issue #143: https://github.com/jmrozanec/cron-utils/pull/143
* ExecutionTime.lastExecution() throws Exception when cron defines at 31 Dec
*/
@Test
public void lastExecutionDec31NotFail(){
CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime et = ExecutionTime.forCron(parser.parse("0 0 12 31 12 ? *"));
System.out.println(et.lastExecution(ZonedDateTime.now()));
}
/**
* Issue #144
* https://github.com/jmrozanec/cron-utils/issues/144
* Reported case: periodic incremental hours does not start and end
* at beginning and end of given period
*/
// @Test//TODO
public void testPeriodicIncrementalHoursIgnorePeriodBounds() {
Cron cron = parser.parse("0 0 16-19/2 * * ?");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime start = ZonedDateTime.of(2016, 12, 27, 8, 15, 0, 0, ZoneId.of("UTC"));
ZonedDateTime[] expected = new ZonedDateTime[]{
ZonedDateTime.of(2016, 12, 27, 16, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 27, 18, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 28, 16, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 28, 18, 0, 0, 0, ZoneId.of("UTC")),
ZonedDateTime.of(2016, 12, 29, 16, 0, 0, 0, ZoneId.of("UTC")),
};
List<ZonedDateTime> actualList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
ZonedDateTime next = executionTime.nextExecution(start).get();
start = next;
actualList.add(next);
}
Object[] actual = actualList.toArray();
assertArrayEquals(expected, actual);
}
/**
* Issue #153
* https://github.com/jmrozanec/cron-utils/issues/153
* Reported case: executionTime.nextExecution fails to find when current month does not have desired day
*/
@Test
public void mustJumpToNextMonthIfCurrentMonthDoesNotHaveDesiredDay() {
CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 8 31 * ?" ) );//8:00 on every 31th of Month
ZonedDateTime start = ZonedDateTime.of(2017, 04, 10, 0, 0, 0, 0, ZoneId.systemDefault() );
ZonedDateTime next = executionTime.nextExecution(start).get();
ZonedDateTime expected = ZonedDateTime.of(2017, 05, 31, 8, 0, 0, 0, ZoneId.systemDefault() );
assertEquals( expected, next );
}
/**
* Issue #153
* https://github.com/jmrozanec/cron-utils/issues/153
* Reported case: executionTime.nextExecution fails to find when current month does not have desired day
*/
@Test
public void mustJumpToEndOfMonthIfCurrentMonthHasDesiredDay() {
CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 8 31 * ?" ) );//8:00 on every 31th of Month
ZonedDateTime start = ZonedDateTime.of( 2017, 01, 10, 0, 0, 0, 0, ZoneId.systemDefault() );
ZonedDateTime next = executionTime.nextExecution(start).get();
ZonedDateTime expected = ZonedDateTime.of( 2017, 01, 31, 8, 0, 0, 0, ZoneId.systemDefault() );
assertEquals( expected, next );
}
private Duration getMinimumInterval(String quartzPattern) {
ExecutionTime et = ExecutionTime.forCron(parser.parse(quartzPattern));
ZonedDateTime coolDay = ZonedDateTime.of(2016, 1, 1, 0, 0, 0, 0, UTC);
// Find next execution time #1
ZonedDateTime t1 = et.nextExecution(coolDay).get();
// Find next execution time #2 right after #1, the interval between them is minimum
return et.timeToNextExecution(t1).get();
}
private ZonedDateTime truncateToSeconds(ZonedDateTime dateTime){
return dateTime.truncatedTo(ChronoUnit.SECONDS);
}
private void assertExpectedNextExecution(String cronExpression, ZonedDateTime lastRun,
ZonedDateTime expectedNextRun) {
String testCaseDescription = "cron expression '" + cronExpression + "' with zdt " + lastRun;
System.out.println("TESTING: " + testCaseDescription);
CronDefinition cronDef = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDef);
Cron cron = parser.parse(cronExpression);
ExecutionTime executionTime = ExecutionTime.forCron(cron);
try {
ZonedDateTime nextRun = executionTime.nextExecution(lastRun).get();
assertEquals(testCaseDescription, expectedNextRun, nextRun);
}
catch(DateTimeException e) {
fail("Issue #110: " + testCaseDescription + " led to " + e);
}
}
}
| added test mustMatchLowerBoundDateMatchingCronExpressionRequirements for
issue #192 | src/test/java/com/cronutils/model/time/ExecutionTimeQuartzIntegrationTest.java | added test mustMatchLowerBoundDateMatchingCronExpressionRequirements for issue #192 | <ide><path>rc/test/java/com/cronutils/model/time/ExecutionTimeQuartzIntegrationTest.java
<ide> ZonedDateTime expected = ZonedDateTime.of( 2017, 01, 31, 8, 0, 0, 0, ZoneId.systemDefault() );
<ide> assertEquals( expected, next );
<ide> }
<add>
<add> @Test //#192
<add> public void mustMatchLowerBoundDateMatchingCronExpressionRequirements() {
<add> CronParser parser = new CronParser( CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
<add> ZonedDateTime start = ZonedDateTime.of( 2017, 01, 1, 0, 0, 0, 0, ZoneId.systemDefault() );
<add> ExecutionTime executionTime = ExecutionTime.forCron( parser.parse( "0 0 0 1 * ?" ) ); // every 1st of Month 1970-2099
<add> ExecutionTime constraintExecutionTime = ExecutionTime.forCron( parser.parse( "0 0 0 1 * ? 2017" ) ); // every 1st of Month for 2017
<add> assertEquals("year constraint shouldn't have an impact on next execution", executionTime.nextExecution(start.minusSeconds(1)), constraintExecutionTime.nextExecution(start.minusSeconds(1)));
<add> assertEquals("year constraint shouldn't have an impact on match result", executionTime.isMatch(start), constraintExecutionTime.isMatch(start));
<add> }
<ide>
<ide> private Duration getMinimumInterval(String quartzPattern) {
<ide> ExecutionTime et = ExecutionTime.forCron(parser.parse(quartzPattern)); |
|
JavaScript | unlicense | 1b035e1ea9cf34a47b83877f8670e618dd7ebc51 | 0 | FredericHeem/starhackit,FredericHeem/starhackit,FredericHeem/starhackit,FredericHeem/starhackit | import Debug from 'debug';
let debug = new Debug("intl");
import {Promise} from 'es6-promise';
export default function(language = 'en'){
debug(language);
return new Promise((resolve) => {
if (!window.Intl) {
// Safari only
debug("fetch intl");
require.ensure([
], function(require) {
require('intl');
require(`intl/locale-data/jsonp/en.js`);
//require(`intl/locale-data/jsonp/ru.js`);
//require(`intl/locale-data/jsonp/de.js`);
//require(`intl/locale-data/jsonp/fr.js`);
resolve();
});
} else {
resolve();
}
});
};
| client/src/app/utils/intl.js | import Debug from 'debug';
let debug = new Debug("intl");
import {Promise} from 'es6-promise';
export default function(language = 'en'){
debug(language);
return new Promise((resolve) => {
if (!window.Intl) {
// Safari only
debug("fetch intl");
require.ensure([
'intl', `intl/locale-data/jsonp/${language}.js`
], function(require) {
require('intl');
require(`intl/locale-data/jsonp/${language}.js`);
resolve();
});
} else {
resolve();
}
});
};
| remove webpack warning about intl
| client/src/app/utils/intl.js | remove webpack warning about intl | <ide><path>lient/src/app/utils/intl.js
<ide> // Safari only
<ide> debug("fetch intl");
<ide> require.ensure([
<del> 'intl', `intl/locale-data/jsonp/${language}.js`
<ide> ], function(require) {
<ide> require('intl');
<del> require(`intl/locale-data/jsonp/${language}.js`);
<add> require(`intl/locale-data/jsonp/en.js`);
<add> //require(`intl/locale-data/jsonp/ru.js`);
<add> //require(`intl/locale-data/jsonp/de.js`);
<add> //require(`intl/locale-data/jsonp/fr.js`);
<ide> resolve();
<ide> });
<ide> } else { |
|
Java | lgpl-2.1 | abbff351c14a9711a03c9d0057de49a3aa4363ff | 0 | lucee/Lucee,lucee/Lucee,lucee/Lucee,lucee/Lucee | /**
* Copyright (c) 2014, the Railo Company Ltd.
* Copyright (c) 2015, Lucee Assosication Switzerland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.runtime.type.scope;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lucee.commons.lang.CFTypes;
import lucee.runtime.PageContext;
import lucee.runtime.config.NullSupportHelper;
import lucee.runtime.dump.DumpData;
import lucee.runtime.dump.DumpProperties;
import lucee.runtime.dump.DumpTable;
import lucee.runtime.dump.DumpUtil;
import lucee.runtime.dump.SimpleDumpData;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageRuntimeException;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.ArrayPro;
import lucee.runtime.type.Collection;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Null;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.it.EntryArrayIterator;
import lucee.runtime.type.util.CollectionUtil;
import lucee.runtime.type.util.MemberUtil;
import lucee.runtime.type.wrap.ArrayAsList;
/**
* implementation of the argument scope
*/
public final class ArgumentImpl extends ScopeSupport implements Argument, ArrayPro {
private static final long serialVersionUID = 4346997451403177136L;
private boolean bind;
private Set functionArgumentNames;
// private boolean supportFunctionArguments;
/**
* constructor of the class
*/
public ArgumentImpl() {
super("arguments", SCOPE_ARGUMENTS, Struct.TYPE_LINKED);
// this(true);
}
@Override
public void release(PageContext pc) {
functionArgumentNames = null;
super.release(ThreadLocalPageContext.get(pc));
}
@Override
public void setBind(boolean bind) {
this.bind = bind;
}
@Override
public boolean isBind() {
return this.bind;
}
@Override
public Object getFunctionArgument(String key, Object defaultValue) {
return getFunctionArgument(KeyImpl.getInstance(key), defaultValue);
}
@Override
public Object getFunctionArgument(Collection.Key key, Object defaultValue) {
return super.get(key, defaultValue);
}
@Override
public boolean containsFunctionArgumentKey(Key key) {
return super.containsKey(key);// functionArgumentNames!=null && functionArgumentNames.contains(key);
}
@Override
public Object get(Collection.Key key, Object defaultValue) {
/*
* if(NullSupportHelper.full()) { Object o=super.get(key,NullSupportHelper.NULL());
* if(o!=NullSupportHelper.NULL())return o;
*
* o=get(Caster.toIntValue(key.getString(),-1),NullSupportHelper.NULL());
* if(o!=NullSupportHelper.NULL())return o; return defaultValue; }
*/
Object o = super.g(key, Null.NULL);
if (o != Null.NULL) return o;
if (key.length() > 0) {
char c = key.charAt(0);
if ((c >= '0' && c <= '9') || c == '+') {
o = get(Caster.toIntValue(key.getString(), -1), Null.NULL);
if (o != Null.NULL) return o;
}
}
return defaultValue;
}
@Override
public Object get(Collection.Key key) throws ExpressionException {
// null is supported as returned value with argument scope
Object o = super.g(key, Null.NULL);
if (o != Null.NULL) return o;
if (key.length() > 0) {
char c = key.charAt(0);
if ((c >= '0' && c <= '9') || c == '+') {
o = get(Caster.toIntValue(key.getString(), -1), Null.NULL);
if (o != Null.NULL) return o;
}
}
throw new ExpressionException("The key [" + key.getString() + "] doesn't exist in the arguments scope. The existing keys are ["
+ lucee.runtime.type.util.ListUtil.arrayToList(CollectionUtil.keys(this), ", ") + "]");
}
@Override
public Object get(int intKey, Object defaultValue) {
Iterator<Object> it = valueIterator(); // keyIterator();//getMap().keySet().iterator();
int count = 0;
Object o;
while (it.hasNext()) {
o = it.next();
if ((++count) == intKey) {
return o;// super.get(o.toString(),defaultValue);
}
}
return defaultValue;
}
/**
* return a value matching to key
*
* @param intKey
* @return value matching key
* @throws PageException
*/
@Override
public Object getE(int intKey) throws PageException {
Iterator it = valueIterator();// getMap().keySet().iterator();
int count = 0;
Object o;
while (it.hasNext()) {
o = it.next();
if ((++count) == intKey) {
return o;// super.get(o.toString());
}
}
throw new ExpressionException("invalid index [" + intKey + "] for argument scope");
}
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
DumpTable htmlBox = new DumpTable("struct", "#9999ff", "#ccccff", "#000000");
htmlBox.setTitle("Scope Arguments");
if (size() > 10 && dp.getMetainfo()) htmlBox.setComment("Entries:" + size());
maxlevel--;
// Map mapx=getMap();
Iterator<Key> it = keyIterator();// mapx.keySet().iterator();
int count = 0;
Collection.Key key;
int maxkeys = dp.getMaxKeys();
int index = 0;
while (it.hasNext()) {
key = it.next();// it.next();
if (DumpUtil.keyValid(dp, maxlevel, key)) {
if (maxkeys <= index++) break;
htmlBox.appendRow(3, new SimpleDumpData(key.getString()), new SimpleDumpData(++count), DumpUtil.toDumpData(get(key, null), pageContext, maxlevel, dp));
}
}
return htmlBox;
}
@Override
public int getDimension() {
return 1;
}
@Override
public Object setEL(int intKey, Object value) {
int count = 0;
if (intKey > size()) {
return setEL(Caster.toString(intKey), value);
}
// Iterator it = keyIterator();
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((++count) == intKey) {
return super.setEL(keys[i], value);
}
}
return value;
}
@Override
public Object setE(int intKey, Object value) throws PageException {
if (intKey > size()) {
return set(Caster.toString(intKey), value);
}
// Iterator it = keyIterator();
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.set(keys[i], value);
}
}
throw new ExpressionException("invalid index [" + intKey + "] for argument scope");
}
@Override
public int[] intKeys() {
int[] ints = new int[size()];
for (int i = 0; i < ints.length; i++)
ints[i] = i + 1;
return ints;
}
@Override
public boolean insert(int index, Object value) throws ExpressionException {
return insert(index, "" + index, value);
}
@Override
public boolean insert(int index, String key, Object value) throws ExpressionException {
int len = size();
if (index < 1 || index > len) throw new ExpressionException("invalid index to insert a value to argument scope",
len == 0 ? "can't insert in an empty argument scope" : "valid index goes from 1 to " + (len - 1));
// remove all upper
LinkedHashMap lhm = new LinkedHashMap();
Collection.Key[] keys = keys();
Collection.Key k;
for (int i = 1; i <= keys.length; i++) {
if (i < index) continue;
k = keys[i - 1];
lhm.put(k.getString(), get(k, null));
removeEL(k);
}
// set new value
setEL(key, value);
// reset upper values
Iterator it = lhm.entrySet().iterator();
Map.Entry entry;
while (it.hasNext()) {
entry = (Entry) it.next();
setEL(KeyImpl.toKey(entry.getKey()), entry.getValue());
}
return true;
}
@Override
public Object append(Object o) throws PageException {
return set(Caster.toString(size() + 1), o);
}
@Override
public Object appendEL(Object o) {
try {
return append(o);
}
catch (PageException e) {
return null;
}
}
@Override
public Object prepend(Object o) throws PageException {
for (int i = size(); i > 0; i--) {
setE(i + 1, getE(i));
}
setE(1, o);
return o;
}
@Override
public void resize(int to) throws PageException {
for (int i = size(); i < to; i++) {
append(null);
}
// throw new ExpressionException("can't resize this array");
}
@Override
public void sort(String sortType, String sortOrder) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort [" + sortType + "-" + sortOrder + "] Argument Scope", "not Implemnted Yet");
}
@Override
public void sortIt(Comparator com) {
// TODO Impl.
throw new PageRuntimeException("can't sort Argument Scope", "not Implemnted Yet");
}
@Override
public Object[] toArray() {
Iterator it = keyIterator();// getMap().keySet().iterator();
Object[] arr = new Object[size()];
int count = 0;
while (it.hasNext()) {
arr[count++] = it.next();
}
return arr;
}
@Override
public Object setArgument(Object obj) throws PageException {
if (obj == this) return obj;
if (Decision.isStruct(obj)) {
clear(); // TODO bessere impl. anstelle vererbung wrao auf struct
Struct sct = Caster.toStruct(obj);
Iterator<Key> it = sct.keyIterator();
Key key;
while (it.hasNext()) {
key = it.next();
setEL(key, sct.get(key, null));
}
return obj;
}
throw new ExpressionException("can not overwrite arguments scope");
}
public ArrayList toArrayList() {
ArrayList list = new ArrayList();
Object[] arr = toArray();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
return list;
}
@Override
public Object removeE(int intKey) throws PageException {
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.remove(keys[i]);
}
}
throw new ExpressionException("can't remove argument number [" + intKey + "], argument doesn't exist");
}
@Override
public Object removeEL(int intKey) {
return remove(intKey, null);
}
public Object remove(int intKey, Object defaultValue) {
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.removeEL(keys[i]);
}
}
return defaultValue;
}
@Override
public Object pop() throws PageException {
return removeE(size());
}
@Override
public synchronized Object pop(Object defaultValue) {
return remove(size(), defaultValue);
}
@Override
public Object shift() throws PageException {
return removeE(1);
}
@Override
public synchronized Object shift(Object defaultValue) {
return remove(1, defaultValue);
}
@Override
public final boolean containsKey(Collection.Key key) {
Object val = super.g(key, CollectionUtil.NULL);
if (val == CollectionUtil.NULL) return false;
if (val == null && !NullSupportHelper.full()) return false;
return true;
}
@Override
public final boolean containsKey(PageContext pc, Collection.Key key) {
Object val = super.g(key, CollectionUtil.NULL);
if (val == CollectionUtil.NULL) return false;
if (val == null && !NullSupportHelper.full(pc)) return false;
return true;
}
/*
* public boolean containsKey(Collection.Key key) { return get(key,null)!=null &&
* super.containsKey(key); }
*/
@Override
public boolean containsKey(int key) {
return key > 0 && key <= size();
}
@Override
public List toList() {
return ArrayAsList.toList(this);
}
@Override
public Collection duplicate(boolean deepCopy) {
ArgumentImpl trg = new ArgumentImpl();
trg.bind = false;
trg.functionArgumentNames = functionArgumentNames;
// trg.supportFunctionArguments=supportFunctionArguments;
copy(this, trg, deepCopy);
return trg;
}
@Override
public void setFunctionArgumentNames(Set functionArgumentNames) {// future add to interface
this.functionArgumentNames = functionArgumentNames;
}
/*
* public void setNamedArguments(boolean namedArguments) { this.namedArguments=namedArguments; }
* public boolean isNamedArguments() { return namedArguments; }
*/
/**
* converts an argument scope to a regular struct
*
* @param arg argument scope to convert
* @return resulting struct
*/
public static Struct toStruct(Argument arg) {
Struct trg = new StructImpl();
StructImpl.copy(arg, trg, false);
return trg;
}
/**
* converts an argument scope to a regular array
*
* @param arg argument scope to convert
* @return resulting array
*/
public static Array toArray(Argument arg) {
ArrayImpl trg = new ArrayImpl();
int[] keys = arg.intKeys();
for (int i = 0; i < keys.length; i++) {
trg.setEL(keys[i], arg.get(keys[i], null));
}
return trg;
}
@Override
public Object get(PageContext pc, Key key, Object defaultValue) {
return get(key, defaultValue);
}
@Override
public Object get(PageContext pc, Key key) throws PageException {
return get(key);
}
@Override
public Object set(PageContext pc, Key propertyName, Object value) throws PageException {
return set(propertyName, value);
}
@Override
public Object setEL(PageContext pc, Key propertyName, Object value) {
return setEL(propertyName, value);
}
@Override
public Object call(PageContext pc, Key methodName, Object[] args) throws PageException {
Object obj = get(methodName, null);
if (obj instanceof UDF) {
return ((UDF) obj).call(pc, methodName, args, false);
}
return MemberUtil.call(pc, this, methodName, args, new short[] { CFTypes.TYPE_STRUCT }, new String[] { "struct" });
// return MemberUtil.call(pc, this, methodName, args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
Object obj = get(methodName, null);
if (obj instanceof UDF) {
return ((UDF) obj).callWithNamedValues(pc, methodName, args, false);
}
return MemberUtil.callWithNamedValues(pc, this, methodName, args, CFTypes.TYPE_STRUCT, "struct");
// return MemberUtil.callWithNamedValues(pc,this,methodName,args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Iterator<Entry<Integer, Object>> entryArrayIterator() {
return new EntryArrayIterator(this, intKeys());
}
} | core/src/main/java/lucee/runtime/type/scope/ArgumentImpl.java | /**
* Copyright (c) 2014, the Railo Company Ltd.
* Copyright (c) 2015, Lucee Assosication Switzerland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.runtime.type.scope;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lucee.commons.lang.CFTypes;
import lucee.runtime.PageContext;
import lucee.runtime.config.NullSupportHelper;
import lucee.runtime.dump.DumpData;
import lucee.runtime.dump.DumpProperties;
import lucee.runtime.dump.DumpTable;
import lucee.runtime.dump.DumpUtil;
import lucee.runtime.dump.SimpleDumpData;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageRuntimeException;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.ArrayPro;
import lucee.runtime.type.Collection;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Null;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.it.EntryArrayIterator;
import lucee.runtime.type.util.CollectionUtil;
import lucee.runtime.type.util.MemberUtil;
import lucee.runtime.type.wrap.ArrayAsList;
/**
* implementation of the argument scope
*/
public final class ArgumentImpl extends ScopeSupport implements Argument, ArrayPro {
private static final long serialVersionUID = 4346997451403177136L;
private boolean bind;
private Set functionArgumentNames;
// private boolean supportFunctionArguments;
/**
* constructor of the class
*/
public ArgumentImpl() {
super("arguments", SCOPE_ARGUMENTS, Struct.TYPE_LINKED);
// this(true);
}
@Override
public void release(PageContext pc) {
functionArgumentNames = null;
super.release(ThreadLocalPageContext.get(pc));
}
@Override
public void setBind(boolean bind) {
this.bind = bind;
}
@Override
public boolean isBind() {
return this.bind;
}
@Override
public Object getFunctionArgument(String key, Object defaultValue) {
return getFunctionArgument(KeyImpl.getInstance(key), defaultValue);
}
@Override
public Object getFunctionArgument(Collection.Key key, Object defaultValue) {
return super.get(key, defaultValue);
}
@Override
public boolean containsFunctionArgumentKey(Key key) {
return super.containsKey(key);// functionArgumentNames!=null && functionArgumentNames.contains(key);
}
@Override
public Object get(Collection.Key key, Object defaultValue) {
/*
* if(NullSupportHelper.full()) { Object o=super.get(key,NullSupportHelper.NULL());
* if(o!=NullSupportHelper.NULL())return o;
*
* o=get(Caster.toIntValue(key.getString(),-1),NullSupportHelper.NULL());
* if(o!=NullSupportHelper.NULL())return o; return defaultValue; }
*/
Object o = super.g(key, Null.NULL);
if (o != Null.NULL) return o;
if (key.length() > 0) {
char c = key.charAt(0);
if ((c >= '0' && c <= '9') || c == '+') {
o = get(Caster.toIntValue(key.getString(), -1), Null.NULL);
if (o != Null.NULL) return o;
}
}
return defaultValue;
}
@Override
public Object get(Collection.Key key) throws ExpressionException {
// null is supported as returned value with argument scope
Object o = super.g(key, Null.NULL);
if (o != Null.NULL) return o;
if (key.length() > 0) {
char c = key.charAt(0);
if ((c >= '0' && c <= '9') || c == '+') {
o = get(Caster.toIntValue(key.getString(), -1), Null.NULL);
if (o != Null.NULL) return o;
}
}
throw new ExpressionException("Key [" + key.getString() + "] doesn't exist in arguments scope. The existing keys are ["
+ lucee.runtime.type.util.ListUtil.arrayToList(CollectionUtil.keys(this), ", ") + "]");
}
@Override
public Object get(int intKey, Object defaultValue) {
Iterator<Object> it = valueIterator(); // keyIterator();//getMap().keySet().iterator();
int count = 0;
Object o;
while (it.hasNext()) {
o = it.next();
if ((++count) == intKey) {
return o;// super.get(o.toString(),defaultValue);
}
}
return defaultValue;
}
/**
* return a value matching to key
*
* @param intKey
* @return value matching key
* @throws PageException
*/
@Override
public Object getE(int intKey) throws PageException {
Iterator it = valueIterator();// getMap().keySet().iterator();
int count = 0;
Object o;
while (it.hasNext()) {
o = it.next();
if ((++count) == intKey) {
return o;// super.get(o.toString());
}
}
throw new ExpressionException("invalid index [" + intKey + "] for argument scope");
}
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
DumpTable htmlBox = new DumpTable("struct", "#9999ff", "#ccccff", "#000000");
htmlBox.setTitle("Scope Arguments");
if (size() > 10 && dp.getMetainfo()) htmlBox.setComment("Entries:" + size());
maxlevel--;
// Map mapx=getMap();
Iterator<Key> it = keyIterator();// mapx.keySet().iterator();
int count = 0;
Collection.Key key;
int maxkeys = dp.getMaxKeys();
int index = 0;
while (it.hasNext()) {
key = it.next();// it.next();
if (DumpUtil.keyValid(dp, maxlevel, key)) {
if (maxkeys <= index++) break;
htmlBox.appendRow(3, new SimpleDumpData(key.getString()), new SimpleDumpData(++count), DumpUtil.toDumpData(get(key, null), pageContext, maxlevel, dp));
}
}
return htmlBox;
}
@Override
public int getDimension() {
return 1;
}
@Override
public Object setEL(int intKey, Object value) {
int count = 0;
if (intKey > size()) {
return setEL(Caster.toString(intKey), value);
}
// Iterator it = keyIterator();
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((++count) == intKey) {
return super.setEL(keys[i], value);
}
}
return value;
}
@Override
public Object setE(int intKey, Object value) throws PageException {
if (intKey > size()) {
return set(Caster.toString(intKey), value);
}
// Iterator it = keyIterator();
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.set(keys[i], value);
}
}
throw new ExpressionException("invalid index [" + intKey + "] for argument scope");
}
@Override
public int[] intKeys() {
int[] ints = new int[size()];
for (int i = 0; i < ints.length; i++)
ints[i] = i + 1;
return ints;
}
@Override
public boolean insert(int index, Object value) throws ExpressionException {
return insert(index, "" + index, value);
}
@Override
public boolean insert(int index, String key, Object value) throws ExpressionException {
int len = size();
if (index < 1 || index > len) throw new ExpressionException("invalid index to insert a value to argument scope",
len == 0 ? "can't insert in an empty argument scope" : "valid index goes from 1 to " + (len - 1));
// remove all upper
LinkedHashMap lhm = new LinkedHashMap();
Collection.Key[] keys = keys();
Collection.Key k;
for (int i = 1; i <= keys.length; i++) {
if (i < index) continue;
k = keys[i - 1];
lhm.put(k.getString(), get(k, null));
removeEL(k);
}
// set new value
setEL(key, value);
// reset upper values
Iterator it = lhm.entrySet().iterator();
Map.Entry entry;
while (it.hasNext()) {
entry = (Entry) it.next();
setEL(KeyImpl.toKey(entry.getKey()), entry.getValue());
}
return true;
}
@Override
public Object append(Object o) throws PageException {
return set(Caster.toString(size() + 1), o);
}
@Override
public Object appendEL(Object o) {
try {
return append(o);
}
catch (PageException e) {
return null;
}
}
@Override
public Object prepend(Object o) throws PageException {
for (int i = size(); i > 0; i--) {
setE(i + 1, getE(i));
}
setE(1, o);
return o;
}
@Override
public void resize(int to) throws PageException {
for (int i = size(); i < to; i++) {
append(null);
}
// throw new ExpressionException("can't resize this array");
}
@Override
public void sort(String sortType, String sortOrder) throws ExpressionException {
// TODO Impl.
throw new ExpressionException("can't sort [" + sortType + "-" + sortOrder + "] Argument Scope", "not Implemnted Yet");
}
@Override
public void sortIt(Comparator com) {
// TODO Impl.
throw new PageRuntimeException("can't sort Argument Scope", "not Implemnted Yet");
}
@Override
public Object[] toArray() {
Iterator it = keyIterator();// getMap().keySet().iterator();
Object[] arr = new Object[size()];
int count = 0;
while (it.hasNext()) {
arr[count++] = it.next();
}
return arr;
}
@Override
public Object setArgument(Object obj) throws PageException {
if (obj == this) return obj;
if (Decision.isStruct(obj)) {
clear(); // TODO bessere impl. anstelle vererbung wrao auf struct
Struct sct = Caster.toStruct(obj);
Iterator<Key> it = sct.keyIterator();
Key key;
while (it.hasNext()) {
key = it.next();
setEL(key, sct.get(key, null));
}
return obj;
}
throw new ExpressionException("can not overwrite arguments scope");
}
public ArrayList toArrayList() {
ArrayList list = new ArrayList();
Object[] arr = toArray();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
return list;
}
@Override
public Object removeE(int intKey) throws PageException {
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.remove(keys[i]);
}
}
throw new ExpressionException("can't remove argument number [" + intKey + "], argument doesn't exist");
}
@Override
public Object removeEL(int intKey) {
return remove(intKey, null);
}
public Object remove(int intKey, Object defaultValue) {
Key[] keys = keys();
for (int i = 0; i < keys.length; i++) {
if ((i + 1) == intKey) {
return super.removeEL(keys[i]);
}
}
return defaultValue;
}
@Override
public Object pop() throws PageException {
return removeE(size());
}
@Override
public synchronized Object pop(Object defaultValue) {
return remove(size(), defaultValue);
}
@Override
public Object shift() throws PageException {
return removeE(1);
}
@Override
public synchronized Object shift(Object defaultValue) {
return remove(1, defaultValue);
}
@Override
public final boolean containsKey(Collection.Key key) {
Object val = super.g(key, CollectionUtil.NULL);
if (val == CollectionUtil.NULL) return false;
if (val == null && !NullSupportHelper.full()) return false;
return true;
}
@Override
public final boolean containsKey(PageContext pc, Collection.Key key) {
Object val = super.g(key, CollectionUtil.NULL);
if (val == CollectionUtil.NULL) return false;
if (val == null && !NullSupportHelper.full(pc)) return false;
return true;
}
/*
* public boolean containsKey(Collection.Key key) { return get(key,null)!=null &&
* super.containsKey(key); }
*/
@Override
public boolean containsKey(int key) {
return key > 0 && key <= size();
}
@Override
public List toList() {
return ArrayAsList.toList(this);
}
@Override
public Collection duplicate(boolean deepCopy) {
ArgumentImpl trg = new ArgumentImpl();
trg.bind = false;
trg.functionArgumentNames = functionArgumentNames;
// trg.supportFunctionArguments=supportFunctionArguments;
copy(this, trg, deepCopy);
return trg;
}
@Override
public void setFunctionArgumentNames(Set functionArgumentNames) {// future add to interface
this.functionArgumentNames = functionArgumentNames;
}
/*
* public void setNamedArguments(boolean namedArguments) { this.namedArguments=namedArguments; }
* public boolean isNamedArguments() { return namedArguments; }
*/
/**
* converts an argument scope to a regular struct
*
* @param arg argument scope to convert
* @return resulting struct
*/
public static Struct toStruct(Argument arg) {
Struct trg = new StructImpl();
StructImpl.copy(arg, trg, false);
return trg;
}
/**
* converts an argument scope to a regular array
*
* @param arg argument scope to convert
* @return resulting array
*/
public static Array toArray(Argument arg) {
ArrayImpl trg = new ArrayImpl();
int[] keys = arg.intKeys();
for (int i = 0; i < keys.length; i++) {
trg.setEL(keys[i], arg.get(keys[i], null));
}
return trg;
}
@Override
public Object get(PageContext pc, Key key, Object defaultValue) {
return get(key, defaultValue);
}
@Override
public Object get(PageContext pc, Key key) throws PageException {
return get(key);
}
@Override
public Object set(PageContext pc, Key propertyName, Object value) throws PageException {
return set(propertyName, value);
}
@Override
public Object setEL(PageContext pc, Key propertyName, Object value) {
return setEL(propertyName, value);
}
@Override
public Object call(PageContext pc, Key methodName, Object[] args) throws PageException {
Object obj = get(methodName, null);
if (obj instanceof UDF) {
return ((UDF) obj).call(pc, methodName, args, false);
}
return MemberUtil.call(pc, this, methodName, args, new short[] { CFTypes.TYPE_STRUCT }, new String[] { "struct" });
// return MemberUtil.call(pc, this, methodName, args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
Object obj = get(methodName, null);
if (obj instanceof UDF) {
return ((UDF) obj).callWithNamedValues(pc, methodName, args, false);
}
return MemberUtil.callWithNamedValues(pc, this, methodName, args, CFTypes.TYPE_STRUCT, "struct");
// return MemberUtil.callWithNamedValues(pc,this,methodName,args, CFTypes.TYPE_ARRAY, "array");
}
@Override
public Iterator<Entry<Integer, Object>> entryArrayIterator() {
return new EntryArrayIterator(this, intKeys());
}
} | further improving grammar
| core/src/main/java/lucee/runtime/type/scope/ArgumentImpl.java | further improving grammar | <ide><path>ore/src/main/java/lucee/runtime/type/scope/ArgumentImpl.java
<ide> }
<ide> }
<ide>
<del> throw new ExpressionException("Key [" + key.getString() + "] doesn't exist in arguments scope. The existing keys are ["
<add> throw new ExpressionException("The key [" + key.getString() + "] doesn't exist in the arguments scope. The existing keys are ["
<ide> + lucee.runtime.type.util.ListUtil.arrayToList(CollectionUtil.keys(this), ", ") + "]");
<ide> }
<ide> |
|
Java | apache-2.0 | 29f4f383b74eab1db73abd408654e66cd39a1279 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2007 Columbia University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.gemma.analysis.preprocess.filter;
import java.io.Serializable;
/**
* Holds settings for filtering.
*
* @author Paul
* @version $Id$
*/
public class FilterConfig implements Serializable {
public static final double DEFAULT_HIGHEXPRESSION_CUT = 0.0;
public static final double DEFAULT_LOWEXPRESSIONCUT = 0.3;
public static final double DEFAULT_LOWVARIANCECUT = 0.05;
public static final double DEFAULT_MINPRESENT_FRACTION = 0.3;
public static final double DEFAULT_TOOSMALLTOKEEP = 0.5;
/**
* Fewer rows than this, and we bail.
*/
public static final int MINIMUM_ROWS_TO_BOTHER = 50;
/**
* How many samples a dataset has to have before we consider analyzing it.
*
* @see ExpressionExperimentFilter.MIN_NUMBER_OF_SAMPLES_PRESENT for a related setting.
*/
public final static int MINIMUM_SAMPLE = 7;
/**
*
*/
private static final long serialVersionUID = 1L;
private int afterInitialFilter = 0;
private int afterLowExpressionCut = 0;
private int afterLowVarianceCut = 0;
private int afterMinPresentFilter = 0;
private int afterZeroVarianceCut = 0;
private double highExpressionCut = DEFAULT_HIGHEXPRESSION_CUT;
/**
* If true, the MINIMUM_ROWS_TO_BOTHER is ignored.
*/
private boolean ignoreMinimumRowsThreshold = false;
/**
* If true, MINIMUM_SAMPLE is ignored.
*/
private boolean ignoreMinimumSampleThreshold = false;
private boolean knownGenesOnly = false;
private boolean logTransform = false;
private double lowExpressionCut = DEFAULT_LOWEXPRESSIONCUT;
private boolean lowExpressionCutIsSet = true;
private double lowVarianceCut = DEFAULT_LOWVARIANCECUT;
private boolean lowVarianceCutIsSet = true;
private double minPresentFraction = DEFAULT_MINPRESENT_FRACTION;
private boolean minPresentFractionIsSet = true;
private int startingRows = 0;
/**
* @return the afterInitialFilter
*/
public int getAfterInitialFilter() {
return afterInitialFilter;
}
/**
* @return the afterLowExpressionCut
*/
public int getAfterLowExpressionCut() {
return afterLowExpressionCut;
}
/**
* @return the afterLowVarianceCut
*/
public int getAfterLowVarianceCut() {
return afterLowVarianceCut;
}
/**
* @return the afterMinPresentFilter
*/
public int getAfterMinPresentFilter() {
return afterMinPresentFilter;
}
public int getAfterZeroVarianceCut() {
return afterZeroVarianceCut;
}
public double getHighExpressionCut() {
return highExpressionCut;
}
public double getLowExpressionCut() {
return lowExpressionCut;
}
public double getLowVarianceCut() {
return lowVarianceCut;
}
public double getMinPresentFraction() {
return minPresentFraction;
}
/**
* @return the startingRows
*/
public int getStartingRows() {
return startingRows;
}
/**
* @return the ignoreMinimumRowThreshold
*/
public boolean isIgnoreMinimumRowsThreshold() {
return ignoreMinimumRowsThreshold;
}
public boolean isIgnoreMinimumSampleThreshold() {
return ignoreMinimumSampleThreshold;
}
public boolean isKnownGenesOnly() {
return knownGenesOnly;
}
/**
* @return the logTransform
*/
public boolean isLogTransform() {
return logTransform;
}
public boolean isLowExpressionCutIsSet() {
return lowExpressionCutIsSet;
}
public boolean isLowVarianceCutIsSet() {
return lowVarianceCutIsSet;
}
public boolean isMinPresentFractionIsSet() {
return minPresentFractionIsSet;
}
/**
* @param afterInitialFilter the afterInitialFilter to set
*/
public void setAfterInitialFilter( int afterInitialFilter ) {
this.afterInitialFilter = afterInitialFilter;
}
/**
* @param afterLowExpressionCut the afterLowExpressionCut to set
*/
public void setAfterLowExpressionCut( int afterLowExpressionCut ) {
this.afterLowExpressionCut = afterLowExpressionCut;
}
/**
* @param afterLowVarianceCut the afterLowVarianceCut to set
*/
public void setAfterLowVarianceCut( int afterLowVarianceCut ) {
this.afterLowVarianceCut = afterLowVarianceCut;
}
/**
* @param afterMinPresentFilter the afterMinPresentFilter to set
*/
public void setAfterMinPresentFilter( int afterMinPresentFilter ) {
this.afterMinPresentFilter = afterMinPresentFilter;
}
public void setAfterZeroVarianceCut( int afterZeroVarianceCut ) {
this.afterZeroVarianceCut = afterZeroVarianceCut;
}
public void setHighExpressionCut( double highExpressionCut ) {
this.highExpressionCut = highExpressionCut;
}
/**
* @param ignoreMinimumRowThreshold the ignoreMinimumRowThreshold to set
*/
public void setIgnoreMinimumRowsThreshold( boolean ignoreMinimumRowsThreshold ) {
this.ignoreMinimumRowsThreshold = ignoreMinimumRowsThreshold;
}
public void setIgnoreMinimumSampleThreshold( boolean ignoreMinimumSampleThreshold ) {
this.ignoreMinimumSampleThreshold = ignoreMinimumSampleThreshold;
}
public void setKnownGenesOnly( boolean knownGenesOnly ) {
this.knownGenesOnly = knownGenesOnly;
}
/**
* @param logTransform the logTransform to set
*/
public void setLogTransform( boolean logTransform ) {
this.logTransform = logTransform;
}
public void setLowExpressionCut( double lowExpressionCut ) {
this.lowExpressionCutIsSet = true;
this.lowExpressionCut = lowExpressionCut;
}
public void setLowVarianceCut( double lowVarianceCut ) {
this.lowVarianceCutIsSet = true;
this.lowVarianceCut = lowVarianceCut;
}
public void setMinPresentFraction( double minPresentFraction ) {
this.minPresentFractionIsSet = true;
this.minPresentFraction = minPresentFraction;
}
/**
* @param startingRows the startingRows to set
*/
public void setStartingRows( int startingRows ) {
this.startingRows = startingRows;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append( "# highExpressionCut:" + this.getHighExpressionCut() + "\n" );
buf.append( "# lowExpressionCut:" + this.getLowExpressionCut() + "\n" );
buf.append( "# minPresentFraction:" + this.getMinPresentFraction() + "\n" );
buf.append( "# lowVarianceCut:" + this.getLowVarianceCut() + "\n" );
buf.append( "# startingProbes:" + this.getStartingRows() + "\n" );
buf.append( "# afterInitialFilter:" + this.getAfterInitialFilter() + "\n" );
buf.append( "# afterMinPresentFilter:" + this.getAfterMinPresentFilter() + "\n" );
buf.append( "# afterLowVarianceCut:" + this.getAfterLowVarianceCut() + "\n" );
buf.append( "# afterLowExpressionCut:" + this.getAfterLowExpressionCut() + "\n" );
buf.append( "# logTransform:" + this.isLogTransform() + "\n" );
// buf.append( "# knownGenesOnly " + this.isKnownGenesOnly() + "\n" );
return buf.toString();
}
}
| gemma-core/src/main/java/ubic/gemma/analysis/preprocess/filter/FilterConfig.java | /*
* The Gemma project
*
* Copyright (c) 2007 Columbia University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.gemma.analysis.preprocess.filter;
import java.io.Serializable;
/**
* Holds settings for filtering.
*
* @author Paul
* @version $Id$
*/
public class FilterConfig implements Serializable {
public static final double DEFAULT_HIGHEXPRESSION_CUT = 0.0;
public static final double DEFAULT_LOWEXPRESSIONCUT = 0.3;
public static final double DEFAULT_LOWVARIANCECUT = 0.05;
public static final double DEFAULT_MINPRESENT_FRACTION = 0.3;
public static final double DEFAULT_TOOSMALLTOKEEP = 0.5;
/**
* Fewer rows than this, and we bail.
*/
public static final int MINIMUM_ROWS_TO_BOTHER = 100;
/**
* How many samples a dataset has to have before we consider analyzing it.
*
* @see ExpressionExperimentFilter.MIN_NUMBER_OF_SAMPLES_PRESENT for a related setting.
*/
public final static int MINIMUM_SAMPLE = 7;
/**
*
*/
private static final long serialVersionUID = 1L;
private int afterInitialFilter = 0;
private int afterLowExpressionCut = 0;
private int afterLowVarianceCut = 0;
private int afterMinPresentFilter = 0;
private int afterZeroVarianceCut = 0;
private double highExpressionCut = DEFAULT_HIGHEXPRESSION_CUT;
/**
* If true, the MINIMUM_ROWS_TO_BOTHER is ignored.
*/
private boolean ignoreMinimumRowsThreshold = false;
/**
* If true, MINIMUM_SAMPLE is ignored.
*/
private boolean ignoreMinimumSampleThreshold = false;
private boolean knownGenesOnly = false;
private boolean logTransform = false;
private double lowExpressionCut = DEFAULT_LOWEXPRESSIONCUT;
private boolean lowExpressionCutIsSet = true;
private double lowVarianceCut = DEFAULT_LOWVARIANCECUT;
private boolean lowVarianceCutIsSet = true;
private double minPresentFraction = DEFAULT_MINPRESENT_FRACTION;
private boolean minPresentFractionIsSet = true;
private int startingRows = 0;
/**
* @return the afterInitialFilter
*/
public int getAfterInitialFilter() {
return afterInitialFilter;
}
/**
* @return the afterLowExpressionCut
*/
public int getAfterLowExpressionCut() {
return afterLowExpressionCut;
}
/**
* @return the afterLowVarianceCut
*/
public int getAfterLowVarianceCut() {
return afterLowVarianceCut;
}
/**
* @return the afterMinPresentFilter
*/
public int getAfterMinPresentFilter() {
return afterMinPresentFilter;
}
public int getAfterZeroVarianceCut() {
return afterZeroVarianceCut;
}
public double getHighExpressionCut() {
return highExpressionCut;
}
public double getLowExpressionCut() {
return lowExpressionCut;
}
public double getLowVarianceCut() {
return lowVarianceCut;
}
public double getMinPresentFraction() {
return minPresentFraction;
}
/**
* @return the startingRows
*/
public int getStartingRows() {
return startingRows;
}
/**
* @return the ignoreMinimumRowThreshold
*/
public boolean isIgnoreMinimumRowsThreshold() {
return ignoreMinimumRowsThreshold;
}
public boolean isIgnoreMinimumSampleThreshold() {
return ignoreMinimumSampleThreshold;
}
public boolean isKnownGenesOnly() {
return knownGenesOnly;
}
/**
* @return the logTransform
*/
public boolean isLogTransform() {
return logTransform;
}
public boolean isLowExpressionCutIsSet() {
return lowExpressionCutIsSet;
}
public boolean isLowVarianceCutIsSet() {
return lowVarianceCutIsSet;
}
public boolean isMinPresentFractionIsSet() {
return minPresentFractionIsSet;
}
/**
* @param afterInitialFilter the afterInitialFilter to set
*/
public void setAfterInitialFilter( int afterInitialFilter ) {
this.afterInitialFilter = afterInitialFilter;
}
/**
* @param afterLowExpressionCut the afterLowExpressionCut to set
*/
public void setAfterLowExpressionCut( int afterLowExpressionCut ) {
this.afterLowExpressionCut = afterLowExpressionCut;
}
/**
* @param afterLowVarianceCut the afterLowVarianceCut to set
*/
public void setAfterLowVarianceCut( int afterLowVarianceCut ) {
this.afterLowVarianceCut = afterLowVarianceCut;
}
/**
* @param afterMinPresentFilter the afterMinPresentFilter to set
*/
public void setAfterMinPresentFilter( int afterMinPresentFilter ) {
this.afterMinPresentFilter = afterMinPresentFilter;
}
public void setAfterZeroVarianceCut( int afterZeroVarianceCut ) {
this.afterZeroVarianceCut = afterZeroVarianceCut;
}
public void setHighExpressionCut( double highExpressionCut ) {
this.highExpressionCut = highExpressionCut;
}
/**
* @param ignoreMinimumRowThreshold the ignoreMinimumRowThreshold to set
*/
public void setIgnoreMinimumRowsThreshold( boolean ignoreMinimumRowsThreshold ) {
this.ignoreMinimumRowsThreshold = ignoreMinimumRowsThreshold;
}
public void setIgnoreMinimumSampleThreshold( boolean ignoreMinimumSampleThreshold ) {
this.ignoreMinimumSampleThreshold = ignoreMinimumSampleThreshold;
}
public void setKnownGenesOnly( boolean knownGenesOnly ) {
this.knownGenesOnly = knownGenesOnly;
}
/**
* @param logTransform the logTransform to set
*/
public void setLogTransform( boolean logTransform ) {
this.logTransform = logTransform;
}
public void setLowExpressionCut( double lowExpressionCut ) {
this.lowExpressionCutIsSet = true;
this.lowExpressionCut = lowExpressionCut;
}
public void setLowVarianceCut( double lowVarianceCut ) {
this.lowVarianceCutIsSet = true;
this.lowVarianceCut = lowVarianceCut;
}
public void setMinPresentFraction( double minPresentFraction ) {
this.minPresentFractionIsSet = true;
this.minPresentFraction = minPresentFraction;
}
/**
* @param startingRows the startingRows to set
*/
public void setStartingRows( int startingRows ) {
this.startingRows = startingRows;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append( "# highExpressionCut:" + this.getHighExpressionCut() + "\n" );
buf.append( "# lowExpressionCut:" + this.getLowExpressionCut() + "\n" );
buf.append( "# minPresentFraction:" + this.getMinPresentFraction() + "\n" );
buf.append( "# lowVarianceCut:" + this.getLowVarianceCut() + "\n" );
buf.append( "# startingProbes:" + this.getStartingRows() + "\n" );
buf.append( "# afterInitialFilter:" + this.getAfterInitialFilter() + "\n" );
buf.append( "# afterMinPresentFilter:" + this.getAfterMinPresentFilter() + "\n" );
buf.append( "# afterLowVarianceCut:" + this.getAfterLowVarianceCut() + "\n" );
buf.append( "# afterLowExpressionCut:" + this.getAfterLowExpressionCut() + "\n" );
buf.append( "# logTransform:" + this.isLogTransform() + "\n" );
// buf.append( "# knownGenesOnly " + this.isKnownGenesOnly() + "\n" );
return buf.toString();
}
}
| allow analysis when there are only 50 rows (by default)
| gemma-core/src/main/java/ubic/gemma/analysis/preprocess/filter/FilterConfig.java | allow analysis when there are only 50 rows (by default) | <ide><path>emma-core/src/main/java/ubic/gemma/analysis/preprocess/filter/FilterConfig.java
<ide> /**
<ide> * Fewer rows than this, and we bail.
<ide> */
<del> public static final int MINIMUM_ROWS_TO_BOTHER = 100;
<add> public static final int MINIMUM_ROWS_TO_BOTHER = 50;
<ide>
<ide> /**
<ide> * How many samples a dataset has to have before we consider analyzing it. |
|
Java | apache-2.0 | 49a072d9e975686416e30f97d4fda252f2015464 | 0 | skunkiferous/Util | package org.agilewiki.jactor2.core.impl.stRequests;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.agilewiki.jactor2.core.impl.stReactors.ReactorStImpl;
import org.agilewiki.jactor2.core.plant.impl.PlantImpl;
import org.agilewiki.jactor2.core.reactors.CommonReactor;
import org.agilewiki.jactor2.core.reactors.Reactor;
import org.agilewiki.jactor2.core.requests.*;
import org.agilewiki.jactor2.core.requests.impl.AsyncRequestImpl;
import org.agilewiki.jactor2.core.requests.impl.RequestImpl;
import org.agilewiki.jactor2.core.util.Timer;
/**
* Internal implementation of AsyncRequest.
*
* @param <RESPONSE_TYPE> The type of response.
*/
public class AsyncRequestStImpl<RESPONSE_TYPE> extends
RequestStImpl<RESPONSE_TYPE> implements AsyncNativeRequest<RESPONSE_TYPE> {
private final Set<RequestStImpl<?>> pendingRequests = new HashSet<RequestStImpl<?>>();
private boolean noHungRequestCheck;
private final AsyncOperation<RESPONSE_TYPE> asyncOperation;
/** Used by the Timer. */
private volatile long start;
/**
* Create an AsyncRequestMtImpl and bind it to its operation and target targetReactor.
*
* @param _asyncOperation The request being implemented.
* @param _targetReactor The targetReactor where this AsyncRequest Objects is passed for processing.
* The thread owned by this targetReactor will process this AsyncRequest.
*/
public AsyncRequestStImpl(final AsyncOperation<RESPONSE_TYPE> _asyncOperation,
final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = _asyncOperation;
}
public AsyncRequestStImpl(final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = this;
}
@Override
public AsyncOperation<RESPONSE_TYPE> asOperation() {
return asyncOperation;
}
/**
* Disable check for hung request.
* This must be called when a response must wait for a subsequent request.
*/
@Override
public void setNoHungRequestCheck() {
noHungRequestCheck = true;
}
/**
* Returns a count of the number of subordinate requests which have not yet responded.
*
* @return A count of the number of subordinate requests which have not yet responded.
*/
@Override
public int getPendingResponseCount() {
return pendingRequests.size();
}
/**
* Process the response to this request.
*
* @param _response The response to this request.
*/
@Override
public void processAsyncResponse(final RESPONSE_TYPE _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, true);
processObjectResponse(_response);
}
/**
* Returns an exception as a response instead of throwing it.
* But regardless of how a response is returned, if the response is an exception it
* is passed to the exception handler of the request that did the call or send on the request.
*
* @param _response An exception.
*/
@Override
public void processAsyncException(final Exception _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, false);
processObjectResponse(_response);
}
private void pendingCheck() throws Exception {
if (incomplete && !isCanceled() && (pendingRequests.size() == 0)
&& !noHungRequestCheck) {
targetReactor.asReactorImpl().error("hung request:\n" + toString());
close();
targetReactorImpl.getRecovery().onHungRequest(this);
}
}
@Override
protected void processRequestMessage() throws Exception {
start = asyncOperation.getTimer().nanos();
asyncOperation.processAsyncOperation(this, this);
pendingCheck();
}
@Override
public void responseReceived(final RequestImpl<?> request) {
pendingRequests.remove(request);
}
@Override
public void responseProcessed() {
try {
pendingCheck();
} catch (final Exception e) {
processException(requestSource, e);
}
}
@Override
public <RT> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT> _responseProcessor) {
if (canceled && (_responseProcessor != null)) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
if (_responseProcessor != OneWayResponseProcessor.SINGLETON) {
pendingRequests.add(requestImpl);
}
requestImpl.doSend(targetReactorImpl, _responseProcessor);
}
@Override
public <RT, RT2> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
if (canceled) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
pendingRequests.add(requestImpl);
requestImpl.doSend(targetReactorImpl, new AsyncResponseProcessor<RT>() {
@Override
public void processAsyncResponse(final RT _response)
throws Exception {
_dis.processAsyncResponse(_fixedResponse);
}
});
}
/**
* Replace the current ExceptionHandler with another.
* <p>
* When an event or request message is processed by a targetReactor, the current
* exception handler is set to null. When a request is sent by a targetReactor, the
* current exception handler is saved in the outgoing message and restored when
* the response message is processed.
* </p>
*
* @param _exceptionHandler The exception handler to be used now.
* May be null if the default exception handler is to be used.
* @return The exception handler that was previously in effect, or null if the
* default exception handler was in effect.
*/
@Override
public ExceptionHandler<RESPONSE_TYPE> setExceptionHandler(
final ExceptionHandler<RESPONSE_TYPE> _exceptionHandler) {
@SuppressWarnings("unchecked")
final ExceptionHandler<RESPONSE_TYPE> old = (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
targetReactorImpl.setExceptionHandler(_exceptionHandler);
return old;
}
/**
* Returns the current exception handler.
*
* @return The current exception handler, or null.
*/
@SuppressWarnings("unchecked")
public ExceptionHandler<RESPONSE_TYPE> getExceptionHandler() {
return (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
}
@Override
public void close() {
if (!incomplete) {
return;
}
final HashSet<RequestStImpl<?>> pr = new HashSet<RequestStImpl<?>>(
pendingRequests);
final Iterator<RequestStImpl<?>> it = pr.iterator();
while (it.hasNext()) {
it.next().cancel();
}
super.close();
asOperation().onClose(this);
}
/**
* Cancel a subordinate RequestImpl.
*
* @param _requestImpl The subordinate RequestImpl.
* @return True if the subordinate RequestImpl was canceled.
*/
@Override
public boolean cancel(final RequestImpl<?> _requestImpl) {
final RequestStImpl<?> requestImpl = (RequestStImpl<?>) _requestImpl;
if (!pendingRequests.remove(requestImpl)) {
return false;
}
requestImpl.cancel();
return true;
}
/**
* Cancel all subordinate RequestImpl's.
*/
@Override
public void cancelAll() {
final Set<RequestImpl<?>> all = new HashSet<RequestImpl<?>>(
pendingRequests);
final Iterator<RequestImpl<?>> it = all.iterator();
while (it.hasNext()) {
cancel(it.next());
}
}
/**
* Cancel this request.
*/
@Override
public void cancel() {
if (canceled) {
return;
}
canceled = true;
asOperation().onCancel(this);
}
@Override
protected void setResponse(final Object _response,
final ReactorStImpl _activeReactor) {
if ((_response instanceof Throwable)
|| (targetReactor instanceof CommonReactor)) {
cancelAll();
}
super.setResponse(_response, _activeReactor);
}
@Override
public <RT> void send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_sOp, _sOp.targetReactor), _asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_sOp, _sOp.targetReactor), _dis, _fixedResponse);
}
@Override
public <RT> void send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_aOp, _aOp.targetReactor), _asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_aOp, _aOp.targetReactor), _dis, _fixedResponse);
}
@Override
public <RT> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest, _syncNativeRequest.getTargetReactor()),
_asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest, _syncNativeRequest.getTargetReactor()),
_dis, _fixedResponse);
}
@Override
public <RT> void send(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_dis, _fixedResponse);
}
@Override
public <RT> void asyncDirect(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor)
throws Exception {
final ExceptionHandler<RESPONSE_TYPE> oldExceptionHandler = getExceptionHandler();
_aOp.targetReactor.directCheck(getTargetReactor());
_aOp.processAsyncOperation(this, new AsyncResponseProcessor<RT>() {
@Override
public void processAsyncResponse(RT _response) throws Exception {
setExceptionHandler(oldExceptionHandler);
_asyncResponseProcessor.processAsyncResponse(_response);
}
});
}
@Override
public <RT> void asyncDirect(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor)
throws Exception {
final ExceptionHandler<RESPONSE_TYPE> oldExceptionHandler = getExceptionHandler();
ReactorStImpl reactorMtImpl = (ReactorStImpl) _asyncNativeRequest.getTargetReactor();
reactorMtImpl.directCheck(getTargetReactor());
_asyncNativeRequest.processAsyncOperation(this, new AsyncResponseProcessor<RT>() {
@Override
public void processAsyncResponse(RT _response) throws Exception {
setExceptionHandler(oldExceptionHandler);
_asyncResponseProcessor.processAsyncResponse(_response);
}
});
}
@Override
public void onCancel(final AsyncRequestImpl _asyncRequestImpl) {
onCancel();
}
/**
* An optional callback used to signal that the request has been canceled.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* The default action of onCancel is to call cancelAll and,
* if the reactor is not a common reactor, sends a response of null via
* a bound response processor.
*/
public void onCancel() {
cancelAll();
final Reactor targetReactor = getTargetReactor();
if (!(targetReactor instanceof CommonReactor)) {
try {
new BoundResponseProcessor<RESPONSE_TYPE>(targetReactor, this)
.processAsyncResponse(null);
} catch (final Exception e) {
}
}
}
@Override
public void onClose(final AsyncRequestImpl _asyncRequestImpl) {
onClose();
}
/**
* An optional callback used to signal that the request has been closed.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* By default, onClose does nothing.
*/
public void onClose() {
}
@Override
public void processAsyncOperation(final AsyncRequestImpl _asyncRequestImpl,
final AsyncResponseProcessor<RESPONSE_TYPE> _asyncResponseProcessor)
throws Exception {
throw new IllegalStateException();
}
}
| jactor2-coreSt/src/main/java/org/agilewiki/jactor2/core/impl/stRequests/AsyncRequestStImpl.java | package org.agilewiki.jactor2.core.impl.stRequests;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.agilewiki.jactor2.core.impl.stReactors.ReactorStImpl;
import org.agilewiki.jactor2.core.plant.impl.PlantImpl;
import org.agilewiki.jactor2.core.reactors.CommonReactor;
import org.agilewiki.jactor2.core.reactors.Reactor;
import org.agilewiki.jactor2.core.requests.*;
import org.agilewiki.jactor2.core.requests.impl.AsyncRequestImpl;
import org.agilewiki.jactor2.core.requests.impl.RequestImpl;
import org.agilewiki.jactor2.core.util.Timer;
/**
* Internal implementation of AsyncRequest.
*
* @param <RESPONSE_TYPE> The type of response.
*/
public class AsyncRequestStImpl<RESPONSE_TYPE> extends
RequestStImpl<RESPONSE_TYPE> implements AsyncNativeRequest<RESPONSE_TYPE> {
private final Set<RequestStImpl<?>> pendingRequests = new HashSet<RequestStImpl<?>>();
private boolean noHungRequestCheck;
private final AsyncOperation<RESPONSE_TYPE> asyncOperation;
/** Used by the Timer. */
private volatile long start;
/**
* Create an AsyncRequestMtImpl and bind it to its operation and target targetReactor.
*
* @param _asyncOperation The request being implemented.
* @param _targetReactor The targetReactor where this AsyncRequest Objects is passed for processing.
* The thread owned by this targetReactor will process this AsyncRequest.
*/
public AsyncRequestStImpl(final AsyncOperation<RESPONSE_TYPE> _asyncOperation,
final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = _asyncOperation;
}
public AsyncRequestStImpl(final Reactor _targetReactor) {
super(_targetReactor);
asyncOperation = this;
}
@Override
public AsyncOperation<RESPONSE_TYPE> asOperation() {
return asyncOperation;
}
/**
* Disable check for hung request.
* This must be called when a response must wait for a subsequent request.
*/
@Override
public void setNoHungRequestCheck() {
noHungRequestCheck = true;
}
/**
* Returns a count of the number of subordinate requests which have not yet responded.
*
* @return A count of the number of subordinate requests which have not yet responded.
*/
@Override
public int getPendingResponseCount() {
return pendingRequests.size();
}
/**
* Process the response to this request.
*
* @param _response The response to this request.
*/
@Override
public void processAsyncResponse(final RESPONSE_TYPE _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, true);
processObjectResponse(_response);
}
/**
* Returns an exception as a response instead of throwing it.
* But regardless of how a response is returned, if the response is an exception it
* is passed to the exception handler of the request that did the call or send on the request.
*
* @param _response An exception.
*/
@Override
public void processAsyncException(final Exception _response) {
final Timer timer = asyncOperation.getTimer();
timer.updateNanos(timer.nanos() - start, false);
processObjectResponse(_response);
}
private void pendingCheck() throws Exception {
if (incomplete && !isCanceled() && (pendingRequests.size() == 0)
&& !noHungRequestCheck) {
targetReactor.asReactorImpl().error("hung request:\n" + toString());
close();
targetReactorImpl.getRecovery().onHungRequest(this);
}
}
@Override
protected void processRequestMessage() throws Exception {
start = asyncOperation.getTimer().nanos();
asyncOperation.processAsyncOperation(this, this);
pendingCheck();
}
@Override
public void responseReceived(final RequestImpl<?> request) {
pendingRequests.remove(request);
}
@Override
public void responseProcessed() {
try {
pendingCheck();
} catch (final Exception e) {
processException(requestSource, e);
}
}
@Override
public <RT> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT> _responseProcessor) {
if (canceled && (_responseProcessor != null)) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
if (_responseProcessor != OneWayResponseProcessor.SINGLETON) {
pendingRequests.add(requestImpl);
}
requestImpl.doSend(targetReactorImpl, _responseProcessor);
}
@Override
public <RT, RT2> void send(final RequestImpl<RT> _requestImpl,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
if (canceled) {
return;
}
if (targetReactorImpl.getCurrentRequest() != this) {
throw new UnsupportedOperationException(
"send called on inactive request");
}
final RequestStImpl<RT> requestImpl = (RequestStImpl<RT>) _requestImpl;
pendingRequests.add(requestImpl);
requestImpl.doSend(targetReactorImpl, new AsyncResponseProcessor<RT>() {
@Override
public void processAsyncResponse(final RT _response)
throws Exception {
_dis.processAsyncResponse(_fixedResponse);
}
});
}
/**
* Replace the current ExceptionHandler with another.
* <p>
* When an event or request message is processed by a targetReactor, the current
* exception handler is set to null. When a request is sent by a targetReactor, the
* current exception handler is saved in the outgoing message and restored when
* the response message is processed.
* </p>
*
* @param _exceptionHandler The exception handler to be used now.
* May be null if the default exception handler is to be used.
* @return The exception handler that was previously in effect, or null if the
* default exception handler was in effect.
*/
@Override
public ExceptionHandler<RESPONSE_TYPE> setExceptionHandler(
final ExceptionHandler<RESPONSE_TYPE> _exceptionHandler) {
@SuppressWarnings("unchecked")
final ExceptionHandler<RESPONSE_TYPE> old = (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
targetReactorImpl.setExceptionHandler(_exceptionHandler);
return old;
}
/**
* Returns the current exception handler.
*
* @return The current exception handler, or null.
*/
@SuppressWarnings("unchecked")
public ExceptionHandler<RESPONSE_TYPE> getExceptionHandler() {
return (ExceptionHandler<RESPONSE_TYPE>) targetReactorImpl
.getExceptionHandler();
}
@Override
public void close() {
if (!incomplete) {
return;
}
final HashSet<RequestStImpl<?>> pr = new HashSet<RequestStImpl<?>>(
pendingRequests);
final Iterator<RequestStImpl<?>> it = pr.iterator();
while (it.hasNext()) {
it.next().cancel();
}
super.close();
asOperation().onClose(this);
}
/**
* Cancel a subordinate RequestImpl.
*
* @param _requestImpl The subordinate RequestImpl.
* @return True if the subordinate RequestImpl was canceled.
*/
@Override
public boolean cancel(final RequestImpl<?> _requestImpl) {
final RequestStImpl<?> requestImpl = (RequestStImpl<?>) _requestImpl;
if (!pendingRequests.remove(requestImpl)) {
return false;
}
requestImpl.cancel();
return true;
}
/**
* Cancel all subordinate RequestImpl's.
*/
@Override
public void cancelAll() {
final Set<RequestImpl<?>> all = new HashSet<RequestImpl<?>>(
pendingRequests);
final Iterator<RequestImpl<?>> it = all.iterator();
while (it.hasNext()) {
cancel(it.next());
}
}
/**
* Cancel this request.
*/
@Override
public void cancel() {
if (canceled) {
return;
}
canceled = true;
asOperation().onCancel(this);
}
@Override
protected void setResponse(final Object _response,
final ReactorStImpl _activeReactor) {
if ((_response instanceof Throwable)
|| (targetReactor instanceof CommonReactor)) {
cancelAll();
}
super.setResponse(_response, _activeReactor);
}
@Override
public <RT> void send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_sOp, _sOp.targetReactor), _asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final SOp<RT> _sOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_sOp, _sOp.targetReactor), _dis, _fixedResponse);
}
@Override
public <RT> void send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_aOp, _aOp.targetReactor), _asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_aOp, _aOp.targetReactor), _dis, _fixedResponse);
}
@Override
public <RT> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest, _syncNativeRequest.getTargetReactor()),
_asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final SyncNativeRequest<RT> _syncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createSyncRequestImpl(_syncNativeRequest, _syncNativeRequest.getTargetReactor()),
_dis, _fixedResponse);
}
@Override
public <RT> void send(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_asyncResponseProcessor);
}
@Override
public <RT, RT2> void send(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT2> _dis, final RT2 _fixedResponse) {
send(PlantImpl.getSingleton().createAsyncRequestImpl(_asyncNativeRequest, _asyncNativeRequest.getTargetReactor()),
_dis, _fixedResponse);
}
@Override
public <RT> void asyncDirect(final AOp<RT> _aOp,
final AsyncResponseProcessor<RT> _asyncResponseProcessor)
throws Exception {
_aOp.targetReactor.directCheck(getTargetReactor());
_aOp.processAsyncOperation(this, _asyncResponseProcessor);
}
@Override
public <RT> void asyncDirect(final AsyncNativeRequest<RT> _asyncNativeRequest,
final AsyncResponseProcessor<RT> _asyncResponseProcessor)
throws Exception {
ReactorStImpl reactorMtImpl = (ReactorStImpl) _asyncNativeRequest.getTargetReactor();
reactorMtImpl.directCheck(getTargetReactor());
_asyncNativeRequest.processAsyncOperation(this, _asyncResponseProcessor);
}
@Override
public void onCancel(final AsyncRequestImpl _asyncRequestImpl) {
onCancel();
}
/**
* An optional callback used to signal that the request has been canceled.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* The default action of onCancel is to call cancelAll and,
* if the reactor is not a common reactor, sends a response of null via
* a bound response processor.
*/
public void onCancel() {
cancelAll();
final Reactor targetReactor = getTargetReactor();
if (!(targetReactor instanceof CommonReactor)) {
try {
new BoundResponseProcessor<RESPONSE_TYPE>(targetReactor, this)
.processAsyncResponse(null);
} catch (final Exception e) {
}
}
}
@Override
public void onClose(final AsyncRequestImpl _asyncRequestImpl) {
onClose();
}
/**
* An optional callback used to signal that the request has been closed.
* This method must be thread-safe, as there is no constraint on which
* thread is used to call it.
* By default, onClose does nothing.
*/
public void onClose() {
}
@Override
public void processAsyncOperation(final AsyncRequestImpl _asyncRequestImpl,
final AsyncResponseProcessor<RESPONSE_TYPE> _asyncResponseProcessor)
throws Exception {
throw new IllegalStateException();
}
}
| asyncDirect restores old exception handler on completion
| jactor2-coreSt/src/main/java/org/agilewiki/jactor2/core/impl/stRequests/AsyncRequestStImpl.java | asyncDirect restores old exception handler on completion | <ide><path>actor2-coreSt/src/main/java/org/agilewiki/jactor2/core/impl/stRequests/AsyncRequestStImpl.java
<ide> public <RT> void asyncDirect(final AOp<RT> _aOp,
<ide> final AsyncResponseProcessor<RT> _asyncResponseProcessor)
<ide> throws Exception {
<add> final ExceptionHandler<RESPONSE_TYPE> oldExceptionHandler = getExceptionHandler();
<ide> _aOp.targetReactor.directCheck(getTargetReactor());
<del> _aOp.processAsyncOperation(this, _asyncResponseProcessor);
<add> _aOp.processAsyncOperation(this, new AsyncResponseProcessor<RT>() {
<add> @Override
<add> public void processAsyncResponse(RT _response) throws Exception {
<add> setExceptionHandler(oldExceptionHandler);
<add> _asyncResponseProcessor.processAsyncResponse(_response);
<add> }
<add> });
<ide> }
<ide>
<ide> @Override
<ide> public <RT> void asyncDirect(final AsyncNativeRequest<RT> _asyncNativeRequest,
<ide> final AsyncResponseProcessor<RT> _asyncResponseProcessor)
<ide> throws Exception {
<add> final ExceptionHandler<RESPONSE_TYPE> oldExceptionHandler = getExceptionHandler();
<ide> ReactorStImpl reactorMtImpl = (ReactorStImpl) _asyncNativeRequest.getTargetReactor();
<ide> reactorMtImpl.directCheck(getTargetReactor());
<del> _asyncNativeRequest.processAsyncOperation(this, _asyncResponseProcessor);
<add> _asyncNativeRequest.processAsyncOperation(this, new AsyncResponseProcessor<RT>() {
<add> @Override
<add> public void processAsyncResponse(RT _response) throws Exception {
<add> setExceptionHandler(oldExceptionHandler);
<add> _asyncResponseProcessor.processAsyncResponse(_response);
<add> }
<add> });
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 5a0745c7ab94aa1f56cc486aa6ca239b848c4acb | 0 | mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData | /*******************************************************************************
* Copyright © 2017 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
******************************************************************************/
package uk.ac.ebi.phenotype.web.controller.registerinterest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.header.writers.frameoptions.AllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
/**
* Created by mrelac on 12/06/2017.
*
* Design of sample login screen taken from http://websystique.com/spring-security/spring-security-4-hibernate-annotation-example/
*/
@Configuration
@EnableWebSecurity
@PropertySource("file:${user.home}/configfiles/${profile}/application.properties")
@ComponentScan("uk.ac.ebi.phenotype.web.controller.registerinterest")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private DataSource riDataSource;
// Must use qualifier to get ri database; otherwise, komp2 is served up.
@Inject
public WebSecurityConfig(@Qualifier("riDataSource") DataSource riDataSource) {
this.riDataSource = riDataSource;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
AllowFromStrategy strategy = httpServletRequest -> "www.immunophenotype.org, wwwdev.ebi.ac.uk";
http
.headers()
// in spring-security-core 4.2.8 , the addHeaderWriter line commented out below is broken: specifying X-Frame-Options:ALLOW-FROM also incorrectly adds DENY to the same header so it reads ALLOW-FROM DENY.
// see https://github.com/spring-projects/spring-security/issues/123
// .addHeaderWriter(new XFrameOptionsHeaderWriter(new WhiteListedAllowFromStrategy(Arrays.asList("www.immunophenotype.org", "wwwdev.ebi.ac.uk"))))
.frameOptions().disable()
.addHeaderWriter(new XFrameOptionsHeaderWriter(strategy))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/authenticated/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/summary").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/registration/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/unregistration/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/account").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.POST, "/account").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET,"/**")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/Access_Denied")
.and()
.formLogin()
.loginPage("/rilogin")
.failureUrl("/rilogin?error")
.successHandler(new RiSavedRequestAwareAuthenticationSuccessHandler())
.usernameParameter("ssoId")
.passwordParameter("password")
.and().csrf().disable()
;
}
@Autowired
public void configureGlobalSecurityJdbc(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(bcryptPasswordEncoder())
.and()
.jdbcAuthentication()
.dataSource(riDataSource)
.rolePrefix("ROLE_")
.usersByUsernameQuery("SELECT address AS username, password, 'true' AS enabled FROM contact WHERE address = ?")
.authoritiesByUsernameQuery("SELECT c.address AS username, cr.role FROM contact c JOIN contact_role cr ON cr.contact_pk = c.pk WHERE c.address = ?")
;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
// public class RiSavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
// protected final Log logger = LogFactory.getLog(this.getClass());
// private RequestCache requestCache = new HttpSessionRequestCache();
//
// public RiSavedRequestAwareAuthenticationSuccessHandler() {
// }
//
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
// logger.info("RiSavedRequest: Authentication Success!");
// SavedRequest savedRequest = this.requestCache.getRequest(request, response);
// if (savedRequest == null) {
// logger.info("RiSavedRequest: savedRequest is null.");
// super.onAuthenticationSuccess(request, response, authentication);
// } else {
// String targetUrlParameter = this.getTargetUrlParameter();
// if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
// this.clearAuthenticationAttributes(request);
// String targetUrl = savedRequest.getRedirectUrl();
// this.logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
// } else {
// logger.info("RiSavedRequest: removing request.");
// this.requestCache.removeRequest(request, response);
// super.onAuthenticationSuccess(request, response, authentication);
// }
// }
// }
//
// public void setRequestCache(RequestCache requestCache) {
// this.requestCache = requestCache;
// }
// }
public class RiSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private RequestCache requestCache = new HttpSessionRequestCache();
public RiSavedRequestAwareAuthenticationSuccessHandler() {
}
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
logger.info("RiSavedRequest: Authentication Success!");
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest == null) {
logger.info("RiSavedRequest: savedRequest is null.");
super.onAuthenticationSuccess(request, response, authentication);
} else {
String targetUrlParameter = this.getTargetUrlParameter();
if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
this.clearAuthenticationAttributes(request);
String targetUrl = savedRequest.getRedirectUrl();
this.logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
} else {
logger.info("RiSavedRequest: removing request.");
this.requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}
} | web/src/main/java/uk/ac/ebi/phenotype/web/controller/registerinterest/WebSecurityConfig.java | /*******************************************************************************
* Copyright © 2017 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
******************************************************************************/
package uk.ac.ebi.phenotype.web.controller.registerinterest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.header.writers.frameoptions.AllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
/**
* Created by mrelac on 12/06/2017.
*
* Design of sample login screen taken from http://websystique.com/spring-security/spring-security-4-hibernate-annotation-example/
*/
@Configuration
@EnableWebSecurity
@PropertySource("file:${user.home}/configfiles/${profile}/application.properties")
@ComponentScan("uk.ac.ebi.phenotype.web.controller.registerinterest")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private DataSource riDataSource;
// Must use qualifier to get ri database; otherwise, komp2 is served up.
@Inject
public WebSecurityConfig(@Qualifier("riDataSource") DataSource riDataSource) {
this.riDataSource = riDataSource;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
AllowFromStrategy strategy = httpServletRequest -> "www.immunophenotype.org, wwwdev.ebi.ac.uk";
http
.headers()
// in spring-security-core 4.2.8 , the addHeaderWriter line commented out below is broken: specifying X-Frame-Options:ALLOW-FROM also incorrectly adds DENY to the same header so it reads ALLOW-FROM DENY.
// see https://github.com/spring-projects/spring-security/issues/123
// .addHeaderWriter(new XFrameOptionsHeaderWriter(new WhiteListedAllowFromStrategy(Arrays.asList("www.immunophenotype.org", "wwwdev.ebi.ac.uk"))))
.frameOptions().disable()
.addHeaderWriter(new XFrameOptionsHeaderWriter(strategy))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/authenticated/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/summary").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/registration/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/unregistration/**").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/account").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.POST, "/account").access("hasRole('USER') or hasRole('ADMIN')")
.antMatchers(HttpMethod.GET,"/**")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/Access_Denied")
.and()
.formLogin()
.loginPage("/rilogin")
.failureUrl("/rilogin?error")
.successHandler(new RiSavedRequestAwareAuthenticationSuccessHandler())
.usernameParameter("ssoId")
.passwordParameter("password")
;
}
@Autowired
public void configureGlobalSecurityJdbc(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(bcryptPasswordEncoder())
.and()
.jdbcAuthentication()
.dataSource(riDataSource)
.rolePrefix("ROLE_")
.usersByUsernameQuery("SELECT address AS username, password, 'true' AS enabled FROM contact WHERE address = ?")
.authoritiesByUsernameQuery("SELECT c.address AS username, cr.role FROM contact c JOIN contact_role cr ON cr.contact_pk = c.pk WHERE c.address = ?")
;
}
@Bean
public PasswordEncoder bcryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
// public class RiSavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
// protected final Log logger = LogFactory.getLog(this.getClass());
// private RequestCache requestCache = new HttpSessionRequestCache();
//
// public RiSavedRequestAwareAuthenticationSuccessHandler() {
// }
//
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
// logger.info("RiSavedRequest: Authentication Success!");
// SavedRequest savedRequest = this.requestCache.getRequest(request, response);
// if (savedRequest == null) {
// logger.info("RiSavedRequest: savedRequest is null.");
// super.onAuthenticationSuccess(request, response, authentication);
// } else {
// String targetUrlParameter = this.getTargetUrlParameter();
// if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
// this.clearAuthenticationAttributes(request);
// String targetUrl = savedRequest.getRedirectUrl();
// this.logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
// this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
// } else {
// logger.info("RiSavedRequest: removing request.");
// this.requestCache.removeRequest(request, response);
// super.onAuthenticationSuccess(request, response, authentication);
// }
// }
// }
//
// public void setRequestCache(RequestCache requestCache) {
// this.requestCache = requestCache;
// }
// }
public class RiSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private RequestCache requestCache = new HttpSessionRequestCache();
public RiSavedRequestAwareAuthenticationSuccessHandler() {
}
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
logger.info("RiSavedRequest: Authentication Success!");
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest == null) {
logger.info("RiSavedRequest: savedRequest is null.");
super.onAuthenticationSuccess(request, response, authentication);
} else {
String targetUrlParameter = this.getTargetUrlParameter();
if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
this.clearAuthenticationAttributes(request);
String targetUrl = savedRequest.getRedirectUrl();
this.logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
} else {
logger.info("RiSavedRequest: removing request.");
this.requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}
} | Disable csrf security temporarily to see if that's why requestcache isn't populated.
| web/src/main/java/uk/ac/ebi/phenotype/web/controller/registerinterest/WebSecurityConfig.java | Disable csrf security temporarily to see if that's why requestcache isn't populated. | <ide><path>eb/src/main/java/uk/ac/ebi/phenotype/web/controller/registerinterest/WebSecurityConfig.java
<ide> .successHandler(new RiSavedRequestAwareAuthenticationSuccessHandler())
<ide> .usernameParameter("ssoId")
<ide> .passwordParameter("password")
<add>
<add>
<add>
<add> .and().csrf().disable()
<ide> ;
<ide> }
<ide> |
|
Java | apache-2.0 | 6794e55ec79a150a6e37c532d68883fbdcaf5292 | 0 | phraktle/lmdbjava,lmdbjava/lmdbjava | /*-
* #%L
* LmdbJava
* %%
* Copyright (C) 2016 The LmdbJava Open Source Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.lmdbjava;
import static jnr.ffi.Memory.allocateDirect;
import static jnr.ffi.NativeType.ADDRESS;
import jnr.ffi.Pointer;
import jnr.ffi.provider.MemoryManager;
import static org.lmdbjava.BufferProxy.MDB_VAL_STRUCT_SIZE;
import static org.lmdbjava.BufferProxy.STRUCT_FIELD_OFFSET_SIZE;
import static org.lmdbjava.Env.SHOULD_CHECK;
import static org.lmdbjava.Library.LIB;
import static org.lmdbjava.Library.RUNTIME;
import static org.lmdbjava.MaskedFlag.isSet;
import static org.lmdbjava.MaskedFlag.mask;
import static org.lmdbjava.ResultCodeMapper.checkRc;
import static org.lmdbjava.Txn.State.DONE;
import static org.lmdbjava.Txn.State.READY;
import static org.lmdbjava.Txn.State.RELEASED;
import static org.lmdbjava.Txn.State.RESET;
import static org.lmdbjava.TxnFlags.MDB_RDONLY_TXN;
/**
* LMDB transaction.
*
* @param <T> buffer type
*/
public final class Txn<T> implements AutoCloseable {
private static final MemoryManager MEM_MGR = RUNTIME.getMemoryManager();
private final Env<T> env;
private final T k;
private final Txn<T> parent;
private final BufferProxy<T> proxy;
private final Pointer ptr;
private final Pointer ptrKey;
private final long ptrKeyAddr;
private final Pointer ptrVal;
private final long ptrValAddr;
private final boolean readOnly;
private State state;
private final T v;
Txn(final Env<T> env, final Txn<T> parent, final BufferProxy<T> proxy,
final TxnFlags... flags) {
this.env = env;
this.proxy = proxy;
final int flagsMask = mask(flags);
this.readOnly = isSet(flagsMask, MDB_RDONLY_TXN);
if (env.isReadOnly() && !this.readOnly) {
throw new EnvIsReadOnly();
}
this.parent = parent;
if (parent != null && parent.isReadOnly() != this.readOnly) {
throw new IncompatibleParent();
}
final Pointer txnPtr = allocateDirect(RUNTIME, ADDRESS);
final Pointer txnParentPtr = parent == null ? null : parent.ptr;
checkRc(LIB.mdb_txn_begin(env.pointer(), txnParentPtr, flagsMask, txnPtr));
ptr = txnPtr.getPointer(0);
this.k = proxy.allocate();
this.v = proxy.allocate();
ptrKey = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
ptrKeyAddr = ptrKey.address();
ptrVal = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
ptrValAddr = ptrVal.address();
state = READY;
}
/**
* Aborts this transaction.
*/
public void abort() {
checkReady();
state = DONE;
LIB.mdb_txn_abort(ptr);
}
/**
* Closes this transaction by aborting if not already committed.
*
* <p>
* Closing the transaction will invoke
* {@link BufferProxy#deallocate(java.lang.Object)} for each read-only buffer
* (ie the key and value).
*/
@Override
public void close() {
if (state == RELEASED) {
return;
}
if (state == READY) {
LIB.mdb_txn_abort(ptr);
}
proxy.deallocate(k);
proxy.deallocate(v);
state = RELEASED;
env.txnRelease(this);
}
/**
* Commits this transaction.
*/
public void commit() {
checkReady();
state = DONE;
checkRc(LIB.mdb_txn_commit(ptr));
}
/**
* Return the transaction's ID.
*
* @return A transaction ID, valid if input is an active transaction
*/
public long getId() {
return LIB.mdb_txn_id(ptr);
}
/**
* Obtains this transaction's parent.
*
* @return the parent transaction (may be null)
*/
public Txn<T> getParent() {
return parent;
}
/**
* Whether this transaction is read-only.
*
* @return if read-only
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Fetch the buffer which holds a read-only view of the LMDI allocated memory.
* Any use of this buffer must comply with the standard LMDB C "mdb_get"
* contract (ie do not modify, do not attempt to release the memory, do not
* use once the transaction or cursor closes, do not use after a write etc).
*
* @return the key buffer (never null)
*/
public T key() {
return k;
}
/**
* Renews a read-only transaction previously released by {@link #reset()}.
*/
public void renew() {
if (state != RESET) {
throw new NotResetException();
}
state = DONE;
checkRc(LIB.mdb_txn_renew(ptr));
state = READY;
}
/**
* Aborts this read-only transaction and resets the transaction handle so it
* can be reused upon calling {@link #renew()}.
*/
public void reset() {
checkReadOnly();
if (state != READY && state != DONE) {
throw new ResetException();
}
state = RESET;
LIB.mdb_txn_reset(ptr);
}
/**
* Fetch the buffer which holds a read-only view of the LMDI allocated memory.
* Any use of this buffer must comply with the standard LMDB C "mdb_get"
* contract (ie do not modify, do not attempt to release the memory, do not
* use once the transaction or cursor closes, do not use after a write etc).
*
* @return the value buffer (never null)
*/
public T val() {
return v;
}
void checkReadOnly() throws ReadOnlyRequiredException {
if (!readOnly) {
throw new ReadOnlyRequiredException();
}
}
void checkReady() throws NotReadyException {
if (state != READY) {
throw new NotReadyException();
}
}
void checkWritesAllowed() throws ReadWriteRequiredException {
if (readOnly) {
throw new ReadWriteRequiredException();
}
}
/**
* Return the state of the transaction.
*
* @return the state
*/
State getState() {
return state;
}
void keyIn(final T key) {
proxy.in(key, ptrKey, ptrKeyAddr);
if (SHOULD_CHECK) {
final long size = ptrKey.getLong(STRUCT_FIELD_OFFSET_SIZE);
if (size <= 0) {
throw new IndexOutOfBoundsException("Keys must be > 0 bytes");
}
if (size > env.getMaxKeySize()) {
throw new IndexOutOfBoundsException("Key too many bytes for Env");
}
}
}
void keyOut() {
proxy.out(k, ptrKey, ptrKeyAddr);
}
Pointer pointer() {
return ptr;
}
Pointer pointerKey() {
return ptrKey;
}
Pointer pointerVal() {
return ptrVal;
}
void valIn(final T val, final boolean zeroLenValAllowed) {
proxy.in(val, ptrVal, ptrValAddr);
if (SHOULD_CHECK && !zeroLenValAllowed) {
final long size = ptrVal.getLong(STRUCT_FIELD_OFFSET_SIZE);
if (size <= 0) {
throw new IndexOutOfBoundsException("Values must be > 0 bytes");
}
}
}
void valIn(final int size) {
if (size <= 0) {
throw new IndexOutOfBoundsException("Reservation must be > 0 bytes");
}
proxy.in(v, size, ptrVal, ptrValAddr);
}
void valOut() {
proxy.out(v, ptrVal, ptrValAddr);
}
/**
* Transaction must abort, has a child, or is invalid.
*/
public static final class BadException extends LmdbNativeException {
static final int MDB_BAD_TXN = -30_782;
private static final long serialVersionUID = 1L;
BadException() {
super(MDB_BAD_TXN, "Transaction must abort, has a child, or is invalid");
}
}
/**
* Invalid reuse of reader locktable slot.
*/
public static final class BadReaderLockException extends LmdbNativeException {
static final int MDB_BAD_RSLOT = -30_783;
private static final long serialVersionUID = 1L;
BadReaderLockException() {
super(MDB_BAD_RSLOT, "Invalid reuse of reader locktable slot");
}
}
/**
* The proposed R-W transaction is incompatible with a R-O Env.
*/
public static class EnvIsReadOnly extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public EnvIsReadOnly() {
super("Read-write Txn incompatible with read-only Env");
}
}
/**
* The proposed transaction is incompatible with its parent transaction.
*/
public static class IncompatibleParent extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public IncompatibleParent() {
super("Transaction incompatible with its parent transaction");
}
}
/**
* Transaction is not in a READY state.
*/
public static final class NotReadyException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public NotReadyException() {
super("Transaction is not in ready state");
}
}
/**
* The current transaction has not been reset.
*/
public static class NotResetException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public NotResetException() {
super("Transaction has not been reset");
}
}
/**
* The current transaction is not a read-only transaction.
*/
public static class ReadOnlyRequiredException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ReadOnlyRequiredException() {
super("Not a read-only transaction");
}
}
/**
* The current transaction is not a read-write transaction.
*/
public static class ReadWriteRequiredException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ReadWriteRequiredException() {
super("Not a read-write transaction");
}
}
/**
* The current transaction has already been reset.
*/
public static class ResetException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ResetException() {
super("Transaction has already been reset");
}
}
/**
* Transaction has too many dirty pages.
*/
public static final class TxFullException extends LmdbNativeException {
static final int MDB_TXN_FULL = -30_788;
private static final long serialVersionUID = 1L;
TxFullException() {
super(MDB_TXN_FULL, "Transaction has too many dirty pages");
}
}
/**
* Transaction states.
*/
enum State {
READY, DONE, RESET, RELEASED
}
}
| src/main/java/org/lmdbjava/Txn.java | /*-
* #%L
* LmdbJava
* %%
* Copyright (C) 2016 The LmdbJava Open Source Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.lmdbjava;
import static jnr.ffi.Memory.allocateDirect;
import static jnr.ffi.NativeType.ADDRESS;
import jnr.ffi.Pointer;
import jnr.ffi.provider.MemoryManager;
import static org.lmdbjava.BufferProxy.MDB_VAL_STRUCT_SIZE;
import static org.lmdbjava.BufferProxy.STRUCT_FIELD_OFFSET_SIZE;
import static org.lmdbjava.Env.SHOULD_CHECK;
import static org.lmdbjava.Library.LIB;
import static org.lmdbjava.Library.RUNTIME;
import static org.lmdbjava.MaskedFlag.isSet;
import static org.lmdbjava.MaskedFlag.mask;
import static org.lmdbjava.ResultCodeMapper.checkRc;
import static org.lmdbjava.Txn.State.DONE;
import static org.lmdbjava.Txn.State.READY;
import static org.lmdbjava.Txn.State.RELEASED;
import static org.lmdbjava.Txn.State.RESET;
import static org.lmdbjava.TxnFlags.MDB_RDONLY_TXN;
/**
* LMDB transaction.
*
* @param <T> buffer type
*/
public final class Txn<T> implements AutoCloseable {
private static final MemoryManager MEM_MGR = RUNTIME.getMemoryManager();
private final Env<T> env;
private final T k;
private final Txn<T> parent;
private final BufferProxy<T> proxy;
private final Pointer ptr;
private final Pointer ptrKey;
private final long ptrKeyAddr;
private final Pointer ptrVal;
private final long ptrValAddr;
private final boolean readOnly;
private State state;
private final T v;
Txn(final Env<T> env, final Txn<T> parent, final BufferProxy<T> proxy,
final TxnFlags... flags) {
this.env = env;
this.proxy = proxy;
final int flagsMask = mask(flags);
this.readOnly = isSet(flagsMask, MDB_RDONLY_TXN);
if (env.isReadOnly() && !this.readOnly) {
throw new EnvIsReadOnly();
}
this.parent = parent;
if (parent != null && parent.isReadOnly() != this.readOnly) {
throw new IncompatibleParent();
}
final Pointer txnPtr = allocateDirect(RUNTIME, ADDRESS);
final Pointer txnParentPtr = parent == null ? null : parent.ptr;
checkRc(LIB.mdb_txn_begin(env.pointer(), txnParentPtr, flagsMask, txnPtr));
ptr = txnPtr.getPointer(0);
this.k = proxy.allocate();
this.v = proxy.allocate();
ptrKey = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
ptrKeyAddr = ptrKey.address();
ptrVal = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
ptrValAddr = ptrVal.address();
state = READY;
}
/**
* Aborts this transaction.
*/
public void abort() {
checkReady();
state = DONE;
LIB.mdb_txn_abort(ptr);
}
/**
* Closes this transaction by aborting if not already committed.
*
* <p>
* Closing the transaction will invoke
* {@link BufferProxy#deallocate(java.lang.Object)} for each read-only buffer
* (ie the key and value).
*/
@Override
public void close() {
if (state == RELEASED) {
return;
}
if (state == READY) {
LIB.mdb_txn_abort(ptr);
}
proxy.deallocate(k);
proxy.deallocate(v);
state = RELEASED;
env.txnRelease(this);
}
/**
* Commits this transaction.
*/
public void commit() {
checkReady();
state = DONE;
checkRc(LIB.mdb_txn_commit(ptr));
}
/**
* Return the transaction's ID.
*
* @return A transaction ID, valid if input is an active transaction
*/
public long getId() {
return LIB.mdb_txn_id(ptr);
}
/**
* Obtains this transaction's parent.
*
* @return the parent transaction (may be null)
*/
public Txn<T> getParent() {
return parent;
}
/**
* Whether this transaction is read-only.
*
* @return if read-only
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Fetch the buffer which holds a read-only view of the LMDI allocated memory.
* Any use of this buffer must comply with the standard LMDB C "mdb_get"
* contract (ie do not modify, do not attempt to release the memory, do not
* use once the transaction or cursor closes, do not use after a write etc).
*
* @return the key buffer (never null)
*/
public T key() {
return k;
}
/**
* Renews a read-only transaction previously released by {@link #reset()}.
*/
public void renew() {
if (state != RESET) {
throw new NotResetException();
}
state = DONE;
checkRc(LIB.mdb_txn_renew(ptr));
state = READY;
}
/**
* Aborts this read-only transaction and resets the transaction handle so it
* can be reused upon calling {@link #renew()}.
*/
public void reset() {
checkReadOnly();
if (state != READY && state != DONE) {
throw new ResetException();
}
state = RESET;
LIB.mdb_txn_reset(ptr);
}
/**
* Fetch the buffer which holds a read-only view of the LMDI allocated memory.
* Any use of this buffer must comply with the standard LMDB C "mdb_get"
* contract (ie do not modify, do not attempt to release the memory, do not
* use once the transaction or cursor closes, do not use after a write etc).
*
* @return the value buffer (never null)
*/
public T val() {
return v;
}
void checkReadOnly() throws ReadOnlyRequiredException {
if (!readOnly) {
throw new ReadOnlyRequiredException();
}
}
void checkReady() throws NotReadyException {
if (state != READY) {
throw new NotReadyException();
}
}
void checkWritesAllowed() throws ReadWriteRequiredException {
if (readOnly) {
throw new ReadWriteRequiredException();
}
}
/**
* Return the state of the transaction.
*
* @return the state
*/
State getState() {
return state;
}
void keyIn(final T key) {
proxy.in(key, ptrKey, ptrKeyAddr);
if (SHOULD_CHECK) {
final long size = ptrKey.getLong(STRUCT_FIELD_OFFSET_SIZE);
if (size <= 0) {
throw new IndexOutOfBoundsException("Keys must be > 0 bytes");
}
if (size > env.getMaxKeySize()) {
throw new IndexOutOfBoundsException("Key too many bytes for Env");
}
}
}
void keyOut() {
proxy.out(k, ptrKey, ptrKeyAddr);
}
Pointer pointer() {
return ptr;
}
Pointer pointerKey() {
return ptrKey;
}
Pointer pointerVal() {
return ptrVal;
}
void valIn(final T val, final boolean zeroLenValAllowed) {
proxy.in(val, ptrVal, ptrValAddr);
if (SHOULD_CHECK && !zeroLenValAllowed) {
final long size = ptrVal.getLong(STRUCT_FIELD_OFFSET_SIZE);
if (size <= 0) {
throw new IndexOutOfBoundsException("Values must be > 0 bytes");
}
}
}
void valIn(final int size) {
if (size <= 0) {
throw new IndexOutOfBoundsException("Reservation must be > 0 bytes");
}
proxy.in(v, size, ptrVal, ptrValAddr);
}
void valOut() {
proxy.out(v, ptrVal, ptrValAddr);
}
/**
* Transaction must abort, has a child, or is invalid.
*/
public static final class BadException extends LmdbNativeException {
static final int MDB_BAD_TXN = -30_782;
private static final long serialVersionUID = 1L;
BadException() {
super(MDB_BAD_TXN, "Transaction must abort, has a child, or is invalid");
}
}
/**
* Invalid reuse of reader locktable slot.
*/
public static final class BadReaderLockException extends LmdbNativeException {
static final int MDB_BAD_RSLOT = -30_783;
private static final long serialVersionUID = 1L;
BadReaderLockException() {
super(MDB_BAD_RSLOT, "Invalid reuse of reader locktable slot");
}
}
/**
* The proposed R-W transaction is incompatible with a R-O Env.
*/
public static class EnvIsReadOnly extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public EnvIsReadOnly() {
super("Read-write Txn incompatible with read-only Env");
}
}
/**
* The proposed transaction is incompatible with its parent transaction.
*/
public static class IncompatibleParent extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public IncompatibleParent() {
super("Transaction incompatible with its parent transaction");
}
}
/**
* Transaction is not in a READY state.
*/
public static final class NotReadyException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public NotReadyException() {
super("Transaction is not in ready state");
}
}
/**
* The current transaction has not been reset.
*/
public static class NotResetException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public NotResetException() {
super("Transaction has not been reset");
}
}
/**
* The current transaction is not a read-only transaction.
*/
public static class ReadOnlyRequiredException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ReadOnlyRequiredException() {
super("Not a read-only transaction");
}
}
/**
* The current transaction is not a read-write transaction.
*/
public static class ReadWriteRequiredException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ReadWriteRequiredException() {
super("Not a read-write transaction");
}
}
/**
* The current transaction has already been reset.
*/
public static class ResetException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public ResetException() {
super("Transaction has already been reset");
}
}
/**
* Transaction has too many dirty pages.
*/
public static final class TxFullException extends LmdbNativeException {
static final int MDB_TXN_FULL = -30_788;
private static final long serialVersionUID = 1L;
TxFullException() {
super(MDB_TXN_FULL, "Transaction has too many dirty pages");
}
}
/**
* Transaction states.
*/
enum State {
READY, DONE, RESET, RELEASED
}
}
| Formatting only
| src/main/java/org/lmdbjava/Txn.java | Formatting only | <ide><path>rc/main/java/org/lmdbjava/Txn.java
<ide> * @param <T> buffer type
<ide> */
<ide> public final class Txn<T> implements AutoCloseable {
<del>
<add>
<ide> private static final MemoryManager MEM_MGR = RUNTIME.getMemoryManager();
<ide> private final Env<T> env;
<ide> private final T k;
<ide> private final boolean readOnly;
<ide> private State state;
<ide> private final T v;
<del>
<add>
<ide> Txn(final Env<T> env, final Txn<T> parent, final BufferProxy<T> proxy,
<ide> final TxnFlags... flags) {
<ide> this.env = env;
<ide> final Pointer txnParentPtr = parent == null ? null : parent.ptr;
<ide> checkRc(LIB.mdb_txn_begin(env.pointer(), txnParentPtr, flagsMask, txnPtr));
<ide> ptr = txnPtr.getPointer(0);
<del>
<add>
<ide> this.k = proxy.allocate();
<ide> this.v = proxy.allocate();
<ide> ptrKey = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
<ide> ptrKeyAddr = ptrKey.address();
<ide> ptrVal = MEM_MGR.allocateTemporary(MDB_VAL_STRUCT_SIZE, false);
<ide> ptrValAddr = ptrVal.address();
<del>
<add>
<ide> state = READY;
<ide> }
<ide>
<ide> public T val() {
<ide> return v;
<ide> }
<del>
<add>
<ide> void checkReadOnly() throws ReadOnlyRequiredException {
<ide> if (!readOnly) {
<ide> throw new ReadOnlyRequiredException();
<ide> }
<ide> }
<del>
<add>
<ide> void checkReady() throws NotReadyException {
<ide> if (state != READY) {
<ide> throw new NotReadyException();
<ide> }
<ide> }
<del>
<add>
<ide> void checkWritesAllowed() throws ReadWriteRequiredException {
<ide> if (readOnly) {
<ide> throw new ReadWriteRequiredException();
<ide> State getState() {
<ide> return state;
<ide> }
<del>
<add>
<ide> void keyIn(final T key) {
<ide> proxy.in(key, ptrKey, ptrKeyAddr);
<ide> if (SHOULD_CHECK) {
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> void keyOut() {
<ide> proxy.out(k, ptrKey, ptrKeyAddr);
<ide> }
<del>
<add>
<ide> Pointer pointer() {
<ide> return ptr;
<ide> }
<del>
<add>
<ide> Pointer pointerKey() {
<ide> return ptrKey;
<ide> }
<del>
<add>
<ide> Pointer pointerVal() {
<ide> return ptrVal;
<ide> }
<del>
<add>
<ide> void valIn(final T val, final boolean zeroLenValAllowed) {
<ide> proxy.in(val, ptrVal, ptrValAddr);
<ide> if (SHOULD_CHECK && !zeroLenValAllowed) {
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> void valIn(final int size) {
<ide> if (size <= 0) {
<ide> throw new IndexOutOfBoundsException("Reservation must be > 0 bytes");
<ide> }
<ide> proxy.in(v, size, ptrVal, ptrValAddr);
<ide> }
<del>
<add>
<ide> void valOut() {
<ide> proxy.out(v, ptrVal, ptrValAddr);
<ide> }
<ide> * Transaction must abort, has a child, or is invalid.
<ide> */
<ide> public static final class BadException extends LmdbNativeException {
<del>
<add>
<ide> static final int MDB_BAD_TXN = -30_782;
<ide> private static final long serialVersionUID = 1L;
<del>
<add>
<ide> BadException() {
<ide> super(MDB_BAD_TXN, "Transaction must abort, has a child, or is invalid");
<ide> }
<ide> * Invalid reuse of reader locktable slot.
<ide> */
<ide> public static final class BadReaderLockException extends LmdbNativeException {
<del>
<add>
<ide> static final int MDB_BAD_RSLOT = -30_783;
<ide> private static final long serialVersionUID = 1L;
<del>
<add>
<ide> BadReaderLockException() {
<ide> super(MDB_BAD_RSLOT, "Invalid reuse of reader locktable slot");
<ide> }
<ide> * The proposed R-W transaction is incompatible with a R-O Env.
<ide> */
<ide> public static class EnvIsReadOnly extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * The proposed transaction is incompatible with its parent transaction.
<ide> */
<ide> public static class IncompatibleParent extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * Transaction is not in a READY state.
<ide> */
<ide> public static final class NotReadyException extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * The current transaction has not been reset.
<ide> */
<ide> public static class NotResetException extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * The current transaction is not a read-only transaction.
<ide> */
<ide> public static class ReadOnlyRequiredException extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * The current transaction is not a read-write transaction.
<ide> */
<ide> public static class ReadWriteRequiredException extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * The current transaction has already been reset.
<ide> */
<ide> public static class ResetException extends LmdbException {
<del>
<add>
<ide> private static final long serialVersionUID = 1L;
<ide>
<ide> /**
<ide> * Transaction has too many dirty pages.
<ide> */
<ide> public static final class TxFullException extends LmdbNativeException {
<del>
<add>
<ide> static final int MDB_TXN_FULL = -30_788;
<ide> private static final long serialVersionUID = 1L;
<del>
<add>
<ide> TxFullException() {
<ide> super(MDB_TXN_FULL, "Transaction has too many dirty pages");
<ide> }
<ide> enum State {
<ide> READY, DONE, RESET, RELEASED
<ide> }
<del>
<add>
<ide> } |
|
Java | mit | c51e745bae3529bfdb24e5afa33a865bf2f1ef88 | 0 | iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable | /*
* Copyright (c) 2010, The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.traversals;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.datasources.providers.ShardDataProvider;
import org.broadinstitute.sting.gatk.datasources.shards.Shard;
import org.broadinstitute.sting.gatk.walkers.Walker;
import org.broadinstitute.sting.gatk.ReadMetrics;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Map;
public abstract class TraversalEngine<M,T,WalkerType extends Walker<M,T>,ProviderType extends ShardDataProvider> {
// Time in milliseconds since we initialized this engine
private long startTime = -1;
private long lastProgressPrintTime = -1; // When was the last time we printed our progress?
// How long can we go without printing some progress info?
private final long MAX_PROGRESS_PRINT_TIME = 30 * 1000; // in seconds
private final long N_RECORDS_TO_PRINT = 1000000;
// for performance log
private static final boolean PERFORMANCE_LOG_ENABLED = true;
private PrintStream performanceLog = null;
private long lastPerformanceLogPrintTime = -1; // When was the last time we printed to the performance log?
private final long PERFORMANCE_LOG_PRINT_FREQUENCY = 1 * 1000; // in seconds
/** our log, which we want to capture anything from this class */
protected static Logger logger = Logger.getLogger(TraversalEngine.class);
protected GenomeAnalysisEngine engine;
/**
* Gets the named traversal type associated with the given traversal.
* @return A user-friendly name for the given traversal type.
*/
protected abstract String getTraversalType();
/**
* @param curTime (current runtime, in millisecs)
* @param lastPrintTime the last time we printed, in machine milliseconds
* @param printFreq maximum permitted difference between last print and current times
*
* @return true if the maximum interval (in millisecs) has passed since the last printing
*/
private boolean maxElapsedIntervalForPrinting(final long curTime, long lastPrintTime, long printFreq) {
return (curTime - lastPrintTime) > printFreq;
}
/**
* Forward request to printProgress
*
* @param shard the given shard currently being processed.
* @param loc the location
*/
public void printProgress(Shard shard,GenomeLoc loc) {
// A bypass is inserted here for unit testing.
// TODO: print metrics outside of the traversal engine to more easily handle cumulative stats.
ReadMetrics cumulativeMetrics = engine.getCumulativeMetrics() != null ? engine.getCumulativeMetrics().clone() : new ReadMetrics();
cumulativeMetrics.incrementMetrics(shard.getReadMetrics());
printProgress(loc, cumulativeMetrics, false);
}
/**
* Utility routine that prints out process information (including timing) every N records or
* every M seconds, for N and M set in global variables.
*
* @param loc Current location
* @param metrics Metrics of reads filtered in/out.
* @param mustPrint If true, will print out info, regardless of nRecords or time interval
*/
private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) {
final long nRecords = metrics.getNumIterations();
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
final double secsPer1MReads = (elapsed * 1000000.0) / Math.max(nRecords, 1);
if (mustPrint
|| nRecords == 1
|| nRecords % N_RECORDS_TO_PRINT == 0
|| maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, MAX_PROGRESS_PRINT_TIME)) {
lastProgressPrintTime = curTime;
if ( nRecords == 1 )
logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]");
else {
if (loc != null)
logger.info(String.format("[PROGRESS] Traversed to %s, processing %,d %s in %.2f secs (%.2f secs per 1M %s)", loc, nRecords, getTraversalType(), elapsed, secsPer1MReads, getTraversalType()));
else
logger.info(String.format("[PROGRESS] Traversed %,d %s in %.2f secs (%.2f secs per 1M %s)", nRecords, getTraversalType(), elapsed, secsPer1MReads, getTraversalType()));
}
}
//
// code to process the performance log
//
// TODO -- should be controlled by Queue so that .out and .performance.log comes out
//
if ( PERFORMANCE_LOG_ENABLED && performanceLog == null
&& engine != null && engine.getArguments().performanceLog != null ) {
try {
performanceLog = new PrintStream(new FileOutputStream(engine.getArguments().performanceLog));
performanceLog.println(Utils.join("\t", Arrays.asList("elapsed.time", "units.processed", "processing.speed")));
} catch (FileNotFoundException e) {
throw new UserException.CouldNotCreateOutputFile(engine.getArguments().performanceLog, e);
}
}
if ( performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY)) {
lastPerformanceLogPrintTime = curTime;
if ( nRecords > 1 ) performanceLog.printf("%.2f\t%d\t%.2f%n", elapsed, nRecords, secsPer1MReads);
}
}
/**
* Called after a traversal to print out information about the traversal process
*/
public void printOnTraversalDone(ReadMetrics cumulativeMetrics) {
printProgress(null, cumulativeMetrics, true);
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
// count up the number of skipped reads by summing over all filters
long nSkippedReads = 0L;
for ( Map.Entry<Class, Long> countsByFilter: cumulativeMetrics.getCountsByFilter().entrySet())
nSkippedReads += countsByFilter.getValue();
logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours", elapsed, elapsed / 60, elapsed / 3600));
if ( cumulativeMetrics.getNumReadsSeen() > 0 )
logger.info(String.format("%d reads were filtered out during traversal out of %d total (%.2f%%)",
nSkippedReads,
cumulativeMetrics.getNumReadsSeen(),
100.0 * MathUtils.ratio(nSkippedReads,cumulativeMetrics.getNumReadsSeen())));
for ( Map.Entry<Class, Long> filterCounts : cumulativeMetrics.getCountsByFilter().entrySet() ) {
long count = filterCounts.getValue();
logger.info(String.format(" -> %d reads (%.2f%% of total) failing %s",
count, 100.0 * MathUtils.ratio(count,cumulativeMetrics.getNumReadsSeen()), Utils.getClassName(filterCounts.getKey())));
}
if ( performanceLog != null ) performanceLog.close();
}
/**
* Initialize the traversal engine. After this point traversals can be run over the data
* @param engine GenomeAnalysisEngine for this traversal
*/
public void initialize(GenomeAnalysisEngine engine) {
this.engine = engine;
}
/**
* Should be called to indicate that we're going to process records and the timer should start ticking
*/
public void startTimers() {
lastProgressPrintTime = startTime = System.currentTimeMillis();
}
/**
* this method must be implemented by all traversal engines
*
* @param walker the walker to run with
* @param dataProvider the data provider that generates data given the shard
* @param sum the accumulator
*
* @return an object of the reduce type
*/
public abstract T traverse(WalkerType walker,
ProviderType dataProvider,
T sum);
}
| java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java | /*
* Copyright (c) 2010, The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.traversals;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.datasources.providers.ShardDataProvider;
import org.broadinstitute.sting.gatk.datasources.shards.Shard;
import org.broadinstitute.sting.gatk.walkers.Walker;
import org.broadinstitute.sting.gatk.ReadMetrics;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Map;
public abstract class TraversalEngine<M,T,WalkerType extends Walker<M,T>,ProviderType extends ShardDataProvider> {
// Time in milliseconds since we initialized this engine
private long startTime = -1;
private long lastProgressPrintTime = -1; // When was the last time we printed our progress?
// How long can we go without printing some progress info?
private final long MAX_PROGRESS_PRINT_TIME = 30 * 1000; // in seconds
private final long N_RECORDS_TO_PRINT = 1000000;
// for performance log
private static final boolean PERFORMANCE_LOG_ENABLED = true;
private PrintStream performanceLog = null;
private long lastPerformanceLogPrintTime = -1; // When was the last time we printed to the performance log?
private final long PERFORMANCE_LOG_PRINT_FREQUENCY = 1 * 1000; // in seconds
/** our log, which we want to capture anything from this class */
protected static Logger logger = Logger.getLogger(TraversalEngine.class);
protected GenomeAnalysisEngine engine;
/**
* Gets the named traversal type associated with the given traversal.
* @return A user-friendly name for the given traversal type.
*/
protected abstract String getTraversalType();
/**
* @param curTime (current runtime, in millisecs)
* @param lastPrintTime the last time we printed, in machine milliseconds
* @param printFreq maximum permitted difference between last print and current times
*
* @return true if the maximum interval (in millisecs) has passed since the last printing
*/
private boolean maxElapsedIntervalForPrinting(final long curTime, long lastPrintTime, long printFreq) {
return (curTime - lastPrintTime) > printFreq;
}
/**
* Forward request to printProgress
*
* @param shard the given shard currently being processed.
* @param loc the location
*/
public void printProgress(Shard shard,GenomeLoc loc) {
// A bypass is inserted here for unit testing.
// TODO: print metrics outside of the traversal engine to more easily handle cumulative stats.
ReadMetrics cumulativeMetrics = engine.getCumulativeMetrics() != null ? engine.getCumulativeMetrics().clone() : new ReadMetrics();
cumulativeMetrics.incrementMetrics(shard.getReadMetrics());
printProgress(loc, cumulativeMetrics, false);
}
/**
* Utility routine that prints out process information (including timing) every N records or
* every M seconds, for N and M set in global variables.
*
* @param loc Current location
* @param metrics Metrics of reads filtered in/out.
* @param mustPrint If true, will print out info, regardless of nRecords or time interval
*/
private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) {
final long nRecords = metrics.getNumIterations();
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
final double secsPer1MReads = (elapsed * 1000000.0) / Math.max(nRecords, 1);
if (mustPrint
|| nRecords == 1
|| nRecords % N_RECORDS_TO_PRINT == 0
|| maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, MAX_PROGRESS_PRINT_TIME)) {
lastProgressPrintTime = curTime;
if ( nRecords == 1 )
logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]");
else {
if (loc != null)
logger.info(String.format("[PROGRESS] Traversed to %s, processing %,d %s in %.2f secs (%.2f secs per 1M %s)", loc, nRecords, getTraversalType(), elapsed, secsPer1MReads, getTraversalType()));
else
logger.info(String.format("[PROGRESS] Traversed %,d %s in %.2f secs (%.2f secs per 1M %s)", nRecords, getTraversalType(), elapsed, secsPer1MReads, getTraversalType()));
}
}
//
// code to process the performance log
//
// TODO -- should be controlled by Queue so that .out and .performance.log comes out
//
if ( PERFORMANCE_LOG_ENABLED && performanceLog == null && engine.getArguments().performanceLog != null ) {
try {
performanceLog = new PrintStream(new FileOutputStream(engine.getArguments().performanceLog));
performanceLog.println(Utils.join("\t", Arrays.asList("elapsed.time", "units.processed", "processing.speed")));
} catch (FileNotFoundException e) {
throw new UserException.CouldNotCreateOutputFile(engine.getArguments().performanceLog, e);
}
}
if ( performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY)) {
lastPerformanceLogPrintTime = curTime;
if ( nRecords > 1 ) performanceLog.printf("%.2f\t%d\t%.2f%n", elapsed, nRecords, secsPer1MReads);
}
}
/**
* Called after a traversal to print out information about the traversal process
*/
public void printOnTraversalDone(ReadMetrics cumulativeMetrics) {
printProgress(null, cumulativeMetrics, true);
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
// count up the number of skipped reads by summing over all filters
long nSkippedReads = 0L;
for ( Map.Entry<Class, Long> countsByFilter: cumulativeMetrics.getCountsByFilter().entrySet())
nSkippedReads += countsByFilter.getValue();
logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours", elapsed, elapsed / 60, elapsed / 3600));
if ( cumulativeMetrics.getNumReadsSeen() > 0 )
logger.info(String.format("%d reads were filtered out during traversal out of %d total (%.2f%%)",
nSkippedReads,
cumulativeMetrics.getNumReadsSeen(),
100.0 * MathUtils.ratio(nSkippedReads,cumulativeMetrics.getNumReadsSeen())));
for ( Map.Entry<Class, Long> filterCounts : cumulativeMetrics.getCountsByFilter().entrySet() ) {
long count = filterCounts.getValue();
logger.info(String.format(" -> %d reads (%.2f%% of total) failing %s",
count, 100.0 * MathUtils.ratio(count,cumulativeMetrics.getNumReadsSeen()), Utils.getClassName(filterCounts.getKey())));
}
if ( performanceLog != null ) performanceLog.close();
}
/**
* Initialize the traversal engine. After this point traversals can be run over the data
* @param engine GenomeAnalysisEngine for this traversal
*/
public void initialize(GenomeAnalysisEngine engine) {
this.engine = engine;
}
/**
* Should be called to indicate that we're going to process records and the timer should start ticking
*/
public void startTimers() {
lastProgressPrintTime = startTime = System.currentTimeMillis();
}
/**
* this method must be implemented by all traversal engines
*
* @param walker the walker to run with
* @param dataProvider the data provider that generates data given the shard
* @param sum the accumulator
*
* @return an object of the reduce type
*/
public abstract T traverse(WalkerType walker,
ProviderType dataProvider,
T sum);
}
| The engine can be null in a unit test, so check for it
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@4923 348d0f76-0448-11de-a6fe-93d51630548a
| java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java | The engine can be null in a unit test, so check for it | <ide><path>ava/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java
<ide> //
<ide> // TODO -- should be controlled by Queue so that .out and .performance.log comes out
<ide> //
<del> if ( PERFORMANCE_LOG_ENABLED && performanceLog == null && engine.getArguments().performanceLog != null ) {
<add> if ( PERFORMANCE_LOG_ENABLED && performanceLog == null
<add> && engine != null && engine.getArguments().performanceLog != null ) {
<ide> try {
<ide> performanceLog = new PrintStream(new FileOutputStream(engine.getArguments().performanceLog));
<ide> performanceLog.println(Utils.join("\t", Arrays.asList("elapsed.time", "units.processed", "processing.speed"))); |
|
Java | mit | 11782599344dfd0bfd95357abeb3734d7d32a725 | 0 | LightningDevStudios/CircuitCrawler | package com.lds.game.entity;
import com.lds.Vector2f;
public class Teleporter extends StaticEnt
{
protected boolean active;
public Teleporter(float size, float xPos, float yPos, float angle, float xScl, float yScl, boolean isSolid, boolean circular, boolean willCollide)
{
super(size, xPos, yPos, angle, xScl, yScl, isSolid, circular, willCollide);
active = false;
}
public Teleporter(float size, float xPos, float yPos)
{
super(size, xPos, yPos, 0.0f, 1.0f, 1.0f, true, false, false);
active = false;
}
public Vector2f getPos()
{
return new Vector2f(getXPos(),getYPos());
}
@Override
public void interact (Entity ent)
{
if(active == false)
{
((PhysEnt) ent).setPos(TeleporterLinker.getLinkedPos(this).getX(), TeleporterLinker.getLinkedPos(this).getY());
}
}
@Override
public void uninteract (Entity ent)
{
active = false;
}
public void setActive(boolean bool)
{
active = bool;
}
}
| src/com/lds/game/entity/Teleporter.java | package com.lds.game.entity;
import com.lds.Vector2f;
public class Teleporter extends StaticEnt
{
protected boolean active;
protected Object tempEnt;
public Teleporter(float size, float xPos, float yPos, float angle, float xScl, float yScl, boolean isSolid, boolean circular, boolean willCollide)
{
super(size, xPos, yPos, angle, xScl, yScl, isSolid, circular, willCollide);
active = false;
}
public Teleporter(float size, float xPos, float yPos)
{
super(size, xPos, yPos, 0.0f, 1.0f, 1.0f, true, false, false);
active = false;
}
public Vector2f getPos()
{
return new Vector2f(getXPos(),getYPos());
}
@Override
public void interact (Entity ent)
{
if(active == false)
{
((PhysEnt) ent).setPos(TeleporterLinker.getLinkedPos(this).getX(), TeleporterLinker.getLinkedPos(this).getY());
tempEnt = ent;
}
}
@Override
public void uninteract (Entity ent)
{
active = false;
}
public void setActive(boolean bool)
{
active = bool;
}
}
| nothin | src/com/lds/game/entity/Teleporter.java | nothin | <ide><path>rc/com/lds/game/entity/Teleporter.java
<ide> public class Teleporter extends StaticEnt
<ide> {
<ide> protected boolean active;
<del> protected Object tempEnt;
<ide>
<ide> public Teleporter(float size, float xPos, float yPos, float angle, float xScl, float yScl, boolean isSolid, boolean circular, boolean willCollide)
<ide> {
<ide> if(active == false)
<ide> {
<ide> ((PhysEnt) ent).setPos(TeleporterLinker.getLinkedPos(this).getX(), TeleporterLinker.getLinkedPos(this).getY());
<del> tempEnt = ent;
<ide> }
<ide> }
<ide> |
|
Java | mit | 114069c76b8c7b40433144003f4c6793c71039be | 0 | GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.session.ws.rs;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.gluu.model.security.Identity;
import org.gluu.oxauth.audit.ApplicationAuditLogger;
import org.gluu.oxauth.model.audit.Action;
import org.gluu.oxauth.model.audit.OAuth2AuditLog;
import org.gluu.oxauth.model.authorize.AuthorizeRequestParam;
import org.gluu.oxauth.model.common.AuthorizationGrant;
import org.gluu.oxauth.model.common.AuthorizationGrantList;
import org.gluu.oxauth.model.common.SessionId;
import org.gluu.oxauth.model.config.Constants;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.oxauth.model.error.ErrorResponseFactory;
import org.gluu.oxauth.model.gluu.GluuErrorResponseType;
import org.gluu.oxauth.model.registration.Client;
import org.gluu.oxauth.model.session.EndSessionErrorResponseType;
import org.gluu.oxauth.model.token.JsonWebResponse;
import org.gluu.oxauth.model.util.URLPatternList;
import org.gluu.oxauth.model.util.Util;
import org.gluu.oxauth.service.ClientService;
import org.gluu.oxauth.service.GrantService;
import org.gluu.oxauth.service.RedirectionUriService;
import org.gluu.oxauth.service.SessionIdService;
import org.gluu.oxauth.service.external.ExternalApplicationSessionService;
import org.gluu.oxauth.service.external.ExternalEndSessionService;
import org.gluu.oxauth.service.external.context.EndSessionContext;
import org.gluu.oxauth.util.ServerUtil;
import org.gluu.util.Pair;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author Javier Rojas Blum
* @author Yuriy Movchan
* @author Yuriy Zabrovarnyy
* @version December 8, 2018
*/
@Path("/")
public class EndSessionRestWebServiceImpl implements EndSessionRestWebService {
@Inject
private Logger log;
@Inject
private ErrorResponseFactory errorResponseFactory;
@Inject
private RedirectionUriService redirectionUriService;
@Inject
private AuthorizationGrantList authorizationGrantList;
@Inject
private ExternalApplicationSessionService externalApplicationSessionService;
@Inject
private ExternalEndSessionService externalEndSessionService;
@Inject
private SessionIdService sessionIdService;
@Inject
private ClientService clientService;
@Inject
private GrantService grantService;
@Inject
private Identity identity;
@Inject
private ApplicationAuditLogger applicationAuditLogger;
@Inject
private AppConfiguration appConfiguration;
@Inject
private LogoutTokenFactory logoutTokenFactory;
@Override
public Response requestEndSession(String idTokenHint, String postLogoutRedirectUri, String state, String sessionId,
HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) {
try {
log.debug("Attempting to end session, idTokenHint: {}, postLogoutRedirectUri: {}, sessionId: {}, Is Secure = {}",
idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure());
validateIdTokenHint(idTokenHint, postLogoutRedirectUri);
validateSessionIdRequestParameter(sessionId, postLogoutRedirectUri);
final Pair<SessionId, AuthorizationGrant> pair = getPair(idTokenHint, sessionId, httpRequest);
if (pair.getFirst() == null) {
final String reason = "Failed to identify session by session_id query parameter or by session_id cookie.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
postLogoutRedirectUri = validatePostLogoutRedirectUri(postLogoutRedirectUri, pair);
endSession(pair, httpRequest, httpResponse);
auditLogging(httpRequest, pair);
Set<Client> clients = getSsoClients(pair);
Set<String> frontchannelUris = Sets.newHashSet();
Map<String, Client> backchannelUris = Maps.newHashMap();
for (Client client : clients) {
boolean hasBackchannel = false;
for (String logoutUri : client.getAttributes().getBackchannelLogoutUri()) {
if (Util.isNullOrEmpty(logoutUri)) {
continue; // skip if logout_uri is blank
}
backchannelUris.put(logoutUri, client);
hasBackchannel = true;
}
if (hasBackchannel) { // client has backchannel_logout_uri
continue;
}
for (String logoutUri : client.getFrontChannelLogoutUri()) {
if (Util.isNullOrEmpty(logoutUri)) {
continue; // skip if logout_uri is blank
}
frontchannelUris.add(EndSessionUtils.appendSid(logoutUri, pair.getFirst().getId(), client.getFrontChannelLogoutSessionRequired()));
}
}
backChannel(backchannelUris, pair.getSecond(), pair.getFirst().getId());
if (frontchannelUris.isEmpty()) { // no front-channel
log.trace("No frontchannel_redirect_uri's found in clients involved in SSO.");
if (StringUtils.isBlank(postLogoutRedirectUri)) {
log.trace("postlogout_redirect_uri is missed");
return Response.ok().build();
}
try {
log.trace("Redirect to postlogout_redirect_uri: " + postLogoutRedirectUri);
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
} catch (URISyntaxException e) {
final String message = "Failed to create URI for " + postLogoutRedirectUri + " postlogout_redirect_uri.";
log.error(message);
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(EndSessionErrorResponseType.INVALID_REQUEST, message)).build();
}
}
return httpBased(frontchannelUris, postLogoutRedirectUri, state, pair, httpRequest);
} catch (WebApplicationException e) {
if (e.getResponse() != null) {
return e.getResponse();
}
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorResponseFactory.getJsonErrorResponse(GluuErrorResponseType.SERVER_ERROR))
.build());
}
}
private void backChannel(Map<String, Client> backchannelUris, AuthorizationGrant grant, String sessionId) throws InterruptedException {
if (backchannelUris.isEmpty()) {
return;
}
log.trace("backchannel_redirect_uri's: " + backchannelUris);
final ExecutorService executorService = EndSessionUtils.getExecutorService();
for (final Map.Entry<String, Client> entry : backchannelUris.entrySet()) {
final JsonWebResponse logoutToken = logoutTokenFactory.createLogoutToken(entry.getValue(), grant != null ? grant.getUser() : null, sessionId);
if (logoutToken == null) {
log.error("Failed to create logout_token for client: " + entry.getValue().getClientId());
return;
}
executorService.execute(() -> EndSessionUtils.callRpWithBackchannelUri(entry.getKey(), logoutToken.toString()));
}
executorService.shutdown();
executorService.awaitTermination(30, TimeUnit.SECONDS);
log.trace("Finished backchannel calls.");
}
private Response createErrorResponse(String postLogoutRedirectUri, EndSessionErrorResponseType error, String reason) {
log.debug(reason);
try {
if (allowPostLogoutRedirect(postLogoutRedirectUri)) {
// Commented out to avoid sending an error:
// String separator = postLogoutRedirectUri.contains("?") ? "&" : "?";
// postLogoutRedirectUri = postLogoutRedirectUri + separator + errorResponseFactory.getErrorAsQueryString(error, "", reason);
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
}
} catch (URISyntaxException e) {
log.error("Can't perform redirect", e);
}
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(error, reason)).build();
}
/**
* Allow post logout redirect without validation only if:
* allowPostLogoutRedirectWithoutValidation = true and post_logout_redirect_uri is white listed
*/
private boolean allowPostLogoutRedirect(String postLogoutRedirectUri) {
if (StringUtils.isBlank(postLogoutRedirectUri)) {
return false;
}
final Boolean allowPostLogoutRedirectWithoutValidation = appConfiguration.getAllowPostLogoutRedirectWithoutValidation();
return allowPostLogoutRedirectWithoutValidation != null &&
allowPostLogoutRedirectWithoutValidation &&
new URLPatternList(appConfiguration.getClientWhiteList()).isUrlListed(postLogoutRedirectUri);
}
private void validateSessionIdRequestParameter(String sessionId, String postLogoutRedirectUri) {
// session_id is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(sessionId)) {
SessionId sessionIdObject = sessionIdService.getSessionId(sessionId);
if (sessionIdObject == null) {
final String reason = "session_id parameter in request is not valid. Logout is rejected. session_id parameter in request can be skipped or otherwise valid value must be provided.";
log.error(reason);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
}
}
private void validateIdTokenHint(String idTokenHint, String postLogoutRedirectUri) {
// id_token_hint is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(idTokenHint)) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
if (authorizationGrant == null) {
final String reason = "id_token_hint is not valid. Logout is rejected. id_token_hint can be skipped or otherwise valid value must be provided.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
}
}
}
private String validatePostLogoutRedirectUri(String postLogoutRedirectUri, Pair<SessionId, AuthorizationGrant> pair) {
try {
if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) {
log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true)");
return postLogoutRedirectUri;
}
boolean isNotBlank = StringUtils.isNotBlank(postLogoutRedirectUri);
final String result;
if (pair.getSecond() == null) {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getFirst(), postLogoutRedirectUri);
} else {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);
}
if (isNotBlank && StringUtils.isBlank(result)) {
log.trace("Failed to valistdate post_logout_redirect_uri.");
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
}
if (StringUtils.isNotBlank(result)) {
return result;
}
log.trace("Unable to validate post_logout_redirect_uri.");
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
} catch (WebApplicationException e) {
if (pair.getFirst() != null) { // session_id was found and removed
String reason = "Session was removed successfully but post_logout_redirect_uri validation fails since AS failed to validate it against clients associated with session (which was just removed).";
log.error(reason, e);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, reason));
} else {
throw e;
}
}
}
private Response httpBased(Set<String> frontchannelUris, String postLogoutRedirectUri, String state, Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest) {
try {
final EndSessionContext context = new EndSessionContext(httpRequest, frontchannelUris, postLogoutRedirectUri, pair.getFirst());
final String htmlFromScript = externalEndSessionService.getFrontchannelHtml(context);
if (StringUtils.isNotBlank(htmlFromScript)) {
log.debug("HTML from `getFrontchannelHtml` external script: " + htmlFromScript);
return okResponse(htmlFromScript);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// default handling
final String html = EndSessionUtils.createFronthannelHtml(frontchannelUris, postLogoutRedirectUri, state);
log.debug("Constructed html logout page: " + html);
return okResponse(html);
}
private Response okResponse(String html) {
return Response.ok().
cacheControl(ServerUtil.cacheControl(true, true)).
header("Pragma", "no-cache").
type(MediaType.TEXT_HTML_TYPE).entity(html).
build();
}
private Pair<SessionId, AuthorizationGrant> getPair(String idTokenHint, String sessionId, HttpServletRequest httpRequest) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
}
SessionId ldapSessionId = null;
try {
String id = sessionId;
if (StringHelper.isEmpty(id)) {
id = sessionIdService.getSessionIdFromCookie(httpRequest);
}
if (StringHelper.isNotEmpty(id)) {
ldapSessionId = sessionIdService.getSessionId(id);
}
} catch (Exception e) {
log.error("Failed to current session id.", e);
}
return new Pair<>(ldapSessionId, authorizationGrant);
}
private void endSession(Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
// Clean up authorization session
removeConsentSessionId(httpRequest, httpResponse);
removeSessionId(pair, httpResponse);
boolean isExternalLogoutPresent;
boolean externalLogoutResult = false;
isExternalLogoutPresent = externalApplicationSessionService.isEnabled();
if (isExternalLogoutPresent) {
String userName = pair.getFirst().getSessionAttributes().get(Constants.AUTHENTICATED_USER);
externalLogoutResult = externalApplicationSessionService.executeExternalEndSessionMethods(httpRequest, pair.getFirst());
log.info("End session result for '{}': '{}'", userName, "logout", externalLogoutResult);
}
boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult;
if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) {
throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, EndSessionErrorResponseType.INVALID_GRANT, "External logout is present but executed external logout script returned failed result.");
}
grantService.removeAllTokensBySession(pair.getFirst().getDn());
if (identity != null) {
identity.logout();
}
}
private Set<Client> getSsoClients(Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
if (sessionId == null) {
log.error("session_id is not passed to endpoint (as cookie or manually). Therefore unable to match clients for session_id.");
return Sets.newHashSet();
}
final Set<Client> clients = sessionId.getPermissionGrantedMap() != null ?
clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) :
Sets.newHashSet();
if (authorizationGrant != null) {
clients.add(authorizationGrant.getClient());
}
return clients;
}
private void removeSessionId(Pair<SessionId, AuthorizationGrant> pair, HttpServletResponse httpResponse) {
try {
boolean result = sessionIdService.remove(pair.getFirst());
if (!result) {
log.error("Failed to remove session_id '{}'", pair.getFirst().getId());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
sessionIdService.removeSessionIdCookie(httpResponse);
sessionIdService.removeOPBrowserStateCookie(httpResponse);
}
}
private void removeConsentSessionId(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
try {
String id = sessionIdService.getConsentSessionIdFromCookie(httpRequest);
if (StringHelper.isNotEmpty(id)) {
SessionId ldapSessionId = sessionIdService.getSessionId(id);
if (ldapSessionId != null) {
boolean result = sessionIdService.remove(ldapSessionId);
if (!result) {
log.error("Failed to remove consent_session_id '{}'", id);
}
} else {
log.error("Failed to load session by consent_session_id: '{}'", id);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
sessionIdService.removeConsentSessionIdCookie(httpResponse);
}
}
private void auditLogging(HttpServletRequest request, Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.SESSION_DESTROYED);
oAuth2AuditLog.setSuccess(true);
if (authorizationGrant != null) {
oAuth2AuditLog.setClientId(authorizationGrant.getClientId());
oAuth2AuditLog.setScope(StringUtils.join(authorizationGrant.getScopes(), " "));
oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
} else if (sessionId != null) {
oAuth2AuditLog.setClientId(sessionId.getPermissionGrantedMap().getClientIds(true).toString());
oAuth2AuditLog.setScope(sessionId.getSessionAttributes().get(AuthorizeRequestParam.SCOPE));
oAuth2AuditLog.setUsername(sessionId.getUserDn());
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
} | Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.session.ws.rs;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.gluu.model.security.Identity;
import org.gluu.oxauth.audit.ApplicationAuditLogger;
import org.gluu.oxauth.model.audit.Action;
import org.gluu.oxauth.model.audit.OAuth2AuditLog;
import org.gluu.oxauth.model.authorize.AuthorizeRequestParam;
import org.gluu.oxauth.model.common.AuthorizationGrant;
import org.gluu.oxauth.model.common.AuthorizationGrantList;
import org.gluu.oxauth.model.common.SessionId;
import org.gluu.oxauth.model.config.Constants;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.oxauth.model.error.ErrorResponseFactory;
import org.gluu.oxauth.model.gluu.GluuErrorResponseType;
import org.gluu.oxauth.model.registration.Client;
import org.gluu.oxauth.model.session.EndSessionErrorResponseType;
import org.gluu.oxauth.model.token.JsonWebResponse;
import org.gluu.oxauth.model.util.URLPatternList;
import org.gluu.oxauth.model.util.Util;
import org.gluu.oxauth.service.ClientService;
import org.gluu.oxauth.service.GrantService;
import org.gluu.oxauth.service.RedirectionUriService;
import org.gluu.oxauth.service.SessionIdService;
import org.gluu.oxauth.service.external.ExternalApplicationSessionService;
import org.gluu.oxauth.service.external.ExternalEndSessionService;
import org.gluu.oxauth.service.external.context.EndSessionContext;
import org.gluu.oxauth.util.ServerUtil;
import org.gluu.util.Pair;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author Javier Rojas Blum
* @author Yuriy Movchan
* @author Yuriy Zabrovarnyy
* @version December 8, 2018
*/
@Path("/")
public class EndSessionRestWebServiceImpl implements EndSessionRestWebService {
@Inject
private Logger log;
@Inject
private ErrorResponseFactory errorResponseFactory;
@Inject
private RedirectionUriService redirectionUriService;
@Inject
private AuthorizationGrantList authorizationGrantList;
@Inject
private ExternalApplicationSessionService externalApplicationSessionService;
@Inject
private ExternalEndSessionService externalEndSessionService;
@Inject
private SessionIdService sessionIdService;
@Inject
private ClientService clientService;
@Inject
private GrantService grantService;
@Inject
private Identity identity;
@Inject
private ApplicationAuditLogger applicationAuditLogger;
@Inject
private AppConfiguration appConfiguration;
@Inject
private LogoutTokenFactory logoutTokenFactory;
@Override
public Response requestEndSession(String idTokenHint, String postLogoutRedirectUri, String state, String sessionId,
HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) {
try {
log.debug("Attempting to end session, idTokenHint: {}, postLogoutRedirectUri: {}, sessionId: {}, Is Secure = {}",
idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure());
validateIdTokenHint(idTokenHint, postLogoutRedirectUri);
validateSessionIdRequestParameter(sessionId, postLogoutRedirectUri);
final Pair<SessionId, AuthorizationGrant> pair = getPair(idTokenHint, sessionId, httpRequest);
if (pair.getFirst() == null) {
final String reason = "Failed to identify session by session_id query parameter or by session_id cookie.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
postLogoutRedirectUri = validatePostLogoutRedirectUri(postLogoutRedirectUri, pair);
endSession(pair, httpRequest, httpResponse);
auditLogging(httpRequest, pair);
Set<Client> clients = getSsoClients(pair);
Set<String> frontchannelUris = Sets.newHashSet();
Map<String, Client> backchannelUris = Maps.newHashMap();
for (Client client : clients) {
boolean hasBackchannel = false;
for (String logoutUri : client.getAttributes().getBackchannelLogoutUri()) {
if (Util.isNullOrEmpty(logoutUri)) {
continue; // skip if logout_uri is blank
}
backchannelUris.put(logoutUri, client);
hasBackchannel = true;
}
if (hasBackchannel) { // client has backchannel_logout_uri
continue;
}
for (String logoutUri : client.getFrontChannelLogoutUri()) {
if (Util.isNullOrEmpty(logoutUri)) {
continue; // skip if logout_uri is blank
}
frontchannelUris.add(EndSessionUtils.appendSid(logoutUri, pair.getFirst().getId(), client.getFrontChannelLogoutSessionRequired()));
}
}
backChannel(backchannelUris, pair.getSecond(), pair.getFirst().getId());
if (frontchannelUris.isEmpty()) { // no front-channel
log.trace("No frontchannel_redirect_uri's found in clients involved in SSO.");
if (StringUtils.isBlank(postLogoutRedirectUri)) {
log.trace("postlogout_redirect_uri is missed");
return Response.ok().build();
}
try {
log.trace("Redirect to postlogout_redirect_uri: " + postLogoutRedirectUri);
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
} catch (URISyntaxException e) {
final String message = "Failed to create URI for " + postLogoutRedirectUri + " postlogout_redirect_uri.";
log.error(message);
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(EndSessionErrorResponseType.INVALID_REQUEST, message)).build();
}
}
return httpBased(frontchannelUris, postLogoutRedirectUri, state, pair, httpRequest);
} catch (WebApplicationException e) {
if (e.getResponse() != null) {
return e.getResponse();
}
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorResponseFactory.getJsonErrorResponse(GluuErrorResponseType.SERVER_ERROR))
.build());
}
}
private void backChannel(Map<String, Client> backchannelUris, AuthorizationGrant grant, String sessionId) throws InterruptedException {
if (backchannelUris.isEmpty()) {
return;
}
log.trace("backchannel_redirect_uri's: " + backchannelUris);
final ExecutorService executorService = EndSessionUtils.getExecutorService();
for (final Map.Entry<String, Client> entry : backchannelUris.entrySet()) {
final JsonWebResponse logoutToken = logoutTokenFactory.createLogoutToken(entry.getValue(), grant != null ? grant.getUser() : null, sessionId);
if (logoutToken == null) {
log.error("Failed to create logout_token for client: " + entry.getValue().getClientId());
return;
}
executorService.execute(() -> EndSessionUtils.callRpWithBackchannelUri(entry.getKey(), logoutToken.toString()));
}
executorService.shutdown();
executorService.awaitTermination(30, TimeUnit.SECONDS);
log.trace("Finished backchannel calls.");
}
private Response createErrorResponse(String postLogoutRedirectUri, EndSessionErrorResponseType error, String reason) {
log.debug(reason);
try {
if (allowPostLogoutRedirect(postLogoutRedirectUri)) {
// Commented out to avoid sending an error:
// String separator = postLogoutRedirectUri.contains("?") ? "&" : "?";
// postLogoutRedirectUri = postLogoutRedirectUri + separator + errorResponseFactory.getErrorAsQueryString(error, "", reason);
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
}
} catch (URISyntaxException e) {
log.error("Can't perform redirect", e);
}
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(error, reason)).build();
}
/**
* Allow post logout redirect without validation only if:
* allowPostLogoutRedirectWithoutValidation = true and post_logout_redirect_uri is white listed
*/
private boolean allowPostLogoutRedirect(String postLogoutRedirectUri) {
if (StringUtils.isBlank(postLogoutRedirectUri)) {
return false;
}
final Boolean allowPostLogoutRedirectWithoutValidation = appConfiguration.getAllowPostLogoutRedirectWithoutValidation();
return allowPostLogoutRedirectWithoutValidation != null &&
allowPostLogoutRedirectWithoutValidation &&
new URLPatternList(appConfiguration.getClientWhiteList()).isUrlListed(postLogoutRedirectUri);
}
private void validateSessionIdRequestParameter(String sessionId, String postLogoutRedirectUri) {
// session_id is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(sessionId)) {
SessionId sessionIdObject = sessionIdService.getSessionId(sessionId);
if (sessionIdObject == null) {
final String reason = "session_id parameter in request is not valid. Logout is rejected. session_id parameter in request can be skipped or otherwise valid value must be provided.";
log.error(reason);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
}
}
private void validateIdTokenHint(String idTokenHint, String postLogoutRedirectUri) {
// id_token_hint is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(idTokenHint)) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
if (authorizationGrant == null) {
final String reason = "id_token_hint is not valid. Logout is rejected. id_token_hint can be skipped or otherwise valid value must be provided.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
}
}
}
private String validatePostLogoutRedirectUri(String postLogoutRedirectUri, Pair<SessionId, AuthorizationGrant> pair) {
try {
if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) {
return postLogoutRedirectUri;
}
boolean isNotBlank = StringUtils.isNotBlank(postLogoutRedirectUri);
final String result;
if (pair.getSecond() == null) {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getFirst(), postLogoutRedirectUri);
} else {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);
}
if (isNotBlank && StringUtils.isBlank(result)) { // failed to validate
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
}
if (StringUtils.isNotBlank(result)) {
return result;
}
log.trace("Unable to validate post_logout_redirect_uri.");
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
} catch (WebApplicationException e) {
if (pair.getFirst() != null) { // session_id was found and removed
String reason = "Session was removed successfully but post_logout_redirect_uri validation fails since AS failed to validate it against clients associated with session (which was just removed).";
log.error(reason, e);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, reason));
} else {
throw e;
}
}
}
private Response httpBased(Set<String> frontchannelUris, String postLogoutRedirectUri, String state, Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest) {
try {
final EndSessionContext context = new EndSessionContext(httpRequest, frontchannelUris, postLogoutRedirectUri, pair.getFirst());
final String htmlFromScript = externalEndSessionService.getFrontchannelHtml(context);
if (StringUtils.isNotBlank(htmlFromScript)) {
log.debug("HTML from `getFrontchannelHtml` external script: " + htmlFromScript);
return okResponse(htmlFromScript);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// default handling
final String html = EndSessionUtils.createFronthannelHtml(frontchannelUris, postLogoutRedirectUri, state);
log.debug("Constructed html logout page: " + html);
return okResponse(html);
}
private Response okResponse(String html) {
return Response.ok().
cacheControl(ServerUtil.cacheControl(true, true)).
header("Pragma", "no-cache").
type(MediaType.TEXT_HTML_TYPE).entity(html).
build();
}
private Pair<SessionId, AuthorizationGrant> getPair(String idTokenHint, String sessionId, HttpServletRequest httpRequest) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
}
SessionId ldapSessionId = null;
try {
String id = sessionId;
if (StringHelper.isEmpty(id)) {
id = sessionIdService.getSessionIdFromCookie(httpRequest);
}
if (StringHelper.isNotEmpty(id)) {
ldapSessionId = sessionIdService.getSessionId(id);
}
} catch (Exception e) {
log.error("Failed to current session id.", e);
}
return new Pair<>(ldapSessionId, authorizationGrant);
}
private void endSession(Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
// Clean up authorization session
removeConsentSessionId(httpRequest, httpResponse);
removeSessionId(pair, httpResponse);
boolean isExternalLogoutPresent;
boolean externalLogoutResult = false;
isExternalLogoutPresent = externalApplicationSessionService.isEnabled();
if (isExternalLogoutPresent) {
String userName = pair.getFirst().getSessionAttributes().get(Constants.AUTHENTICATED_USER);
externalLogoutResult = externalApplicationSessionService.executeExternalEndSessionMethods(httpRequest, pair.getFirst());
log.info("End session result for '{}': '{}'", userName, "logout", externalLogoutResult);
}
boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult;
if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) {
throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, EndSessionErrorResponseType.INVALID_GRANT, "External logout is present but executed external logout script returned failed result.");
}
grantService.removeAllTokensBySession(pair.getFirst().getDn());
if (identity != null) {
identity.logout();
}
}
private Set<Client> getSsoClients(Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
if (sessionId == null) {
log.error("session_id is not passed to endpoint (as cookie or manually). Therefore unable to match clients for session_id.");
return Sets.newHashSet();
}
final Set<Client> clients = sessionId.getPermissionGrantedMap() != null ?
clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) :
Sets.newHashSet();
if (authorizationGrant != null) {
clients.add(authorizationGrant.getClient());
}
return clients;
}
private void removeSessionId(Pair<SessionId, AuthorizationGrant> pair, HttpServletResponse httpResponse) {
try {
boolean result = sessionIdService.remove(pair.getFirst());
if (!result) {
log.error("Failed to remove session_id '{}'", pair.getFirst().getId());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
sessionIdService.removeSessionIdCookie(httpResponse);
sessionIdService.removeOPBrowserStateCookie(httpResponse);
}
}
private void removeConsentSessionId(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
try {
String id = sessionIdService.getConsentSessionIdFromCookie(httpRequest);
if (StringHelper.isNotEmpty(id)) {
SessionId ldapSessionId = sessionIdService.getSessionId(id);
if (ldapSessionId != null) {
boolean result = sessionIdService.remove(ldapSessionId);
if (!result) {
log.error("Failed to remove consent_session_id '{}'", id);
}
} else {
log.error("Failed to load session by consent_session_id: '{}'", id);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
sessionIdService.removeConsentSessionIdCookie(httpResponse);
}
}
private void auditLogging(HttpServletRequest request, Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.SESSION_DESTROYED);
oAuth2AuditLog.setSuccess(true);
if (authorizationGrant != null) {
oAuth2AuditLog.setClientId(authorizationGrant.getClientId());
oAuth2AuditLog.setScope(StringUtils.join(authorizationGrant.getScopes(), " "));
oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
} else if (sessionId != null) {
oAuth2AuditLog.setClientId(sessionId.getPermissionGrantedMap().getClientIds(true).toString());
oAuth2AuditLog.setScope(sessionId.getSessionAttributes().get(AuthorizeRequestParam.SCOPE));
oAuth2AuditLog.setUsername(sessionId.getUserDn());
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
} | add more log messages for post_logout_redirect_uri validation
https://github.com/GluuFederation/oxAuth/issues/1274
| Server/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java | add more log messages for post_logout_redirect_uri validation | <ide><path>erver/src/main/java/org/gluu/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java
<ide> private String validatePostLogoutRedirectUri(String postLogoutRedirectUri, Pair<SessionId, AuthorizationGrant> pair) {
<ide> try {
<ide> if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) {
<add> log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true)");
<ide> return postLogoutRedirectUri;
<ide> }
<ide>
<ide> result = redirectionUriService.validatePostLogoutRedirectUri(pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);
<ide> }
<ide>
<del> if (isNotBlank && StringUtils.isBlank(result)) { // failed to validate
<add> if (isNotBlank && StringUtils.isBlank(result)) {
<add> log.trace("Failed to valistdate post_logout_redirect_uri.");
<ide> throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
<ide> }
<ide> |
|
Java | apache-2.0 | 87591655ad6114e17b549bfdcf61667dc29c95bc | 0 | igniterealtime/Smack,Flowdalic/Smack,vanitasvitae/Smack,igniterealtime/Smack,Flowdalic/Smack,Flowdalic/Smack,vanitasvitae/Smack,igniterealtime/Smack,vanitasvitae/Smack | /**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.filter;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.Predicate;
/**
* Defines a way to filter stanzas for particular attributes. Stanza filters are used when
* constructing stanza listeners or collectors -- the filter defines what stanzas match the criteria
* of the collector or listener for further stanza processing.
* <p>
* Several simple filters are pre-defined. These filters can be logically combined for more complex
* stanza filtering by using the {@link org.jivesoftware.smack.filter.AndFilter AndFilter} and
* {@link org.jivesoftware.smack.filter.OrFilter OrFilter} filters. It's also possible to define
* your own filters by implementing this interface. The code example below creates a trivial filter
* for stanzas with a specific ID (real code should use {@link StanzaIdFilter} instead).
*
* <pre>
* // Use an anonymous inner class to define a stanza filter that returns
* // all stanzas that have a stanza ID of "RS145".
* StanzaFilter myFilter = new StanzaFilter() {
* public boolean accept(Stanza stanza) {
* return "RS145".equals(stanza.getStanzaId());
* }
* };
* // Create a new stanza collector using the filter we created.
* StanzaCollector myCollector = connection.createStanzaCollector(myFilter);
* </pre>
* <p>
* As a rule of thumb: If you have a predicate method, that is, a method which takes a single Stanza as argument, is pure
* (side effect free) and returns only a boolean, then it is a good indicator that the logic should be put into a
* {@link StanzaFilter} (and be referenced in {@link org.jivesoftware.smack.StanzaListener}).
* </p>
*
* @see org.jivesoftware.smack.StanzaCollector
* @see org.jivesoftware.smack.StanzaListener
* @author Matt Tucker
*/
public interface StanzaFilter extends Predicate<Stanza> {
/**
* Tests whether or not the specified stanza should pass the filter.
*
* @param stanza the stanza to test.
* @return true if and only if <code>stanza</code> passes the filter.
*/
boolean accept(Stanza stanza);
@Override
default boolean test(Stanza stanza) {
return accept(stanza);
}
default <S extends Stanza> Predicate<S> asPredicate(Class<?> stanzaClass) {
return s -> {
if (!stanzaClass.isAssignableFrom(s.getClass())) {
return false;
}
return accept(s);
};
}
}
| smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaFilter.java | /**
*
* Copyright 2003-2007 Jive Software.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.filter;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.Predicate;
/**
* Defines a way to filter stanzas for particular attributes. Stanza filters are used when
* constructing stanza listeners or collectors -- the filter defines what stanzas match the criteria
* of the collector or listener for further stanza processing.
* <p>
* Several simple filters are pre-defined. These filters can be logically combined for more complex
* stanza filtering by using the {@link org.jivesoftware.smack.filter.AndFilter AndFilter} and
* {@link org.jivesoftware.smack.filter.OrFilter OrFilter} filters. It's also possible to define
* your own filters by implementing this interface. The code example below creates a trivial filter
* for stanzas with a specific ID (real code should use {@link StanzaIdFilter} instead).
*
* <pre>
* // Use an anonymous inner class to define a stanza filter that returns
* // all stanzas that have a stanza ID of "RS145".
* StanzaFilter myFilter = new StanzaFilter() {
* public boolean accept(Stanza stanza) {
* return "RS145".equals(stanza.getStanzaId());
* }
* };
* // Create a new stanza collector using the filter we created.
* StanzaCollector myCollector = connection.createStanzaCollector(myFilter);
* </pre>
* <p>
* As a rule of thumb: If you have a predicate method, that is, a method which takes a single Stanza as argument, is pure
* (side effect free) and returns only a boolean, then it is a good indicator that the logic should be put into a
* {@link StanzaFilter} (and be referenced in {@link org.jivesoftware.smack.StanzaListener}).
* </p>
*
* @see org.jivesoftware.smack.StanzaCollector
* @see org.jivesoftware.smack.StanzaListener
* @author Matt Tucker
*/
public interface StanzaFilter extends Predicate<Stanza> {
/**
* Tests whether or not the specified stanza should pass the filter.
*
* @param stanza the stanza to test.
* @return true if and only if <code>stanza</code> passes the filter.
*/
boolean accept(Stanza stanza);
@Override
default boolean test(Stanza stanza) {
return accept(stanza);
}
}
| [core] Add StanzaFilter.asPredicate(Class)
| smack-core/src/main/java/org/jivesoftware/smack/filter/StanzaFilter.java | [core] Add StanzaFilter.asPredicate(Class) | <ide><path>mack-core/src/main/java/org/jivesoftware/smack/filter/StanzaFilter.java
<ide> default boolean test(Stanza stanza) {
<ide> return accept(stanza);
<ide> }
<add>
<add> default <S extends Stanza> Predicate<S> asPredicate(Class<?> stanzaClass) {
<add> return s -> {
<add> if (!stanzaClass.isAssignableFrom(s.getClass())) {
<add> return false;
<add> }
<add> return accept(s);
<add> };
<add> }
<ide> } |
|
Java | apache-2.0 | c10748e49b915bf8b4cfa359c3ef14270302e8e3 | 0 | apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.seaborne.dboe.base.file ;
import java.io.File ;
import java.io.IOException ;
import java.util.Objects ;
import org.seaborne.dboe.sys.Names ;
/**
* Wrapper for a file system directory; can create filenames in that directory.
* Enforces some simple consistency policies and provides a "typed string" for a
* filename to reduce errors.
*/
public class Location {
static String pathSeparator = File.separator ; // Or just "/"
private static String memNamePath = Names.memName+pathSeparator ;
private String pathname ;
private MetaFile metafile = null ;
private boolean isMem = false ;
private boolean isMemUnique = false ;
private LocationLock lock ;
static int memoryCount = 0 ;
/**
* Return a fresh memory location : always unique, never .equals to another
* location.
*/
static public Location mem() {
return mem(null) ;
}
/** Return a memory location with a name */
static public Location mem(String name) {
Location loc = new Location() ;
memInit(loc, name) ;
return loc ;
}
/** Return a location for a directory on disk */
static public Location create(String directoryName) {
if ( directoryName == null )
// Fresh, anonymous, memory area
return mem() ;
Location loc = new Location(directoryName) ;
return loc ;
}
private Location() {}
private static void memInit(Location location, String name) {
location.pathname = Names.memName ;
if ( name != null ) {
name = name.replace('\\', '/') ;
location.pathname = location.pathname + '/' + name ;
} else
location.isMemUnique = true ;
if ( !location.pathname.endsWith(pathSeparator) )
location.pathname = location.pathname + '/' ;
location.isMem = true ;
location.metafile = new MetaFile(Names.memName, Names.memName) ;
location.lock = new LocationLock(location);
}
private Location(String rootname) {
super() ;
if ( rootname.equals(Names.memName) ) {
memInit(this, null) ;
return ;
}
if ( rootname.startsWith(memNamePath) ) {
String name = rootname.substring(memNamePath.length()) ;
memInit(this, name) ;
return ;
}
ensure(rootname) ;
pathname = fixupName(rootname) ;
// Metafilename for a directory.
String metafileName = getPath(Names.directoryMetafile, Names.extMeta) ;
metafile = new MetaFile("Location: " + rootname, metafileName) ;
// Set up locking
// Note that we don't check the lock in any way at this point, checking
// and obtaining the lock is carried out by StoreConnection
lock = new LocationLock(this);
}
// MS Windows:
// getCanonicalPath is only good enough for existing files.
// It leaves the case as it finds it (upper, lower) and lower cases
// not-existing segments. But later creation of a segment with uppercase
// changes the exact string returned.
private String fixupName(String fsName) {
if ( isMem() )
return fsName ;
File file = new File(fsName) ;
try {
fsName = file.getCanonicalPath() ;
} catch (IOException ex) {
throw new FileException("Failed to get canoncial path: " + file.getAbsolutePath(), ex) ;
}
if ( !fsName.endsWith(File.separator) && !fsName.endsWith(pathSeparator) )
fsName = fsName + pathSeparator ;
return fsName ;
}
public String getDirectoryPath() {
return pathname ;
}
public MetaFile getMetaFile() {
return metafile ;
}
public boolean isMem() {
return isMem ;
}
public boolean isMemUnique() {
return isMemUnique ;
}
public LocationLock getLock() {
return lock;
}
public Location getSubLocation(String dirname) {
String newName = pathname + dirname ;
ensure(newName) ;
return Location.create(newName) ;
}
private void ensure(String dirname) {
if ( isMem() )
return ;
File file = new File(dirname) ;
if ( file.exists() && !file.isDirectory() )
throw new FileException("Existing file: " + file.getAbsolutePath()) ;
if ( !file.exists() )
file.mkdir() ;
}
public String getSubDirectory(String dirname) {
return getSubLocation(dirname).getDirectoryPath() ;
}
/**
* Return an absolute filename where relative names are resolved from the
* location
*/
public String absolute(String filename, String extension) {
return (extension == null) ? absolute(filename) : absolute(filename + "." + extension) ;
}
/**
* Return an absolute filename where relative names are resolved from the
* location
*/
public String absolute(String filename) {
File f = new File(filename) ;
// Location relative.
if ( !f.isAbsolute() )
filename = pathname + filename ;
return filename ;
}
/** Does the location exist (and it a directory, and is accessible) */
public boolean exists() {
File f = new File(getDirectoryPath()) ;
return f.exists() && f.isDirectory() && f.canRead() ;
}
public boolean exists(String filename) {
return exists(filename, null) ;
}
public boolean exists(String filename, String ext) {
String fn = getPath(filename, ext) ;
File f = new File(fn) ;
return f.exists() ;
}
/** Return the name of the file relative to this location */
public String getPath(String filename) {
return getPath(filename, null) ;
}
/** Return the name of the file, and extension, relative to this location */
public String getPath(String filename, String ext) {
check(filename, ext) ;
if ( ext == null )
return pathname + filename ;
return pathname + filename + "." + ext ;
}
private void check(String filename, String ext) {
if ( filename == null )
throw new FileException("Location: null filename") ;
if ( filename.contains("/") || filename.contains("\\") )
throw new FileException("Illegal file component name: " + filename) ;
if ( filename.contains(".") && ext != null )
throw new FileException("Filename has an extension: " + filename) ;
if ( ext != null ) {
if ( ext.contains(".") )
throw new FileException("Extension has an extension: " + filename) ;
}
}
@Override
public int hashCode() {
final int prime = 31 ;
int result = isMem ? 1 : 2 ;
result = prime * result + ((pathname == null) ? 0 : pathname.hashCode()) ;
return result ;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true ;
if ( obj == null )
return false ;
if ( getClass() != obj.getClass() )
return false ;
Location other = (Location)obj ;
if ( isMem && !other.isMem )
return false ;
if ( !isMem && other.isMem )
return false ;
// Not == so ...
if ( isMemUnique )
return false ;
return Objects.equals(pathname, other.pathname) ;
}
@Override
public String toString() {
return "location:" + pathname ;
}
}
| dboe-base/src/main/java/org/seaborne/dboe/base/file/Location.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.seaborne.dboe.base.file ;
import java.io.File ;
import java.io.IOException ;
import java.util.Objects ;
import org.seaborne.dboe.sys.Names ;
/**
* Wrapper for a file system directory; can create filenames in that directory.
* Enforces some simple consistency policies and provides a "typed string" for a
* filename to reduce errors.
*/
public class Location {
static String pathSeparator = File.separator ; // Or just "/"
private static String memNamePath = Names.memName+pathSeparator ;
private String pathname ;
private MetaFile metafile = null ;
private boolean isMem = false ;
private boolean isMemUnique = false ;
private LocationLock lock ;
static int memoryCount = 0 ;
/**
* Return a fresh memory location : always unique, never .equals to another
* location.
*/
static public Location mem() {
return mem(null) ;
}
/** Return a memory location with a name */
static public Location mem(String name) {
Location loc = new Location() ;
memInit(loc, name) ;
return loc ;
}
/** Return a location for a directory on disk */
static public Location create(String directoryName) {
if ( directoryName == null )
// Fresh, anonymous, memory area
return mem() ;
Location loc = new Location(directoryName) ;
return loc ;
}
private Location() {}
private static void memInit(Location location, String name) {
location.pathname = Names.memName ;
if ( name != null ) {
name = name.replace('\\', '/') ;
location.pathname = location.pathname + '/' + name ;
} else
location.isMemUnique = true ;
if ( !location.pathname.endsWith(pathSeparator) )
location.pathname = location.pathname + '/' ;
location.isMem = true ;
location.metafile = new MetaFile(Names.memName, Names.memName) ;
location.lock = new LocationLock(location);
}
/** @deprecated Use{@link Location#create(String)} */
@Deprecated
public Location(String rootname) {
super() ;
if ( rootname.equals(Names.memName) ) {
memInit(this, null) ;
return ;
}
if ( rootname.startsWith(memNamePath) ) {
String name = rootname.substring(memNamePath.length()) ;
memInit(this, name) ;
return ;
}
ensure(rootname) ;
pathname = fixupName(rootname) ;
// Metafilename for a directory.
String metafileName = getPath(Names.directoryMetafile, Names.extMeta) ;
metafile = new MetaFile("Location: " + rootname, metafileName) ;
// Set up locking
// Note that we don't check the lock in any way at this point, checking
// and obtaining the lock is carried out by StoreConnection
lock = new LocationLock(this);
}
// MS Windows:
// getCanonicalPath is only good enough for existing files.
// It leaves the case as it finds it (upper, lower) and lower cases
// not-existing segments. But later creation of a segment with uppercase
// changes the exact string returned.
private String fixupName(String fsName) {
if ( isMem() )
return fsName ;
File file = new File(fsName) ;
try {
fsName = file.getCanonicalPath() ;
} catch (IOException ex) {
throw new FileException("Failed to get canoncial path: " + file.getAbsolutePath(), ex) ;
}
if ( !fsName.endsWith(File.separator) && !fsName.endsWith(pathSeparator) )
fsName = fsName + pathSeparator ;
return fsName ;
}
public String getDirectoryPath() {
return pathname ;
}
public MetaFile getMetaFile() {
return metafile ;
}
public boolean isMem() {
return isMem ;
}
public boolean isMemUnique() {
return isMemUnique ;
}
public LocationLock getLock() {
return lock;
}
public Location getSubLocation(String dirname) {
String newName = pathname + dirname ;
ensure(newName) ;
return Location.create(newName) ;
}
private void ensure(String dirname) {
if ( isMem() )
return ;
File file = new File(dirname) ;
if ( file.exists() && !file.isDirectory() )
throw new FileException("Existing file: " + file.getAbsolutePath()) ;
if ( !file.exists() )
file.mkdir() ;
}
public String getSubDirectory(String dirname) {
return getSubLocation(dirname).getDirectoryPath() ;
}
/**
* Return an absolute filename where relative names are resolved from the
* location
*/
public String absolute(String filename, String extension) {
return (extension == null) ? absolute(filename) : absolute(filename + "." + extension) ;
}
/**
* Return an absolute filename where relative names are resolved from the
* location
*/
public String absolute(String filename) {
File f = new File(filename) ;
// Location relative.
if ( !f.isAbsolute() )
filename = pathname + filename ;
return filename ;
}
/** Does the location exist (and it a directory, and is accessible) */
public boolean exists() {
File f = new File(getDirectoryPath()) ;
return f.exists() && f.isDirectory() && f.canRead() ;
}
public boolean exists(String filename) {
return exists(filename, null) ;
}
public boolean exists(String filename, String ext) {
String fn = getPath(filename, ext) ;
File f = new File(fn) ;
return f.exists() ;
}
/** Return the name of the file relative to this location */
public String getPath(String filename) {
return getPath(filename, null) ;
}
/** Return the name of the file, and extension, relative to this location */
public String getPath(String filename, String ext) {
check(filename, ext) ;
if ( ext == null )
return pathname + filename ;
return pathname + filename + "." + ext ;
}
private void check(String filename, String ext) {
if ( filename == null )
throw new FileException("Location: null filename") ;
if ( filename.contains("/") || filename.contains("\\") )
throw new FileException("Illegal file component name: " + filename) ;
if ( filename.contains(".") && ext != null )
throw new FileException("Filename has an extension: " + filename) ;
if ( ext != null ) {
if ( ext.contains(".") )
throw new FileException("Extension has an extension: " + filename) ;
}
}
@Override
public int hashCode() {
final int prime = 31 ;
int result = isMem ? 1 : 2 ;
result = prime * result + ((pathname == null) ? 0 : pathname.hashCode()) ;
return result ;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true ;
if ( obj == null )
return false ;
if ( getClass() != obj.getClass() )
return false ;
Location other = (Location)obj ;
if ( isMem && !other.isMem )
return false ;
if ( !isMem && other.isMem )
return false ;
// Not == so ...
if ( isMemUnique )
return false ;
return Objects.equals(pathname, other.pathname) ;
}
@Override
public String toString() {
return "location:" + pathname ;
}
}
| Constructor -> private | dboe-base/src/main/java/org/seaborne/dboe/base/file/Location.java | Constructor -> private | <ide><path>boe-base/src/main/java/org/seaborne/dboe/base/file/Location.java
<ide> location.lock = new LocationLock(location);
<ide> }
<ide>
<del> /** @deprecated Use{@link Location#create(String)} */
<del> @Deprecated
<del> public Location(String rootname) {
<add> private Location(String rootname) {
<ide> super() ;
<ide> if ( rootname.equals(Names.memName) ) {
<ide> memInit(this, null) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.