answer stringlengths 17 10.2M |
|---|
package com.github.dreamhead.moco.verification;
public abstract class UnaryTimesVerification extends AbstractTimesVerification {
protected abstract boolean doMeet(int size, int count);
private final int count;
protected UnaryTimesVerification(final int count) {
this.count = count;
}
@Override
protected String expectedTip() {
return Integer.toString(count);
}
@Override
protected boolean meet(final int size) {
return doMeet(size, count);
}
} |
package org.navalplanner.web.resourceload;
import static org.navalplanner.web.I18nHelper._;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.lang.Validate;
import org.joda.time.LocalDate;
import org.navalplanner.business.planner.daos.IResourceAllocationDAO;
import org.navalplanner.business.planner.entities.GenericResourceAllocation;
import org.navalplanner.business.planner.entities.ResourceAllocation;
import org.navalplanner.business.planner.entities.SpecificResourceAllocation;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.resources.daos.IResourceDAO;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.resources.entities.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.zkoss.ganttz.data.resourceload.LoadLevel;
import org.zkoss.ganttz.data.resourceload.LoadPeriod;
import org.zkoss.ganttz.data.resourceload.LoadTimeLine;
import org.zkoss.ganttz.data.resourceload.LoadTimelinesGroup;
import org.zkoss.ganttz.util.Interval;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ResourceLoadModel implements IResourceLoadModel {
@Autowired
private IResourceDAO resourcesDAO;
@Autowired
private IResourceAllocationDAO resourceAllocationDAO;
private List<LoadTimelinesGroup> loadTimeLines;
private Interval viewInterval;
@Override
@Transactional(readOnly = true)
public void initGlobalView() {
List<Resource> allResources = resourcesDAO.list(Resource.class);
loadTimeLines = groupsFor(allResources);
viewInterval = new Interval(toDate(new LocalDate(2008, 6, 10)),
toDate(new LocalDate(2011, 6, 10)));
}
private List<LoadTimelinesGroup> groupsFor(List<Resource> allResources) {
List<LoadTimelinesGroup> result = new ArrayList<LoadTimelinesGroup>();
for (Resource resource : allResources) {
result.add(buildGroup(resource));
}
return result;
}
private LoadTimelinesGroup buildGroup(Resource resource) {
List<ResourceAllocation<?>> sortedByStartDate = ResourceAllocation
.sortedByStartDate(resourceAllocationDAO
.findAllocationsRelatedTo(resource));
return new LoadTimelinesGroup(buildTimeLine(resource, resource
.getDescription(), sortedByStartDate), buildSecondLevel(
resource, sortedByStartDate));
}
private List<LoadTimeLine> buildSecondLevel(Resource resource,
List<ResourceAllocation<?>> sortedByStartDate) {
List<LoadTimeLine> result = new ArrayList<LoadTimeLine>();
result.addAll(buildTimeLinesForEachTask(resource,
onlySpecific(sortedByStartDate)));
result.addAll(buildTimeLinesForEachCriterion(resource,
onlyGeneric(sortedByStartDate)));
return result;
}
private List<GenericResourceAllocation> onlyGeneric(
List<ResourceAllocation<?>> sortedByStartDate) {
List<GenericResourceAllocation> result = new ArrayList<GenericResourceAllocation>();
for (ResourceAllocation<?> r : sortedByStartDate) {
if (r instanceof GenericResourceAllocation) {
result.add((GenericResourceAllocation) r);
}
}
return result;
}
private List<SpecificResourceAllocation> onlySpecific(
List<ResourceAllocation<?>> sortedByStartDate) {
List<SpecificResourceAllocation> result = new ArrayList<SpecificResourceAllocation>();
for (ResourceAllocation<?> r : sortedByStartDate) {
if (r instanceof SpecificResourceAllocation) {
result.add((SpecificResourceAllocation) r);
}
}
return result;
}
private List<LoadTimeLine> buildTimeLinesForEachCriterion(
Resource resource, List<GenericResourceAllocation> sortdByStartDate) {
Map<Set<Criterion>, List<GenericResourceAllocation>> byCriterions = GenericResourceAllocation
.byCriterions(sortdByStartDate);
List<LoadTimeLine> result = new ArrayList<LoadTimeLine>();
for (Entry<Set<Criterion>, List<GenericResourceAllocation>> entry : byCriterions
.entrySet()) {
result.add(buildTimeLine(new ArrayList<Criterion>(entry.getKey()),
resource, entry.getValue()));
}
return result;
}
private List<LoadTimeLine> buildTimeLinesForEachTask(Resource resource,
List<SpecificResourceAllocation> sortedByStartDate) {
Map<Task, List<ResourceAllocation<?>>> byTask = ResourceAllocation
.byTask(sortedByStartDate);
List<LoadTimeLine> secondLevel = new ArrayList<LoadTimeLine>();
for (Entry<Task, List<ResourceAllocation<?>>> entry : byTask.entrySet()) {
secondLevel.add(buildTimeLine(resource, entry.getKey().getName(),
entry.getValue()));
}
return secondLevel;
}
private LoadTimeLine buildTimeLine(List<Criterion> criterions,
Resource resource,
List<GenericResourceAllocation> allocationsSortedByStartDate) {
return new LoadTimeLine(getName(criterions), PeriodsBuilder.build(
new OnResourceFactory(resource), allocationsSortedByStartDate));
}
private String getName(List<Criterion> criterions) {
if (criterions.isEmpty()) {
return _("generic all workers");
}
String[] names = new String[criterions.size()];
for (int i = 0; i < names.length; i++) {
names[i] = criterions.get(i).getName();
}
return Arrays.toString(names);
}
private LoadTimeLine buildTimeLine(Resource resource, String name,
List<ResourceAllocation<?>> sortedByStartDate) {
return new LoadTimeLine(name, PeriodsBuilder.build(
new OnResourceFactory(resource), sortedByStartDate));
}
@Override
public List<LoadTimelinesGroup> getLoadTimeLines() {
return loadTimeLines;
}
@Override
public Interval getViewInterval() {
return viewInterval;
}
private Date toDate(LocalDate localDate) {
return localDate.toDateTimeAtStartOfDay().toDate();
}
}
interface LoadPeriodGeneratorFactory {
LoadPeriodGenerator create(ResourceAllocation<?> allocation);
}
class OnResourceFactory implements LoadPeriodGeneratorFactory {
private final Resource resource;
public OnResourceFactory(Resource resource) {
Validate.notNull(resource);
this.resource = resource;
}
@Override
public LoadPeriodGenerator create(ResourceAllocation<?> allocation) {
return new LoadPeriodGenerator(resource, allocation);
}
}
class PeriodsBuilder {
private final List<? extends ResourceAllocation<?>> sortedByStartDate;
private final List<LoadPeriodGenerator> loadPeriodsGenerators = new LinkedList<LoadPeriodGenerator>();
private final LoadPeriodGeneratorFactory factory;
private PeriodsBuilder(LoadPeriodGeneratorFactory factory,
List<? extends ResourceAllocation<?>> sortedByStartDate) {
this.factory = factory;
this.sortedByStartDate = sortedByStartDate;
}
public static List<LoadPeriod> build(LoadPeriodGeneratorFactory factory,
List<? extends ResourceAllocation<?>> sortedByStartDate) {
return new PeriodsBuilder(factory, sortedByStartDate).buildPeriods();
}
private List<LoadPeriod> buildPeriods() {
for (ResourceAllocation<?> resourceAllocation : sortedByStartDate) {
loadPeriodsGenerators.add(factory.create(resourceAllocation));
}
joinPeriodGenerators();
return toGenerators(loadPeriodsGenerators);
}
private List<LoadPeriod> toGenerators(List<LoadPeriodGenerator> generators) {
List<LoadPeriod> result = new ArrayList<LoadPeriod>();
for (LoadPeriodGenerator loadPeriodGenerator : generators) {
result.add(loadPeriodGenerator.build());
}
return result;
}
private void joinPeriodGenerators() {
ListIterator<LoadPeriodGenerator> iterator = loadPeriodsGenerators
.listIterator();
while (iterator.hasNext()) {
LoadPeriodGenerator current = iterator.next();
if (iterator.hasNext()) {
iterator.remove();
LoadPeriodGenerator next = iterator.next();
iterator.remove();
List<LoadPeriodGenerator> generated = current.join(next);
final LoadPeriodGenerator nextOne = generated.size() > 1 ? generated
.get(1)
: generated.get(0);
List<LoadPeriodGenerator> sortedByStartDate = mergeListsKeepingByStartSortOrder(
generated, loadPeriodsGenerators.subList(iterator
.nextIndex(), loadPeriodsGenerators.size()));
final int takenFromRemaining = sortedByStartDate.size()
- generated.size();
removeNextElements(iterator, takenFromRemaining);
addAtCurrentPosition(iterator, sortedByStartDate);
rewind(iterator, nextOne);
}
}
}
private void addAtCurrentPosition(
ListIterator<LoadPeriodGenerator> iterator,
List<LoadPeriodGenerator> sortedByStartDate) {
for (LoadPeriodGenerator l : sortedByStartDate) {
iterator.add(l);
}
}
private void removeNextElements(ListIterator<LoadPeriodGenerator> iterator,
final int elementsNumber) {
for (int i = 0; i < elementsNumber; i++) {
iterator.next();
iterator.remove();
}
}
private void rewind(ListIterator<LoadPeriodGenerator> iterator,
LoadPeriodGenerator nextOne) {
while (peekNext(iterator) != nextOne) {
iterator.previous();
}
}
private List<LoadPeriodGenerator> mergeListsKeepingByStartSortOrder(
List<LoadPeriodGenerator> joined,
List<LoadPeriodGenerator> remaining) {
List<LoadPeriodGenerator> result = new ArrayList<LoadPeriodGenerator>();
ListIterator<LoadPeriodGenerator> joinedIterator = joined
.listIterator();
ListIterator<LoadPeriodGenerator> remainingIterator = remaining
.listIterator();
while (joinedIterator.hasNext() && remainingIterator.hasNext()) {
LoadPeriodGenerator fromJoined = peekNext(joinedIterator);
LoadPeriodGenerator fromRemaining = peekNext(remainingIterator);
if (fromJoined.getStart().compareTo(fromRemaining.getStart()) <= 0) {
result.add(fromJoined);
joinedIterator.next();
} else {
result.add(fromRemaining);
remainingIterator.next();
}
}
if (joinedIterator.hasNext()) {
result.addAll(joined.subList(joinedIterator.nextIndex(), joined
.size()));
}
return result;
}
private LoadPeriodGenerator peekNext(
ListIterator<LoadPeriodGenerator> iterator) {
if (!iterator.hasNext()) {
return null;
}
LoadPeriodGenerator result = iterator.next();
iterator.previous();
return result;
}
}
class LoadPeriodGenerator {
private Resource resource;
private LocalDate start;
private LocalDate end;
private List<ResourceAllocation<?>> allocationsOnInterval = new ArrayList<ResourceAllocation<?>>();
private LoadPeriodGenerator(Resource resource, LocalDate start,
LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval) {
this.resource = resource;
this.start = start;
this.end = end;
this.allocationsOnInterval = allocationsOnInterval;
}
LoadPeriodGenerator(Resource resource, ResourceAllocation<?> initial) {
this.resource = resource;
this.start = initial.getStartDate();
this.end = initial.getEndDate();
this.allocationsOnInterval.add(initial);
}
public List<LoadPeriodGenerator> join(LoadPeriodGenerator next) {
if (!overlaps(next)) {
return stripEmpty(this, next);
}
if (isIncluded(next)) {
return stripEmpty(this.until(next.start), intersect(next), this
.from(next.end));
}
assert overlaps(next) && !isIncluded(next);
return stripEmpty(this.until(next.start), intersect(next), next
.from(end));
}
private List<LoadPeriodGenerator> stripEmpty(
LoadPeriodGenerator... generators) {
List<LoadPeriodGenerator> result = new ArrayList<LoadPeriodGenerator>();
for (LoadPeriodGenerator loadPeriodGenerator : generators) {
if (!loadPeriodGenerator.isEmpty()) {
result.add(loadPeriodGenerator);
}
}
return result;
}
private boolean isEmpty() {
return start.equals(end);
}
private LoadPeriodGenerator intersect(LoadPeriodGenerator other) {
return new LoadPeriodGenerator(resource, max(this.start, other.start),
min(this.end, other.end), plusAllocations(other));
}
private static LocalDate max(LocalDate l1, LocalDate l2) {
return l1.compareTo(l2) < 0 ? l2 : l1;
}
private static LocalDate min(LocalDate l1, LocalDate l2) {
return l1.compareTo(l2) < 0 ? l1 : l2;
}
private List<ResourceAllocation<?>> plusAllocations(
LoadPeriodGenerator other) {
List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>();
result.addAll(allocationsOnInterval);
result.addAll(other.allocationsOnInterval);
return result;
}
private LoadPeriodGenerator from(LocalDate newStart) {
return new LoadPeriodGenerator(resource, newStart, end,
allocationsOnInterval);
}
private LoadPeriodGenerator until(LocalDate newEnd) {
return new LoadPeriodGenerator(resource, start, newEnd,
allocationsOnInterval);
}
private boolean overlaps(LoadPeriodGenerator other) {
return (start.compareTo(other.end) < 0 && other.start
.compareTo(this.end) < 0);
}
private boolean isIncluded(LoadPeriodGenerator other) {
return other.start.compareTo(start) >= 0
&& other.end.compareTo(end) <= 0;
}
public LoadPeriod build() {
return new LoadPeriod(start, end, new LoadLevel(
calculateLoadPercentage()));
}
private int calculateLoadPercentage() {
final int totalResourceWorkHours = resource.getTotalWorkHours(start,
end);
int assigned = sumAssigned();
double proportion = assigned / (double) totalResourceWorkHours;
try {
return new BigDecimal(proportion).scaleByPowerOfTen(2).intValue();
} catch (NumberFormatException e) {
throw new RuntimeException(e);
}
}
private int sumAssigned() {
int sum = 0;
for (ResourceAllocation<?> resourceAllocation : allocationsOnInterval) {
sum += resourceAllocation.getAssignedHours(resource, start, end);
}
return sum;
}
public LocalDate getStart() {
return start;
}
public LocalDate getEnd() {
return end;
}
} |
package dr.inference.operators.hmc;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.CoercionMode;
import dr.inference.operators.GeneralOperator;
import dr.inference.operators.GibbsOperator;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.Arrays;
/**
* @author Marc A. Suchard
* @author Zhenyu Zhang
*/
public class NoUTurnOperator extends HamiltonianMonteCarloOperator implements GeneralOperator, GibbsOperator {
private final int dim = gradientProvider.getDimension();
private class Options { //TODO: these values might be adjusted for dual averaging.
private double kappa = 0.75;
private double t0 = 10.0;
private double gamma = 0.05;
private double targetAcceptRate = 0.9;
private double logProbErrorTol = 100.0;
private double muFactor = 10.0;
private int findMax = 100;
private int maxHeight = 10;
private int adaptLength = 1000;
}
// TODO Magic numbers; pass as options
private final Options options = new Options();
public NoUTurnOperator(CoercionMode mode, double weight, GradientWrtParameterProvider gradientProvider,
Parameter parameter, Transform transform, double stepSize, int nSteps, double drawVariance) {
super(mode, weight, gradientProvider, parameter, transform, stepSize, nSteps, drawVariance, 0.0);
}
@Override
protected InstabilityHandler getDefaultInstabilityHandler() {
return InstabilityHandler.IGNORE;
}
private class StepSize {
final double initialStepSize;
double stepSize;
double logStepSize;
double averageLogStepSize;
double h;
double mu;
private StepSize(double initialStepSize) {
this.initialStepSize = initialStepSize;
this.stepSize = initialStepSize;
this.logStepSize = Math.log(stepSize);
this.averageLogStepSize = 0;
this.h = 0;
this.mu = Math.log(options.muFactor * initialStepSize);
}
private void update(long m, double cumAcceptProb, double numAcceptProbStates, Options options) {
if (m <= options.adaptLength) {
h = (1 - 1 / (m + options.t0)) * h + 1 / (m + options.t0) * (options.targetAcceptRate - (cumAcceptProb / numAcceptProbStates));
logStepSize = mu - Math.sqrt(m) / options.gamma * h;
averageLogStepSize = Math.pow(m, -options.kappa) * logStepSize +
(1 - Math.pow(m, -options.kappa)) * averageLogStepSize;
stepSize = Math.exp(logStepSize);
}
}
}
private StepSize stepSizeInformation;
@Override
public String getOperatorName() {
return "No-UTurn-Sampler operator";
}
@Override
public double doOperation(Likelihood likelihood) {
final double[] initialPosition = leapFrogEngine.getInitialPosition();
final double initialLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
if (stepSizeInformation == null) {
stepSizeInformation = findReasonableStepSize(initialPosition);
final double testLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
assert (testLogLikelihood == initialLogLikelihood);
assert (Arrays.equals(leapFrogEngine.getInitialPosition(), initialPosition));
}
double[] position = takeOneStep(getCount() + 1, initialPosition);
leapFrogEngine.setParameter(position);
return 0.0;
}
private double[] takeOneStep(long m, double[] initialPosition) {
double[] endPosition = Arrays.copyOf(initialPosition, initialPosition.length);
final double[] initialMomentum = drawInitialMomentum(drawDistribution, dim);
final double initialJointDensity = getJointProbability(gradientProvider, initialMomentum);
double logSliceU = Math.log(MathUtils.nextDouble()) + initialJointDensity;
TreeState trajectoryTree = new TreeState(initialPosition, initialMomentum, 1, true);
// Trajectory of Hamiltonian dynamics endowed with a binary tree structure.
int height = 0;
while (trajectoryTree.flagContinue) {
double[] tmp = updateTrajectoryTree(trajectoryTree, height, logSliceU, initialJointDensity);
if (tmp != null) {
endPosition = tmp;
}
height++;
if (height > options.maxHeight) {
throw new RuntimeException("Reach maximum tree height"); // TODO Handle more gracefully
}
}
stepSizeInformation.update(m, trajectoryTree.cumAcceptProb, trajectoryTree.numAcceptProbStates, options);
return endPosition;
}
private double[] updateTrajectoryTree(TreeState trajectoryTree, int delpth, double logSliceU, double initialJointDensity) {
double[] endPosition = null;
final double uniform1 = MathUtils.nextDouble();
int direction = (uniform1 < 0.5) ? -1 : 1;
TreeState nextTrajectoryTree = buildTree(
trajectoryTree.getPosition(direction), trajectoryTree.getMomentum(direction),
direction, logSliceU, delpth, stepSizeInformation.stepSize, initialJointDensity);
trajectoryTree.mergeNextTree(nextTrajectoryTree, direction);
if (nextTrajectoryTree.flagContinue) {
final double uniform = MathUtils.nextDouble();
final double acceptProb = (double) nextTrajectoryTree.numNodes / (double) trajectoryTree.numNodes;
if (uniform < acceptProb) {
endPosition = nextTrajectoryTree.getSample();
}
}
return endPosition;
}
private TreeState buildTree(double[] position, double[] momentum, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
if (height == 0) {
return buildBaseCase(position, momentum, direction, logSliceU, stepSize, initialJointDensity);
} else {
return buildRecursiveCase(position, momentum, direction, logSliceU, height, stepSize, initialJointDensity);
}
}
private void handleInstability() {
throw new RuntimeException("Numerical instability; need to handle"); // TODO
}
private TreeState buildBaseCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, double stepSize, double initialJointDensity) {
// Make deep copy of position and momentum
double[] position = Arrays.copyOf(inPosition, inPosition.length);
double[] momentum = Arrays.copyOf(inMomentum, inMomentum.length);
leapFrogEngine.setParameter(position);
// "one frog jump!"
try {
doLeap(position, momentum, direction * stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
double logJointProbAfter = getJointProbability(gradientProvider, momentum);
final int numNodes = (logSliceU <= logJointProbAfter ? 1 : 0);
final boolean flagContinue = (logSliceU < options.logProbErrorTol + logJointProbAfter);
// Values for dual-averaging
final double acceptProb = Math.min(1.0, Math.exp(logJointProbAfter - initialJointDensity));
final int numAcceptProbStates = 1;
leapFrogEngine.setParameter(inPosition);
return new TreeState(position, momentum, numNodes, flagContinue, acceptProb, numAcceptProbStates);
}
private TreeState buildRecursiveCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, int height, double stepSize, double initialJointDensity) {
TreeState subtree = buildTree(inPosition, inMomentum, direction, logSliceU,
height - 1, // Recursion
stepSize, initialJointDensity);
if (subtree.flagContinue) {
TreeState nextSubtree = buildTree(subtree.getPosition(direction), subtree.getMomentum(direction), direction,
logSliceU, height - 1, stepSizeInformation.stepSize, initialJointDensity);
subtree.mergeNextTree(nextSubtree)
}
return subtree;
}
private void doLeap(final double[] position,
final double[] momentum,
final double stepSize) throws NumericInstabilityException {
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
leapFrogEngine.updatePosition(position, momentum, stepSize, 1.0);
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
}
private StepSize findReasonableStepSize(double[] initialPosition) {
double stepSize = 1;
double[] momentum = drawInitialMomentum(drawDistribution, dim);
int count = 1;
double[] position = Arrays.copyOf(initialPosition, dim);
double probBefore = getJointProbability(gradientProvider, momentum);
try {
doLeap(position, momentum, stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
double probAfter = getJointProbability(gradientProvider, momentum);
double a = ((probAfter - probBefore) > Math.log(0.5) ? 1 : -1);
double probRatio = Math.exp(probAfter - probBefore);
while (Math.pow(probRatio, a) > Math.pow(2, -a)) {
probBefore = probAfter;
//"one frog jump!"
try {
doLeap(position, momentum, stepSize);
} catch (NumericInstabilityException e) {
handleInstability();
}
probAfter = getJointProbability(gradientProvider, momentum);
probRatio = Math.exp(probAfter - probBefore);
stepSize = Math.pow(2, a) * stepSize;
count++;
if (count > options.findMax) {
throw new RuntimeException("Cannot find a reasonable step-size in " + options.findMax + " iterations");
}
}
leapFrogEngine.setParameter(initialPosition);
return new StepSize(stepSize);
}
private static boolean computeStopCriterion(boolean flagContinue, TreeState state) {
return computeStopCriterion(flagContinue,
state.getPosition(1), state.getPosition(-1),
state.getMomentum(1), state.getMomentum(-1));
}
private static boolean computeStopCriterion(boolean flagContinue,
double[] positionPlus, double[] positionMinus,
double[] momentumPlus, double[] momentumMinus) {
double[] positionDifference = subtractArray(positionPlus, positionMinus);
return flagContinue &&
getDotProduct(positionDifference, momentumMinus) >= 0 &&
getDotProduct(positionDifference, momentumPlus) >= 0;
}
private static double getDotProduct(double[] x, double[] y) {
assert (x.length == y.length);
final int dim = x.length;
double total = 0.0;
for (int i = 0; i < dim; i++) {
total += x[i] * y[i];
}
return total;
}
private static double[] subtractArray(double[] a, double[] b) {
assert (a.length == b.length);
final int dim = a.length;
double result[] = new double[dim];
for (int i = 0; i < dim; i++) {
result[i] = a[i] - b[i];
}
return result;
}
private double getJointProbability(GradientWrtParameterProvider gradientProvider, double[] momentum) {
assert (gradientProvider != null);
assert (momentum != null);
return gradientProvider.getLikelihood().getLogLikelihood() - getScaledDotProduct(momentum, 1.0)
- leapFrogEngine.getParameterLogJacobian();
}
private class TreeState {
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue) {
this(position, moment, numNodes, flagContinue, 0.0, 0);
}
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue,
double acceptProb, int numAcceptProbStates) {
this.position = new double[3][];
this.momentum = new double[3][];
for (int i = 0; i < 3; ++i) {
this.position[i] = position;
this.momentum[i] = moment;
}
// Recursion variables
this.numNodes = numNodes;
this.flagContinue = flagContinue;
// Dual-averaging variables
this.cumAcceptProb = acceptProb;
this.numAcceptProbStates = numAcceptProbStates;
}
private double[] getPosition(int direction) {
return position[getIndex(direction)];
}
private double[] getMomentum(int direction) {
return momentum[getIndex(direction)];
}
private double[] getSample() {
/*
Returns a state chosen uniformly from the acceptable states along a hamiltonian dyanmics trajectory tree.
The sample is updated recursively while building trees.
*/
return this.position[getIndex(0)];
}
private void setPosition(int direction, double[] position) {
this.position[getIndex(direction)] = position;
}
private void setMomentum(int direction, double[] momentum) {
this.momentum[getIndex(direction)] = momentum;
}
private void setSample(double[] position) {
this.setPosition(0, position)
}
private int getIndex(int direction) { // valid directions: -1, 0, +1
assert (direction >= -1 && direction <= 1);
return direction + 1;
}
private void mergeNextTree(TreeState nextTree, int direction) {
this.setPosition(direction, nextTree.getPosition(direction));
this.setMomentum(direction, nextTree.getMomentum(direction));
this.updateSample(nextTree)
this.numNodes += nextTree.numNodes;
this.flagContinue = computeStopCriterion(nextTree.flagContinue, this);
this.cumAcceptProb += nextTree.cumAcceptProb;
this.numAcceptProbStates += nextTree.numAcceptProbStates;
}
private void updateSample(TreeState nextTree) {
double uniform = MathUtils.nextDouble();
if (nextTree.numNodes > 0
&& uniform < ((double) nextTree.numNodes / (double) (this.numNodes + nextTree.numNodes))) {
this.setSample(nextTree.getSample());
}
}
final private double[][] position;
final private double[][] momentum;
private int numNodes;
private boolean flagContinue;
private double cumAcceptProb;
private int numAcceptProbStates;
}
} |
package edu.asu.diging.gilesecosystem.nepomuk.core.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import edu.asu.diging.gilesecosystem.nepomuk.core.service.properties.Properties;
import edu.asu.diging.gilesecosystem.septemberutil.service.impl.SystemMessageHandler;
import edu.asu.diging.gilesecosystem.util.properties.IPropertiesManager;
/**
* Class to initialize message handler class to send exception as kafka topic.
*
* @author snilapwa
*/
@Configuration
public class NepomukConfig {
@Autowired
private IPropertiesManager propertyManager;
@Bean
public SystemMessageHandler getMessageHandler() {
return new SystemMessageHandler(propertyManager.getProperty(Properties.APPLICATION_ID));
}
} |
package org.ngrinder.script.service;
import static org.ngrinder.common.util.Preconditions.checkNotEmpty;
import static org.ngrinder.common.util.Preconditions.checkNotNull;
import java.io.File;
import java.io.IOException;
import java.util.List;
import net.grinder.engine.agent.LocalScriptTestDriveService;
import net.grinder.util.thread.Condition;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.ngrinder.infra.config.Config;
import org.ngrinder.model.User;
import org.ngrinder.script.model.FileEntry;
import org.ngrinder.script.model.FileType;
import org.python.core.PySyntaxError;
import org.python.core.PyTuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
/**
* Script Validation Service
*
* @author JunHo Yoon
* @since 3.0
*/
@Component
public class ScriptValidationService {
private static final Logger LOG = LoggerFactory
.getLogger(ScriptValidationService.class);
@Autowired
private LocalScriptTestDriveService localScriptTestDriveService;
@Autowired
private FileEntryService fileEntryService;
@Autowired
private Config config;
/**
* Validate Script.
*
* It's quite complex.. to validate script, we need write jar files and
* script. Furthermore, to make a small log.. We have to copy optimized
* logback_worker.xml
*
* Finally this method returns the path of validating result file.
*
* @param user
* user
* @param scriptEntry
* scriptEntity.. at least path should be provided.
* @param useScriptInSVN
* true if the script content in SVN is used. otherwise, false
* @return validation result.
*/
public String validateScript(User user, FileEntry scriptEntry,
boolean useScriptInSVN, String hostString) {
try {
checkNotNull(scriptEntry, "scriptEntity should be not null");
checkNotEmpty(scriptEntry.getPath(),
"scriptEntity path should be provided");
if (!useScriptInSVN) {
checkNotEmpty(scriptEntry.getContent(),
"scriptEntity content should be provided");
}
checkNotNull(user, "user should be provided");
String result = checkSyntaxErrors(scriptEntry.getContent());
if (result != null) {
return result;
}
File scriptDirectory = config.getHome().getScriptDirectory(
String.valueOf(user.getId()));
File file = new File(scriptDirectory, "validation-0.log");
file.delete();
// Get all lib and resources in the script path
List<FileEntry> fileEntries = fileEntryService
.getLibAndResourcesEntries(user,
checkNotEmpty(scriptEntry.getPath()), null);
scriptDirectory.mkdirs();
// Distribute each files in that folder.
for (FileEntry each : fileEntries) {
// Directory is not subject to be distributed.
if (each.getFileType() == FileType.DIR) {
continue;
}
fileEntryService.writeContentTo(user, each.getPath(),
scriptDirectory);
}
// Copy logback...
File logbackXml = new ClassPathResource(
"/logback/logback-worker.xml").getFile();
FileUtils.copyFile(logbackXml, new File(scriptDirectory,
"logback-worker.xml"));
File scriptFile = new File(scriptDirectory,
FilenameUtils.getName(scriptEntry.getPath()));
String jvmArguments = "";
if (useScriptInSVN) {
fileEntryService.writeContentTo(user, scriptEntry.getPath(),
scriptDirectory);
} else {
FileUtils.writeStringToFile(scriptFile, scriptEntry
.getContent(), StringUtils.defaultIfBlank(
scriptEntry.getEncoding(), "UTF-8"));
}
File doValidate = localScriptTestDriveService.doValidate(
scriptDirectory, scriptFile, new Condition(), jvmArguments);
return FileUtils.readFileToString(doValidate);
} catch (IOException e) {
LOG.error("Error while distributing files on {} for {}", user,
scriptEntry.getPath());
LOG.error("Error details ", e);
}
return StringUtils.EMPTY;
}
/**
* Run jython parser to find out the syntax error..
*
* @param script
* @return script syntax error message. null otherwise.
*/
public String checkSyntaxErrors(String script) {
try {
org.python.core.parser.parse(script, "exec");
} catch (PySyntaxError e) {
try {
PyTuple pyTuple = (PyTuple) ((PyTuple) e.value).get(1);
Integer line = (Integer) pyTuple.get(1);
Integer column = (Integer) pyTuple.get(2);
String lineString = (String) pyTuple.get(3);
StringBuilder buf = new StringBuilder(lineString);
if (lineString.length() >= column) {
buf.insert(column - 1, "^");
}
return "Error occured\n" + " - Invalid Syntax Error on line "
+ line + " / column " + column + "\n" + buf.toString();
} catch (Exception ex) {
LOG.error("Error occured while evludation PySyntaxError", ex);
return "Error occured while evludation PySyntaxError";
}
}
return null;
}
} |
package edu.cmu.minorthird.text.model;
import edu.cmu.minorthird.text.*;
import java.io.*;
import java.util.*;
/** Unigram Language Model
*
* @author William Cohen
*/
public class UnigramModel
{
// avoid re-creating a zillion copies of Double(1), etc
final private static Double[] CACHED_DOUBLES = new Double[10];
static { for (int i=0; i<CACHED_DOUBLES.length; i++) CACHED_DOUBLES[i] = new Double(i); }
// private data
private Map freq = new HashMap();
private double total = 0;
/** Load a file where each line contains a <count,word> pair.
*/
public void load(File file) throws IOException,FileNotFoundException
{
LineNumberReader in = new LineNumberReader(new FileReader(file));
String line;
while ((line = in.readLine())!=null) {
String[] words = line.trim().split("\\s+");
if (words.length!=2) badLine(line,in);
int n=0;
try {
n = Integer.parseInt(words[0]);
} catch (NumberFormatException e) {
badLine(line,in);
}
total += n;
freq.put( words[1], getDouble(n) );
}
in.close();
}
private void badLine(String line,LineNumberReader in)
{
throw new IllegalStateException("bad input at line "+in.getLineNumber()+": "+line);
}
/** Save a unigram model
*/
public void save(File file) throws IOException
{
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
for (Iterator i=freq.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
out.println( ((Double)e.getValue()).intValue() + " " + e.getKey() );
}
out.close();
}
// routine to use cached doubles, rather than cons up new doubles
private Double getDouble(int n)
{
if (n<CACHED_DOUBLES.length) return CACHED_DOUBLES[n];
else return new Double(n);
}
/** Return log Prob(span|model).
* Assuming indendence, this is sum log Prob(tok_i|model).
*/
public double score(Span span)
{
double sum = 0;
double prior = 0.1/total; // lower than any word we've seen
for (int i=0; i<span.size(); i++) {
int f = getFrequency( span.getToken(i).getValue().toLowerCase() );
sum += estimatedLogProb( f, total, prior, 1.0 );
}
return sum;
}
public double getTotalWordCount()
{
return total;
}
public int getFrequency(String s)
{
String s1 = s.toLowerCase();
Double f = (Double)freq.get(s1);
if (f==null) return 0;
else return f.intValue();
}
public void incrementFrequency(String s)
{
String s1 = s.toLowerCase();
freq.put( s1, getDouble(getFrequency(s1)+1) );
}
private double estimatedLogProb(double k, double n, double prior, double pseudoCounts) {
return Math.log( (k+prior*pseudoCounts) / (n+pseudoCounts) );
}
static public void main(String[] args) throws IOException
{
if (args.length==0) {
System.out.println("usage 1: modelfile span1 span2...");
System.out.println("usage 2: textbase modelfile");
}
if (args.length==2) {
UnigramModel model = new UnigramModel();
TextBase base = FancyLoader.loadTextLabels(args[0]).getTextBase();
for (Span.Looper i=base.documentSpanIterator(); i.hasNext(); ) {
Span s = i.nextSpan();
for (int j=0; j<s.size(); j++) {
model.incrementFrequency( s.getToken(j).getValue() );
}
}
model.save(new File(args[1]));
} else {
UnigramModel model = new UnigramModel();
model.load(new File(args[0]));
TextBase base = new BasicTextBase();
for (int i=1; i<args.length; i++) {
base.loadDocument("argv."+i, args[i]);
}
for (Span.Looper j=base.documentSpanIterator(); j.hasNext(); ) {
Span s = j.nextSpan();
System.out.println(s.asString()+" => "+model.score(s));
for (int k=0; k<s.size(); k++) {
String w = s.getToken(k).getValue();
System.out.print(" "+w+":"+model.getFrequency(w));
}
System.out.println();
}
}
}
} |
package io.github.voidzombie.nhglib.graphics.shaders.tiled;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g3d.Attributes;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.shaders.BaseShader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
import io.github.voidzombie.nhglib.Nhg;
import io.github.voidzombie.nhglib.graphics.lights.tiled.NhgLight;
import io.github.voidzombie.nhglib.graphics.lights.tiled.NhgLightsAttribute;
import io.github.voidzombie.nhglib.utils.data.VectorPool;
import io.github.voidzombie.nhglib.utils.graphics.ShaderUtils;
public class TiledForwardShader extends BaseShader {
private float bones[];
private Vector3 vector;
private Matrix4 matrix;
private Matrix4 idtMatrix;
private Color color;
private Pixmap lightPixmap;
private Pixmap lightInfoPixmap;
private Texture lightTexture;
private Texture lightInfoTexture;
private Camera camera;
private Params params;
private Renderable renderable;
private Environment environment;
private SmallFrustums frustums;
private ShaderProgram shaderProgram;
private Array<IntArray> lightsFrustum;
private Array<NhgLight> lights;
private Array<NhgLight> lightsToRender;
public TiledForwardShader(Renderable renderable, Environment environment, Params params) {
this.renderable = renderable;
this.environment = environment;
this.params = params;
String prefix = createPrefix(renderable);
String vert = prefix + Gdx.files.internal("shaders/tiled_forward_shader.vert").readString();
String frag = prefix + Gdx.files.internal("shaders/tiled_forward_shader.frag").readString();
ShaderProgram.pedantic = false;
shaderProgram = new ShaderProgram(vert, frag);
String shaderLog = shaderProgram.getLog();
if (!shaderProgram.isCompiled()) {
throw new GdxRuntimeException(shaderLog);
}
if (!shaderLog.isEmpty()) {
Nhg.logger.log(this, shaderLog);
}
register("u_cameraPosition", new GlobalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, shader.camera.position);
}
});
register("u_mvpMatrix", new GlobalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, shader.camera.combined);
}
});
register("u_viewMatrix", new GlobalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, shader.camera.view);
}
});
register("u_modelMatrix", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, renderable.worldTransform);
}
});
register("u_graphicsWidth", new GlobalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, Gdx.graphics.getWidth());
}
});
register("u_graphicsHeight", new GlobalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, Gdx.graphics.getHeight());
}
});
register("u_albedo", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
TextureAttribute textureAttribute = (TextureAttribute) combinedAttributes.get(TextureAttribute.Diffuse);
if (textureAttribute != null) {
shader.set(inputID, textureAttribute.textureDescription.texture);
}
}
});
register("u_metalness", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
TextureAttribute textureAttribute = (TextureAttribute) combinedAttributes.get(TextureAttribute.Specular);
if (textureAttribute != null) {
shader.set(inputID, textureAttribute.textureDescription.texture);
}
}
});
register("u_roughness", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
TextureAttribute textureAttribute = (TextureAttribute) combinedAttributes.get(TextureAttribute.Bump);
if (textureAttribute != null) {
shader.set(inputID, textureAttribute.textureDescription.texture);
}
}
});
register("u_normal", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
TextureAttribute textureAttribute = (TextureAttribute) combinedAttributes.get(TextureAttribute.Normal);
if (textureAttribute != null) {
shader.set(inputID, textureAttribute.textureDescription.texture);
}
}
});
register("u_lights", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, lightTexture);
}
});
register("u_lightInfo", new LocalSetter() {
@Override
public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) {
shader.set(inputID, lightInfoTexture);
}
});
NhgLightsAttribute lightsAttribute = (NhgLightsAttribute) environment.get(NhgLightsAttribute.Type);
lights = lightsAttribute.lights;
}
@Override
public void init() {
super.init(shaderProgram, renderable);
idtMatrix = new Matrix4();
bones = new float[0];
lightsFrustum = new Array<>();
lightsToRender = new Array<>();
for (int i = 0; i < 100; i++) {
lightsFrustum.add(new IntArray());
}
color = new Color();
matrix = new Matrix4();
vector = VectorPool.getVector3();
lightTexture = new Texture(64, 128, Pixmap.Format.RGBA8888);
lightTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
lightInfoTexture = new Texture(1, 128, Pixmap.Format.RGBA8888);
lightInfoTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
lightPixmap = new Pixmap(64, 128, Pixmap.Format.RGBA8888);
lightPixmap.setBlending(Pixmap.Blending.None);
lightInfoPixmap = new Pixmap(1, 128, Pixmap.Format.RGBA8888);
lightInfoPixmap.setBlending(Pixmap.Blending.None);
frustums = new SmallFrustums(10, 10);
}
@Override
public int compareTo(Shader other) {
return 0;
}
@Override
public boolean canRender(Renderable instance) {
boolean diffuse = ShaderUtils.hasDiffuse(instance) == params.diffuse;
boolean normal = ShaderUtils.hasNormal(instance) == params.normal;
boolean specular = ShaderUtils.hasSpecular(instance) == params.specular;
boolean bones = ShaderUtils.useBones(instance) == params.useBones;
boolean lit = ShaderUtils.hasLights(instance.environment) == params.lit;
return diffuse && normal && specular && bones && lit;
}
@Override
public void begin(Camera camera, RenderContext context) {
this.camera = camera;
frustums.setFrustums(((PerspectiveCamera) camera));
if (lights != null) {
for (NhgLight light : lights) {
if (camera.frustum.sphereInFrustum(light.position, light.radius) &&
camera.position.dst(light.position) < 15f) {
lightsToRender.add(light);
}
}
}
createLightTexture();
super.begin(camera, context);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
}
@Override
public void render(Renderable renderable) {
for (int light = 0; light < lightsToRender.size; light++) {
NhgLight nhgLight = lightsToRender.get(light);
String lightUniform = "u_lightsList[" + light + "].";
shaderProgram.setUniformf(lightUniform + "position", getViewSpacePosition(nhgLight));
shaderProgram.setUniformf(lightUniform + "direction", nhgLight.direction);
shaderProgram.setUniformf(lightUniform + "intensity", nhgLight.intensity);
shaderProgram.setUniformf(lightUniform + "innerAngle", nhgLight.innerAngle);
shaderProgram.setUniformf(lightUniform + "outerAngle", nhgLight.outerAngle);
}
updateBones(renderable);
super.render(renderable);
}
@Override
public void end() {
lightsToRender.clear();
super.end();
Gdx.gl.glDisable(GL20.GL_BLEND);
Gdx.gl.glDisable(GL20.GL_CULL_FACE);
}
@Override
public void dispose() {
shaderProgram.dispose();
super.dispose();
}
private void createLightTexture() {
int i;
for (i = 0; i < 100; i++) {
lightsFrustum.get(i).clear();
}
for (i = 0; i < lightsToRender.size; i++) {
NhgLight light = lightsToRender.get(i);
frustums.checkFrustums(light.position, light.radius, lightsFrustum, i);
color.set(light.color);
color.a = light.radius / 255.0f;
lightInfoPixmap.setColor(color);
lightInfoPixmap.drawPixel(0, i);
}
lightInfoTexture.draw(lightInfoPixmap, 0, 0);
for (int row = 0; row < 100; row++) {
int column = 0;
float r = lightsFrustum.get(row).size;
color.set(r / 255.0f, 0, 0, 0);
lightPixmap.setColor(color);
lightPixmap.drawPixel(column, row);
column++;
for (int k = 0; k < lightsFrustum.get(row).size; k++) {
int j = (lightsFrustum.get(row).get(k));
color.set(((float) j) / 255.0f, 0, 0, 0);
lightPixmap.setColor(color);
lightPixmap.drawPixel(column, row);
column++;
}
}
lightTexture.draw(lightPixmap, 0, 0);
}
private void updateBones(Renderable renderable) {
if (renderable.bones != null) {
bones = new float[renderable.bones.length * 16];
for (int i = 0; i < bones.length; i++) {
final int idx = i / 16;
bones[i] = (idx >= renderable.bones.length || renderable.bones[idx] == null) ?
idtMatrix.val[i % 16] : renderable.bones[idx].val[i % 16];
}
shaderProgram.setUniformMatrix4fv("u_bones", bones, 0, bones.length);
}
}
private String createPrefix(Renderable renderable) {
String prefix = "";
if (params.useBones) {
prefix += "#define numBones " + 12 + "\n";
final int n = renderable.meshPart.mesh.getVertexAttributes().size();
for (int i = 0; i < n; i++) {
final VertexAttribute attr = renderable.meshPart.mesh.getVertexAttributes().get(i);
if (attr.usage == VertexAttributes.Usage.BoneWeight) {
prefix += "#define boneWeight" + attr.unit + "Flag\n";
}
}
}
if (params.diffuse) {
prefix += "#define diffuse\n";
}
if (params.normal) {
prefix += "#define normal\n";
}
if (params.specular) {
prefix += "#define specular\n";
}
if (params.lit) {
NhgLightsAttribute lightsAttribute = (NhgLightsAttribute) environment.get(NhgLightsAttribute.Type);
prefix += "#define lights " + lightsAttribute.lights.size + "\n";
}
return prefix;
}
private Vector3 getViewSpacePosition(NhgLight light) {
Vector3 position = VectorPool.getVector3();
position.set(light.position)
.mul(camera.view);
return position;
}
public static class Params {
boolean useBones;
boolean diffuse;
boolean normal;
boolean specular;
boolean lit;
}
} |
package net.mm2d.dmsexplorer;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
import android.widget.VideoView;
import net.mm2d.android.cds.CdsObject;
import java.util.concurrent.TimeUnit;
/**
* Activity
*
* @author <a href="mailto:ryo@mm2d.net">(OHMAE Ryosuke)</a>
*/
public class MovieActivity extends AppCompatActivity {
private static final String TAG = "MovieActivity";
private static final long NAVIGATION_INTERVAL = TimeUnit.SECONDS.toMillis(3);
private VideoView mVideoView;
private View mRoot;
private View mToolbar;
private ControlView mControlPanel;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_movie);
mRoot = findViewById(R.id.root);
mRoot.setOnClickListener(v -> {
showNavigation();
postHideNavigation();
});
mHandler = new Handler();
final Intent intent = getIntent();
final CdsObject object = intent.getParcelableExtra(Const.EXTRA_OBJECT);
final Uri uri = intent.getData();
findViewById(R.id.toolbarBack).setOnClickListener(view -> onBackPressed());
final TextView title = (TextView) findViewById(R.id.toolbarTitle);
title.setText(object.getTitle());
mToolbar = findViewById(R.id.toolbar);
mControlPanel = (ControlView) findViewById(R.id.controlPanel);
mControlPanel.setOnCompletionListener(mp -> onBackPressed());
mControlPanel.setOnUserActionListener(this::postHideNavigation);
mVideoView = (VideoView) findViewById(R.id.videoView);
assert mVideoView != null;
mVideoView.setOnPreparedListener(mControlPanel);
mVideoView.setVideoURI(uri);
mRoot.setOnSystemUiVisibilityChangeListener(visibility -> {
if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
mControlPanel.setVisibility(View.VISIBLE);
}
});
adjustControlPanel();
showNavigation();
postHideNavigation();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
adjustControlPanel();
}
private void adjustControlPanel() {
final Display display = getWindowManager().getDefaultDisplay();
final Point p1 = new Point();
display.getSize(p1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final Point p2 = new Point();
display.getRealSize(p2);
adjustControlPanel(p2.x - p1.x, p2.y - p1.y);
} else {
final View v = getWindow().getDecorView();
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
adjustControlPanel(v.getWidth() - p1.x, v.getHeight() - p1.y);
}
});
}
}
private void adjustControlPanel(int right, int bottom) {
mControlPanel.setPadding(0, 0, right, bottom);
final int topPadding = getResources().getDimensionPixelSize(R.dimen.status_bar_size);
mToolbar.setPadding(0, topPadding, right, 0);
}
private final Runnable mHideNavigationTask = this::hideNavigation;
private void postHideNavigation() {
mHandler.removeCallbacks(mHideNavigationTask);
mHandler.postDelayed(mHideNavigationTask, NAVIGATION_INTERVAL);
}
private void showNavigation() {
mToolbar.setVisibility(View.VISIBLE);
mControlPanel.setVisibility(View.VISIBLE);
mRoot.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
private void hideNavigation() {
mToolbar.setVisibility(View.GONE);
mControlPanel.setVisibility(View.GONE);
final int visibility;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
visibility = View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
} else {
visibility = View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
}
mRoot.setSystemUiVisibility(visibility);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
mVideoView.stopPlayback();
super.onDestroy();
}
} |
package com.yahoo.vespa.hosted.provision.maintenance;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Deployer;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.jdisc.Metric;
import com.yahoo.transaction.Mutex;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.provisioning.DockerHostCapacity;
import com.yahoo.vespa.hosted.provision.provisioning.HostProvisioner;
import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
/**
* @author bratseth
*/
public class Rebalancer extends NodeRepositoryMaintainer {
static final Duration waitTimeAfterPreviousDeployment = Duration.ofMinutes(10);
private final Deployer deployer;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return; // All nodes will be allocated on new hosts, so rebalancing makes no sense
if (nodeRepository().zone().environment().isTest()) return; // Test zones have short lived deployments, no need to rebalance
// Work with an unlocked snapshot as this can take a long time and full consistency is not needed
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, nodeRepository().resourcesCalculator());
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
private boolean zoneIsStable(NodeList allNodes) {
NodeList active = allNodes.state(Node.State.active);
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, nodeRepository().resourcesCalculator());
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
ApplicationId applicationId = node.allocation().get().owner();
if (applicationId.instance().isTester()) continue;
if (deployedRecently(applicationId)) continue;
for (Node toHost : allNodes.filter(nodeRepository()::canAllocateTenantNodeTo)) {
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (nodeToMove.get().status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.Rebalancer, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, metric, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
Optional<Node> expectedNewNode = Optional.empty();
try {
if ( ! deployment.prepare()) return false;
expectedNewNode =
nodeRepository().getNodes(application, Node.State.reserved).stream()
.filter(node -> !node.hostname().equals(move.node.hostname()))
.filter(node -> node.allocation().get().membership().cluster().id().equals(move.node.allocation().get().membership().cluster().id()))
.findAny();
if (expectedNewNode.isEmpty()) return false;
if ( ! expectedNewNode.get().hasParent(move.toHost.hostname())) return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false); // Necessary if this failed, no-op otherwise
// Immediately clean up if we reserved the node but could not activate or reserved a node on the wrong host
expectedNewNode.flatMap(node -> nodeRepository().getNode(node.hostname(), Node.State.reserved))
.ifPresent(node -> nodeRepository().setDirty(node, Agent.Rebalancer, "Expired by Rebalancer"));
}
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().justNumbers()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().justNumbers()));
return skewBefore - skewAfter;
}
protected boolean deployedRecently(ApplicationId application) {
return deployer.lastDeployTime(application)
.map(lastDeployTime -> lastDeployTime.isAfter(clock.instant().minus(waitTimeAfterPreviousDeployment)))
// We only know last deploy time for applications that were deployed on this config server,
// the rest will be deployed on another config server
.orElse(true);
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
} |
/**
* EditEntityScreen
*
* Class representing the screen that allows users to edit properties of
* grid entities, including triggers and appearance.
*
* @author Willy McHie
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.entity.Trigger;
import edu.wheaton.simulator.expression.Expression;
import edu.wheaton.simulator.simulation.GUIToAgentFacade;
public class EditEntityScreen extends Screen {
private static final long serialVersionUID = 4021299442173260142L;
private Boolean editing;
private Prototype agent;
private JTabbedPane tabs;
private String currentTab;
private JPanel generalPanel;
private JTextField nameField;
private JColorChooser colorTool;
private ArrayList<JTextField> fieldNames;
private ArrayList<JTextField> fieldValues;
//private ArrayList<JComboBox> fieldTypes;
//private String[] typeNames = { "Integer", "Double", "String", "Boolean" };
private ArrayList<JButton> fieldDeleteButtons;
private ArrayList<JPanel> fieldSubPanels;
private Component glue;
private Component glue2;
private JButton addFieldButton;
private JToggleButton[][] buttons;
private JPanel fieldListPanel;
private ArrayList<JTextField> triggerNames;
private ArrayList<JTextField> triggerPriorities;
private ArrayList<JTextField> triggerConditions;
private ArrayList<JTextField> triggerResults;
private ArrayList<JButton> triggerDeleteButtons;
private ArrayList<JPanel> triggerSubPanels;
private JButton addTriggerButton;
private JPanel triggerListPanel;
private HashSet<Integer> removedFields;
private HashSet<Integer> removedTriggers;
public EditEntityScreen(final ScreenManager sm) {
super(sm);
this.setLayout(new BorderLayout());
removedFields = new HashSet<Integer>();
removedTriggers = new HashSet<Integer>();
nameField = new JTextField(25);
nameField.setMaximumSize(new Dimension(400, 40));
colorTool = new JColorChooser();
buttons = new JToggleButton[7][7];
fieldNames = new ArrayList<JTextField>();
fieldValues = new ArrayList<JTextField>();
//fieldTypes = new ArrayList<JComboBox>();
fieldSubPanels = new ArrayList<JPanel>();
triggerSubPanels = new ArrayList<JPanel>();
triggerNames = new ArrayList<JTextField>();
triggerPriorities = new ArrayList<JTextField>();
triggerConditions = new ArrayList<JTextField>();
triggerResults = new ArrayList<JTextField>();
fieldDeleteButtons = new ArrayList<JButton>();
triggerDeleteButtons = new ArrayList<JButton>();
glue = Box.createVerticalGlue();
glue2 = Box.createVerticalGlue();
currentTab = "General";
fieldListPanel = makeBoxPanel(BoxLayout.Y_AXIS);
triggerListPanel = makeBoxPanel(BoxLayout.Y_AXIS);
tabs = new JTabbedPane();
generalPanel = makeGeneralPanel();
addFieldButton = makeAddFieldButton(this);
addTriggerButton = makeAddTriggerButton(this);
JPanel iconPanel = makeIconPanel();
initIconDesignObject(iconPanel);
//serialization not yet implemented
//JButton loadIconButton = new JButton("Load icon");
initGeneralPanel(iconPanel);
//JLabel fieldTypeLabel = new JLabel("Field Type");
addField();
// TODO make sure components line up
initFieldSubPanels();
//fieldTypeLabel.setHorizontalAlignment(SwingConstants.LEFT);
//fieldLabelsPanel.add(fieldTypeLabel);
initFieldListPanel();
// fieldSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT);
addTrigger();
initTriggerSubPanels();
initTriggerListPanel();
initTabs();
this.add(makeScreenLabel(), BorderLayout.NORTH);
this.add(tabs, BorderLayout.CENTER);
this.add(makeLowerPanel(this,sm), BorderLayout.SOUTH);
}
private void initTabs(){
tabs.addTab("General", generalPanel);
tabs.addTab("Fields", makeFieldMainPanel(fieldListPanel));
tabs.addTab("Triggers", makeTriggerMainPanel(triggerListPanel));
//tabs.addTab("Triggers", new EditTriggerScreen(sm));
tabs.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
if (currentTab == "General")
sendGeneralInfo();
else if (currentTab == "Fields")
sendFieldInfo();
else
sendTriggerInfo();
currentTab = tabs.getTitleAt(tabs.getSelectedIndex());
}
});
}
private void initTriggerListPanel(){
triggerListPanel.add(triggerSubPanels.get(0));
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(glue2);
}
private void initTriggerSubPanels(){
triggerSubPanels.get(0).setLayout(
new BoxLayout(triggerSubPanels.get(0), BoxLayout.X_AXIS));
triggerSubPanels.get(0).add(triggerNames.get(0));
triggerSubPanels.get(0).add(triggerPriorities.get(0));
triggerSubPanels.get(0).add(triggerConditions.get(0));
triggerSubPanels.get(0).add(triggerResults.get(0));
triggerSubPanels.get(0).add(triggerDeleteButtons.get(0));
triggerSubPanels.get(0).setAlignmentX(CENTER_ALIGNMENT);
// triggerSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT);
}
private void initFieldListPanel(){
fieldListPanel.add(fieldSubPanels.get(0));
fieldListPanel.add(addFieldButton);
fieldListPanel.add(glue);
}
private void initFieldSubPanels(){
fieldSubPanels.get(0).setLayout(
new BoxLayout(fieldSubPanels.get(0), BoxLayout.X_AXIS));
fieldSubPanels.get(0).add(fieldNames.get(0));
//fieldSubPanels.get(0).add(fieldTypes.get(0));
fieldSubPanels.get(0).add(fieldValues.get(0));
fieldSubPanels.get(0).add(fieldDeleteButtons.get(0));
}
private void initGeneralPanel(JPanel iconPanel){
generalPanel.add(makeGeneralLabel());
generalPanel.add(makeNameLabel());
generalPanel.add(nameField);
generalPanel.add(makeMainPanel(colorTool,iconPanel));
//generalPanel.add(loadIconButton);
}
private void initIconDesignObject(JPanel iconPanel){
//Creates the icon design object.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
buttons[i][j] = new JToggleButton();
buttons[i][j].setOpaque(true);
buttons[i][j].setBackground(Color.WHITE);
buttons[i][j].setActionCommand(i + "" + j);
//When the button is pushed it switches colors.
buttons[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
JToggleButton jb = buttons[Integer.parseInt(str
.charAt(0) + "")][Integer.parseInt(str
.charAt(1) + "")];
if (jb.getBackground().equals(Color.WHITE)) {
jb.setBackground(Color.BLACK);
jb.setForeground(Color.BLACK);
}
else {
jb.setBackground(Color.WHITE);
jb.setForeground(Color.WHITE);
}
}
});
iconPanel.add(buttons[i][j]);
}
}
}
private static JButton makeAddFieldButton(final EditEntityScreen screen){
JButton addFieldButton = makeButton("Add Field",new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
screen.addField();
}
});
return addFieldButton;
}
private static JButton makeAddTriggerButton(final EditEntityScreen screen){
JButton addTriggerButton = makeButton("Add Trigger",new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
screen.addTrigger();
}
});
return addTriggerButton;
}
private static JPanel makeGeneralPanel(){
JPanel generalPanel = makeBoxPanel(BoxLayout.PAGE_AXIS);
return generalPanel;
}
private static JLabel makeNameLabel(){
return new JLabel("Name: ");
}
private static JLabel makeGeneralLabel(){
JLabel generalLabel = makeLabelPreferredSize("General Info",300,80);
generalLabel.setHorizontalAlignment(SwingConstants.CENTER);
return generalLabel;
}
private static JPanel makeMainPanel(JColorChooser colorTool, JPanel iconPanel){
JPanel mainPanel = makeBoxPanel(BoxLayout.X_AXIS);
mainPanel.setMaximumSize(new Dimension(1200, 500));
mainPanel.add(makeColorPanel(colorTool));
mainPanel.add(iconPanel);
return mainPanel;
}
private static JPanel makeIconPanel(){
JPanel iconPanel = new JPanel();
iconPanel.setLayout(new GridLayout(7, 7));
iconPanel.setMinimumSize(new Dimension(500, 500));
iconPanel.setAlignmentX(RIGHT_ALIGNMENT);
return iconPanel;
}
private static JPanel makeColorPanel(JColorChooser colorTool){
JPanel colorPanel = new JPanel();
colorPanel.add(colorTool);
colorPanel.setAlignmentX(LEFT_ALIGNMENT);
return colorPanel;
}
private static JPanel makeTriggerMainPanel(JPanel triggerListPanel){
JLabel triggerNameLabel = makeLabelPreferredSize("Trigger Name",130,30);
triggerNameLabel.setHorizontalAlignment(SwingConstants.LEFT);
JLabel triggerPriorityLabel = makeLabelPreferredSize("Trigger Priority",180,30);
JLabel triggerConditionLabel = makeLabelPreferredSize("Trigger Condition",300,30);
JLabel triggerResultLabel = makeLabelPreferredSize("Trigger Result",300,30);
JPanel triggerLabelsPanel = makeBoxPanel(BoxLayout.X_AXIS);
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerLabelsPanel.add(triggerNameLabel);
triggerLabelsPanel.add(triggerPriorityLabel);
triggerLabelsPanel.add(triggerConditionLabel);
triggerLabelsPanel.add(triggerResultLabel);
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerLabelsPanel.setAlignmentX(CENTER_ALIGNMENT);
JLabel triggerLabel = makeLabelPreferredSize("Trigger Info",300,100);
triggerLabel.setHorizontalAlignment(SwingConstants.CENTER);
JPanel triggerBodyPanel = makeTriggerBodyPanel();
triggerBodyPanel.add(triggerLabelsPanel);
triggerBodyPanel.add(triggerListPanel);
JPanel triggerMainPanel = makeBorderPanel(new BorderLayout());
triggerMainPanel.add(triggerLabel, BorderLayout.NORTH);
triggerMainPanel.add(triggerBodyPanel, BorderLayout.CENTER);
return triggerMainPanel;
}
private static JPanel makeFieldMainPanel(JPanel fieldListPanel){
JLabel fieldNameLabel = makeLabelPreferredSize("Field Name",350,30);
fieldNameLabel.setHorizontalAlignment(SwingConstants.LEFT);
fieldNameLabel.setAlignmentX(LEFT_ALIGNMENT);
JLabel fieldValueLabel = makeLabelPreferredSize("Field Initial Value",400,30);
fieldValueLabel.setHorizontalAlignment(SwingConstants.CENTER);
JPanel fieldLabelsPanel = makeBoxPanel(BoxLayout.X_AXIS);
fieldLabelsPanel.add(Box.createHorizontalGlue());
fieldLabelsPanel.add(fieldNameLabel);
fieldLabelsPanel.add(fieldValueLabel);
fieldLabelsPanel.add(Box.createHorizontalGlue());
JPanel fieldBodyPanel = makeFieldBodyPanel(fieldLabelsPanel,fieldListPanel);
JLabel fieldLabel = makeLabelPreferredSize("Field Info",300,100);
fieldLabel.setHorizontalAlignment(SwingConstants.CENTER);
JPanel fieldMainPanel = makeBorderPanel(new BorderLayout());
fieldMainPanel.add(fieldLabel, BorderLayout.NORTH);
fieldMainPanel.add(fieldBodyPanel, BorderLayout.CENTER);
return fieldMainPanel;
}
private static JPanel makeLowerPanel(final EditEntityScreen screen, final ScreenManager sm){
JPanel lowerPanel = new JPanel();
lowerPanel.add(makeCancelButton(screen,sm));
lowerPanel.add(makeFinishButton(screen,sm));
return lowerPanel;
}
private static JPanel makeFieldBodyPanel(JPanel fieldLabelsPanel, JPanel fieldListPanel){
JPanel fieldBodyPanel = makeBoxPanel(BoxLayout.Y_AXIS);
fieldBodyPanel.add(fieldLabelsPanel);
fieldBodyPanel.add(fieldListPanel);
return fieldBodyPanel;
}
private static JPanel makeTriggerBodyPanel(){
JPanel triggerBodyPanel = makeBoxPanel(BoxLayout.Y_AXIS);
return triggerBodyPanel;
}
private static JLabel makeScreenLabel(){
JLabel label = new JLabel("Edit Entities");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setHorizontalTextPosition(SwingConstants.CENTER);
return label;
}
private static JButton makeCancelButton(final EditEntityScreen screen, final ScreenManager sm){
JButton cancelButton = makeButton("Cancel",new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sm.update(sm.getScreen("Entities"));
screen.reset();
}
});
return cancelButton;
}
private static JButton makeFinishButton(final EditEntityScreen screen, final ScreenManager sm){
JButton finishButton = makeButton("Finish",new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (screen.sendInfo()) {
sm.update(sm.getScreen("Edit Simulation"));
screen.reset();
}
}
});
return finishButton;
}
public void load(String str) {
reset();
tabs.setSelectedComponent(generalPanel);
sm.getFacade();
agent = GUIToAgentFacade.getPrototype(str);
nameField.setText(agent.getName());
colorTool.setColor(agent.getColor());
byte[] designBytes = agent.getDesign();
byte byter = Byte.parseByte("0000001", 2);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if ((designBytes[i] & (byter << j)) != Byte.parseByte("0000000", 2)) {
buttons[i][6-j].doClick();
}
}
}
Map<String, String> fields = agent.getCustomFieldMap();
int i = 0;
for (String s : fields.keySet()) {
addField();
fieldNames.get(i).setText(s);
fieldValues.get(i).setText(fields.get(s));
i++;
}
List<Trigger> triggers = agent.getTriggers();
int j = 0;
for (Trigger t : triggers) {
addTrigger();
triggerNames.get(j).setText(t.getName());
triggerConditions.get(j).setText(t.getConditions().toString());
triggerResults.get(j).setText(t.getBehavior().toString());
triggerPriorities.get(j).setText(t.getPriority() +"");
j++;
}
}
public void reset() {
agent = null;
nameField.setText("");
colorTool.setColor(Color.WHITE);
for (int x = 0; x < 7; x++) {
for (int y = 0; y < 7; y++) {
buttons[x][y].setSelected(false);
buttons[x][y].setBackground(Color.WHITE);
}
}
fieldNames.clear();
//fieldTypes.clear();
fieldValues.clear();
fieldDeleteButtons.clear();
fieldSubPanels.clear();
removedFields.clear();
fieldListPanel.removeAll();
fieldListPanel.add(addFieldButton);
triggerNames.clear();
triggerPriorities.clear();
triggerConditions.clear();
triggerResults.clear();
triggerDeleteButtons.clear();
triggerSubPanels.clear();
removedTriggers.clear();
triggerListPanel.removeAll();
triggerListPanel.add(addTriggerButton);
}
public boolean sendInfo() {
sendGeneralInfo();
sendFieldInfo();
return sendTriggerInfo();
}
public void sendGeneralInfo(){
if (!editing) {
sm.getFacade();
GUIToAgentFacade.createPrototype(nameField.getText(),
sm.getFacade().getGrid(), colorTool.getColor(), generateBytes());
sm.getFacade();
agent = GUIToAgentFacade.getPrototype(nameField.getText());
}
else {
agent.setPrototypeName(agent.getName(),
nameField.getText());
agent.setColor(colorTool.getColor());
agent.setDesign(generateBytes());
Prototype.addPrototype(agent);
}
}
public void sendFieldInfo(){
try{
for (int i = 0; i < fieldNames.size(); i++) {
if (!removedFields.contains(i)) {
if (fieldNames.get(i).getText().equals("")
|| fieldValues.get(i).getText().equals("")) {
throw new Exception("All fields must have input");
}
}
}
for (int i = 0; i < fieldNames.size(); i++) {
if (removedFields.contains(i)) {
if (agent.hasField(fieldNames.get(i).getText()))
agent.removeField(fieldNames.get(i).toString());
} else {
if (agent.hasField(fieldNames.get(i).getText())) {
agent.updateField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} else
try {
agent.addField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} catch (ElementAlreadyContainedException e) {
e.printStackTrace();
}
}
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public boolean sendTriggerInfo(){
boolean toReturn = false;
try{
for (int j = 0; j < triggerNames.size(); j++) {
if (!removedTriggers.contains(j)) {
if (triggerNames.get(j).getText().equals("")
|| triggerConditions.get(j).getText().equals("")
|| triggerResults.get(j).getText().equals("")) {
throw new Exception("All fields must have input");
}
}
if (Integer.parseInt(triggerPriorities.get(j).getText()) < 0) {
throw new Exception("Priority must be greater than 0");
}
}
for (int i = 0; i < triggerNames.size(); i++) {
if (removedTriggers.contains(i)) {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.removeTrigger(triggerNames.get(i).getText());
} else {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.updateTrigger(triggerNames.get(i).getText(),
generateTrigger(i));
else
agent.addTrigger(generateTrigger(i));
}
}
toReturn = true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Priorities field must be an integer greater than 0.");
e.printStackTrace();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public void setEditing(Boolean b) {
editing = b;
}
private void addField() {
JPanel newPanel = makeBoxPanel(BoxLayout.X_AXIS);
JTextField newName = new JTextField(25);
newName.setMaximumSize(new Dimension(300, 40));
fieldNames.add(newName);
// JComboBox newType = new JComboBox(typeNames);
// newType.setMaximumSize(new Dimension(200, 40));
// fieldTypes.add(newType);
JTextField newValue = new JTextField(25);
newValue.setMaximumSize(new Dimension(300, 40));
fieldValues.add(newValue);
JButton newButton = makeButton("Delete",new DeleteFieldListener());
fieldDeleteButtons.add(newButton);
newButton.setActionCommand(fieldDeleteButtons.indexOf(newButton) + "");
newPanel.add(newName);
// newPanel.add(newType);
newPanel.add(newValue);
newPanel.add(newButton);
fieldSubPanels.add(newPanel);
fieldListPanel.add(newPanel);
fieldListPanel.add(addFieldButton);
fieldListPanel.add(glue);
repaint();
}
private void addTrigger() {
JPanel newPanel = makeBoxPanel(BoxLayout.X_AXIS);
JTextField newName = new JTextField(25);
newName.setMaximumSize(new Dimension(200, 40));
triggerNames.add(newName);
JTextField newPriority = new JTextField(15);
newPriority.setMaximumSize(new Dimension(150, 40));
triggerPriorities.add(newPriority);
JTextField newCondition = new JTextField(50);
newCondition.setMaximumSize(new Dimension(300, 40));
triggerConditions.add(newCondition);
JTextField newResult = new JTextField(50);
newResult.setMaximumSize(new Dimension(300, 40));
triggerResults.add(newResult);
JButton newButton = makeButton("Delete",new DeleteTriggerListener());
triggerDeleteButtons.add(newButton);
newButton.setActionCommand(triggerDeleteButtons.indexOf(newButton)
+ "");
newPanel.add(newName);
newPanel.add(newPriority);
newPanel.add(newCondition);
newPanel.add(newResult);
newPanel.add(newButton);
triggerSubPanels.add(newPanel);
triggerListPanel.add(newPanel);
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(glue2);
repaint();
}
private byte[] generateBytes() {
String str = "";
byte[] toReturn = new byte[7];
for (int column = 0; column < 7; column++) {
for (int row = 0; row < 7; row++) {
if (buttons[column][row].getBackground().equals(Color.BLACK)) {
str += "1";
} else {
str += "0";
}
}
str += ":";
}
str = str.substring(0, str.lastIndexOf(':'));
String[] byteStr = str.split(":");
for (int i = 0; i < 7; i++) {
toReturn[i] = Byte.parseByte(byteStr[i], 2);
}
return toReturn;
}
private Trigger generateTrigger(int i) {
return new Trigger(triggerNames.get(i).getText(),
Integer.parseInt(triggerPriorities.get(i).getText()),
new Expression(triggerConditions.get(i).getText()),
new Expression(triggerResults.get(i).getText()));
}
private class DeleteFieldListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
removedFields.add(Integer.parseInt(e.getActionCommand()));
fieldListPanel.remove(fieldSubPanels.get(Integer.parseInt(e
.getActionCommand())));
repaint();
}
}
private class DeleteTriggerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
removedTriggers.add(Integer.parseInt(e.getActionCommand()));
triggerListPanel.remove(triggerSubPanels.get(Integer.parseInt(e
.getActionCommand())));
repaint();
}
}
@Override
public void load() {
reset();
addField();
addTrigger();
}
} |
/**
* EditEntityScreen
*
* Class representing the screen that allows users to edit properties of
* grid entities, including triggers and appearance.
*
* @author Willy McHie
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import com.sun.corba.se.impl.encoding.CodeSetConversion.BTCConverter;
import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.entity.Trigger;
import edu.wheaton.simulator.expression.Expression;
//TODO deletes prototype after editing
public class EditEntityScreen extends Screen {
private static final long serialVersionUID = 4021299442173260142L;
private Boolean editing;
private Prototype agent;
private JTextField nameField;
private JColorChooser colorTool;
private ArrayList<JTextField> fieldNames;
private ArrayList<JTextField> fieldValues;
private ArrayList<JComboBox> fieldTypes;
private String[] typeNames = { "Integer", "Double", "String", "Boolean" };
private ArrayList<JButton> fieldDeleteButtons;
private ArrayList<JPanel> fieldSubPanels;
private Component glue;
private Component glue2;
private JButton addFieldButton;
private JToggleButton[][] buttons;
private JPanel fieldListPanel;
private ArrayList<JTextField> triggerNames;
private ArrayList<JTextField> triggerPriorities;
private ArrayList<JTextField> triggerConditions;
private ArrayList<JTextField> triggerResults;
private ArrayList<JButton> triggerDeleteButtons;
private ArrayList<JPanel> triggerSubPanels;
private JButton addTriggerButton;
private JPanel triggerListPanel;
private HashSet<Integer> removedFields;
private HashSet<Integer> removedTriggers;
public EditEntityScreen(final ScreenManager sm) {
super(sm);
this.setLayout(new BorderLayout());
JLabel label = new JLabel("Edit Entities");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setHorizontalTextPosition(SwingConstants.CENTER);
JTabbedPane tabs = new JTabbedPane();
JPanel lowerPanel = new JPanel();
JPanel generalPanel = new JPanel();
JPanel mainPanel = new JPanel();
JPanel iconPanel = new JPanel();
JPanel fieldMainPanel = new JPanel();
JPanel fieldLabelsPanel = new JPanel();
fieldListPanel = new JPanel();
JPanel triggerMainPanel = new JPanel();
JPanel triggerLabelsPanel = new JPanel();
triggerListPanel = new JPanel();
removedFields = new HashSet<Integer>();
removedTriggers = new HashSet<Integer>();
JLabel generalLabel = new JLabel("General Info");
generalLabel.setHorizontalAlignment(SwingConstants.CENTER);
generalLabel.setPreferredSize(new Dimension(300, 80));
JLabel nameLabel = new JLabel("Name: ");
nameField = new JTextField(25);
nameField.setMaximumSize(new Dimension(400, 40));
colorTool = new JColorChooser();
JPanel colorPanel = new JPanel();
colorPanel.add(colorTool);
colorPanel.setAlignmentX(LEFT_ALIGNMENT);
iconPanel.setLayout(new GridLayout(7, 7));
iconPanel.setMinimumSize(new Dimension(500, 500));
iconPanel.setAlignmentX(RIGHT_ALIGNMENT);
buttons = new JToggleButton[7][7];
//Creates the icon design object.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
buttons[i][j] = new JToggleButton();
buttons[i][j].setOpaque(true);
buttons[i][j].setBackground(Color.WHITE);
buttons[i][j].setActionCommand(i + "" + j);
//When the button is pushed it switches colors.
buttons[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
JToggleButton jb = buttons[Integer.parseInt(str
.charAt(0) + "")][Integer.parseInt(str
.charAt(1) + "")];
if (jb.getBackground().equals(Color.WHITE))
jb.setBackground(Color.BLACK);
else
jb.setBackground(Color.WHITE);
}
});
iconPanel.add(buttons[i][j]);
}
}
JButton loadIconButton = new JButton("Load icon");
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
mainPanel.setMaximumSize(new Dimension(1200, 500));
generalPanel
.setLayout(new BoxLayout(generalPanel, BoxLayout.PAGE_AXIS));
mainPanel.add(colorPanel);
mainPanel.add(iconPanel);
generalPanel.add(generalLabel);
generalPanel.add(nameLabel);
generalPanel.add(nameField);
generalPanel.add(mainPanel);
generalPanel.add(loadIconButton);
JLabel fieldLabel = new JLabel("Field Info");
fieldLabel.setHorizontalAlignment(SwingConstants.CENTER);
fieldLabel.setPreferredSize(new Dimension(300, 100));
JLabel fieldNameLabel = new JLabel("Field Name");
fieldNameLabel.setPreferredSize(new Dimension(200, 30));
JLabel fieldValueLabel = new JLabel("Field Initial Value");
fieldValueLabel.setPreferredSize(new Dimension(400, 30));
JLabel fieldTypeLabel = new JLabel("Field Type");
fieldNameLabel.setPreferredSize(new Dimension(350, 30));
fieldNames = new ArrayList<JTextField>();
fieldValues = new ArrayList<JTextField>();
fieldTypes = new ArrayList<JComboBox>();
fieldDeleteButtons = new ArrayList<JButton>();
fieldSubPanels = new ArrayList<JPanel>();
addFieldButton = new JButton("Add Field");
addFieldButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addField();
}
});
glue = Box.createVerticalGlue();
addField();
// TODO make sure components line up
fieldMainPanel.setLayout(new BorderLayout());
JPanel fieldBodyPanel = new JPanel();
fieldBodyPanel.setLayout(new BoxLayout(fieldBodyPanel,
BoxLayout.Y_AXIS));
fieldLabelsPanel.setLayout(new BoxLayout(fieldLabelsPanel,
BoxLayout.X_AXIS));
fieldListPanel.setLayout(new BoxLayout(fieldListPanel,
BoxLayout.Y_AXIS));
fieldSubPanels.get(0).setLayout(
new BoxLayout(fieldSubPanels.get(0), BoxLayout.X_AXIS));
fieldMainPanel.add(fieldLabel, BorderLayout.NORTH);
fieldLabelsPanel.add(Box.createHorizontalGlue());
fieldLabelsPanel.add(fieldNameLabel);
fieldNameLabel.setHorizontalAlignment(SwingConstants.LEFT);
fieldNameLabel.setAlignmentX(LEFT_ALIGNMENT);
fieldLabelsPanel.add(fieldTypeLabel);
fieldTypeLabel.setHorizontalAlignment(SwingConstants.LEFT);
fieldLabelsPanel.add(fieldValueLabel);
fieldLabelsPanel.add(Box.createHorizontalGlue());
fieldValueLabel.setHorizontalAlignment(SwingConstants.CENTER);
fieldSubPanels.get(0).add(fieldNames.get(0));
fieldSubPanels.get(0).add(fieldTypes.get(0));
fieldSubPanels.get(0).add(fieldValues.get(0));
fieldSubPanels.get(0).add(fieldDeleteButtons.get(0));
fieldListPanel.add(fieldSubPanels.get(0));
fieldListPanel.add(addFieldButton);
fieldListPanel.add(glue);
// fieldSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT);
fieldBodyPanel.add(fieldLabelsPanel);
fieldBodyPanel.add(fieldListPanel);
fieldMainPanel.add(fieldBodyPanel, BorderLayout.CENTER);
JLabel triggerLabel = new JLabel("Trigger Info");
triggerLabel.setHorizontalAlignment(SwingConstants.CENTER);
triggerLabel.setPreferredSize(new Dimension(300, 100));
JLabel triggerNameLabel = new JLabel("Trigger Name");
triggerNameLabel.setPreferredSize(new Dimension(130, 30));
JLabel triggerPriorityLabel = new JLabel("Trigger Priority");
triggerPriorityLabel.setPreferredSize(new Dimension(180, 30));
JLabel triggerConditionLabel = new JLabel("Trigger Condition");
triggerConditionLabel.setPreferredSize(new Dimension(300, 30));
JLabel triggerResultLabel = new JLabel("Trigger Result");
triggerResultLabel.setPreferredSize(new Dimension(300, 30));
triggerNames = new ArrayList<JTextField>();
triggerPriorities = new ArrayList<JTextField>();
triggerConditions = new ArrayList<JTextField>();
triggerResults = new ArrayList<JTextField>();
triggerDeleteButtons = new ArrayList<JButton>();
triggerSubPanels = new ArrayList<JPanel>();
addTriggerButton = new JButton("Add Trigger");
addTriggerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTrigger();
}
});
glue2 = Box.createVerticalGlue();
addTrigger();
// TODO make sure components line up
triggerMainPanel.setLayout(new BorderLayout());
JPanel triggerBodyPanel = new JPanel();
triggerBodyPanel.setLayout(new BoxLayout(triggerBodyPanel,
BoxLayout.Y_AXIS));
triggerLabelsPanel.setLayout(new BoxLayout(triggerLabelsPanel,
BoxLayout.X_AXIS));
triggerListPanel.setLayout(new BoxLayout(triggerListPanel,
BoxLayout.Y_AXIS));
triggerSubPanels.get(0).setLayout(
new BoxLayout(triggerSubPanels.get(0), BoxLayout.X_AXIS));
triggerMainPanel.add(triggerLabel, BorderLayout.NORTH);
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerLabelsPanel.add(triggerNameLabel);
triggerNameLabel.setHorizontalAlignment(SwingConstants.LEFT);
triggerLabelsPanel.add(triggerPriorityLabel);
triggerLabelsPanel.add(triggerConditionLabel);
triggerLabelsPanel.add(triggerResultLabel);
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerSubPanels.get(0).add(triggerNames.get(0));
triggerSubPanels.get(0).add(triggerPriorities.get(0));
triggerSubPanels.get(0).add(triggerConditions.get(0));
triggerSubPanels.get(0).add(triggerResults.get(0));
triggerSubPanels.get(0).add(triggerDeleteButtons.get(0));
triggerListPanel.add(triggerSubPanels.get(0));
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(glue2);
triggerBodyPanel.add(triggerLabelsPanel);
triggerLabelsPanel.setAlignmentX(CENTER_ALIGNMENT);
triggerBodyPanel.add(triggerListPanel);
triggerSubPanels.get(0).setAlignmentX(CENTER_ALIGNMENT);
// triggerSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT);
triggerMainPanel.add(triggerBodyPanel, BorderLayout.CENTER);
tabs.addTab("General", generalPanel);
tabs.addTab("Fields", fieldMainPanel);
tabs.addTab("Triggers", triggerMainPanel);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sm.update(sm.getScreen("Edit Simulation"));
reset();
}
});
JButton finishButton = new JButton("Finish");
finishButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (sendInfo()) {
sm.update(sm.getScreen("Edit Simulation"));
reset();
}
}
});
lowerPanel.add(cancelButton);
lowerPanel.add(finishButton);
this.add(label, BorderLayout.NORTH);
this.add(tabs, BorderLayout.CENTER);
this.add(lowerPanel, BorderLayout.SOUTH);
}
public void load(String str) {
reset();
agent = sm.getFacade().getPrototype(str);
nameField.setText(agent.getName());
colorTool.setColor(agent.getColor());
byte[] designBytes = agent.getDesign();
for (byte b : designBytes)
System.out.println("lB:" + b);
byte byter = Byte.parseByte("0000001", 2);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if ((designBytes[i] & (byter << j)) != Byte.parseByte("0000000", 2)) {
buttons[i][6-j].doClick();
}
}
}
Map<String, String> fields = agent.getFieldMap();
int i = 0;
for (String s : fields.keySet()) {
addField();
fieldNames.get(i).setText(s);
fieldValues.get(i).setText(s);
i++;
}
List<Trigger> triggers = agent.getTriggers();
int j = 0;
for (Trigger t : triggers) {
addTrigger();
triggerNames.get(j).setText(t.getName());
triggerConditions.get(j).setText(t.getConditions().toString());
triggerResults.get(j).setText(t.getBehavior().toString());
triggerPriorities.get(j).setText(t.getPriority() +"");
}
}
public void reset() {
agent = null;
nameField.setText("");
colorTool.setColor(Color.WHITE);
for (int x = 0; x < 7; x++) {
for (int y = 0; y < 7; y++) {
buttons[x][y].setSelected(false);
buttons[x][y].setBackground(Color.WHITE);
}
}
fieldNames.clear();
fieldTypes.clear();
fieldValues.clear();
fieldDeleteButtons.clear();
fieldSubPanels.clear();
removedFields.clear();
fieldListPanel.removeAll();
fieldListPanel.add(addFieldButton);
triggerNames.clear();
triggerPriorities.clear();
triggerConditions.clear();
triggerResults.clear();
triggerDeleteButtons.clear();
triggerSubPanels.clear();
removedTriggers.clear();
triggerListPanel.removeAll();
triggerListPanel.add(addTriggerButton);
}
public boolean sendInfo() {
boolean toReturn = false;
try {
for (int i = 0; i < fieldNames.size(); i++) {
if (removedFields.contains(i)) {
if (fieldNames.get(i).getText().equals("")
|| fieldValues.get(i).getText().equals("")) {
throw new Exception("All fields must have input");
}
}
}
for (int j = 0; j < triggerNames.size(); j++) {
if (removedTriggers.contains(j)) {
if (triggerNames.get(j).getText().equals("")
|| triggerConditions.get(j).getText().equals("")
|| triggerResults.get(j).getText().equals("")) {
throw new Exception("All fields must have input");
}
}
if (Integer.parseInt(triggerPriorities.get(j).getText()) < 0) {
throw new Exception("Priority must be greater than 0");
}
}
if (!editing) {
sm.getFacade().createPrototype(nameField.getText(),
sm.getFacade().getGrid(), colorTool.getColor(),
generateBytes());
agent = sm.getFacade().getPrototype(nameField.getText());
}
else {
agent.setPrototypeName(agent.getName(),
nameField.getText());
agent.setColor(colorTool.getColor());
agent.setDesign(generateBytes());
Prototype.addPrototype(agent.getName(), agent);
}
for (int i = 0; i < fieldNames.size(); i++) {
if (removedFields.contains(i)) {
if (agent.hasField(fieldNames.get(i).getText()))
agent.removeField(fieldNames.get(i));
} else {
if (agent.hasField(fieldNames.get(i).getText())) {
agent.updateField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} else
try {
agent.addField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} catch (ElementAlreadyContainedException e) {
e.printStackTrace();
}
}
}
for (int i = 0; i < triggerNames.size(); i++) {
if (removedTriggers.contains(i)) {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.removeTrigger(triggerNames.get(i).getText());
} else {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.updateTrigger(triggerNames.get(i).getText(),
generateTrigger(i));
else
agent.addTrigger(generateTrigger(i));
}
}
for (int i = 0; i < triggerNames.size(); i++) {
if (removedTriggers.contains(i)) {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.removeTrigger(triggerNames.get(i).getText());
} else {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.updateTrigger(triggerNames.get(i).getText(),
generateTrigger(i));
else
agent.addTrigger(generateTrigger(i));
}
}
toReturn = true;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Priorities field must be an integer greater than 0.");
e.printStackTrace();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
} finally {
return toReturn;
}
}
public void setEditing(Boolean b) {
editing = b;
}
private void addField() {
JPanel newPanel = new JPanel();
newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
JTextField newName = new JTextField(25);
newName.setMaximumSize(new Dimension(300, 40));
fieldNames.add(newName);
JComboBox newType = new JComboBox(typeNames);
newType.setMaximumSize(new Dimension(200, 40));
fieldTypes.add(newType);
JTextField newValue = new JTextField(25);
newValue.setMaximumSize(new Dimension(300, 40));
fieldValues.add(newValue);
JButton newButton = new JButton("Delete");
newButton.addActionListener(new DeleteFieldListener());
fieldDeleteButtons.add(newButton);
newButton.setActionCommand(fieldDeleteButtons.indexOf(newButton) + "");
newPanel.add(newName);
newPanel.add(newType);
newPanel.add(newValue);
newPanel.add(newButton);
fieldSubPanels.add(newPanel);
fieldListPanel.add(newPanel);
fieldListPanel.add(addFieldButton);
fieldListPanel.add(glue);
repaint();
}
private void addTrigger() {
JPanel newPanel = new JPanel();
newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
JTextField newName = new JTextField(25);
newName.setMaximumSize(new Dimension(200, 40));
triggerNames.add(newName);
JTextField newPriority = new JTextField(15);
newPriority.setMaximumSize(new Dimension(150, 40));
triggerPriorities.add(newPriority);
JTextField newCondition = new JTextField(50);
newCondition.setMaximumSize(new Dimension(300, 40));
triggerConditions.add(newCondition);
JTextField newResult = new JTextField(50);
newResult.setMaximumSize(new Dimension(300, 40));
triggerResults.add(newResult);
JButton newButton = new JButton("Delete");
newButton.addActionListener(new DeleteTriggerListener());
triggerDeleteButtons.add(newButton);
newButton.setActionCommand(triggerDeleteButtons.indexOf(newButton)
+ "");
newPanel.add(newName);
newPanel.add(newPriority);
newPanel.add(newCondition);
newPanel.add(newResult);
newPanel.add(newButton);
triggerSubPanels.add(newPanel);
triggerListPanel.add(newPanel);
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(glue2);
repaint();
}
private byte[] generateBytes() {
String str = "";
byte[] toReturn = new byte[7];
for (int column = 0; column < 7; column++) {
for (int row = 0; row < 7; row++) {
if (buttons[column][row].getBackground().equals(Color.BLACK)) {
System.out.print("1");
str += "1";
} else {
System.out.print("0");
str += "0";
}
}
str += ":";
System.out.print(":");
}
str = str.substring(0, str.lastIndexOf(':'));
String[] byteStr = str.split(":");
System.out.println("BOO: " + str);
for (String s : byteStr)
System.out.println("genB:" +s);
for (int i = 0; i < 7; i++) {
toReturn[i] = Byte.parseByte(byteStr[i], 2);
}
return toReturn;
}
private Trigger generateTrigger(int i) {
return new Trigger(triggerNames.get(i).getText(),
Integer.parseInt(triggerPriorities.get(i).getText()),
new Expression(triggerConditions.get(i).getText()),
new Expression(triggerResults.get(i).getText()));
}
private class DeleteFieldListener implements ActionListener {
private String action;
@Override
public void actionPerformed(ActionEvent e) {
removedFields.add(Integer.parseInt(e.getActionCommand()));
fieldListPanel.remove(fieldSubPanels.get(Integer.parseInt(e
.getActionCommand())));
repaint();
}
}
private class DeleteTriggerListener implements ActionListener {
private String action;
@Override
public void actionPerformed(ActionEvent e) {
removedTriggers.add(Integer.parseInt(e.getActionCommand()));
triggerListPanel.remove(triggerSubPanels.get(Integer.parseInt(e
.getActionCommand())));
repaint();
}
}
@Override
public void load() {
reset();
addField();
addTrigger();
}
} |
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
* @author Enforers
*/
public class Compressor implements Component{
Relay compressor = new Relay(4, Relay.Direction.kForward);
DigitalInput cutoff = new DigitalInput(6);
AnalogChannel analogPressure = new AnalogChannel(3);
double pressure;
public void tickTeleop() {
compressor.set(cutoff.get()?Relay.Value.kOff:Relay.Value.kForward);
SmartDashboard.putNumber("Pressure", pressure);
SmartDashboard.putBoolean("PSI to Shoot?", pressure >= 50);
}
public void tickAuto() {
compressor.set(cutoff.get()?Relay.Value.kOff:Relay.Value.kForward);
}
} |
package com.axelor.db;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Construct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeId;
import org.yaml.snakeyaml.nodes.Tag;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Injector;
import com.google.inject.persist.Transactional;
/**
* This class can be used to load test data for JPA entities.
*
* <p>
* It processes YAML files located in {@code META-INF/fixtures}. A fixture
* consists of two files with {@code .resolver.yml} and {@code .data.yml}
* suffixes.
*
* <p>
* The resolver file defiles short names for fully qualified entity name to use
* in the data file.
*
* <p>
* For example, the following schema:
*
* <pre>
*
* @Entity
* @Table(name = "PERSON_GROUP")
* public class Group extends Model {
* private String name;
* private String title;
* ...
* ...
* }
*
* @Entity
* public class Person extends Model {
* private String name;
* private String age;
* private String lang;
*
* @ManyToMany
* private List<Group> groups;
* ...
* ...
* ...
* </pre>
*
* The fixtures should be defined like this:
*
* 1. demo.resolver.yml
*
* <pre>
* Group: com.axelor.contact.db.Group
* Person: com.axelor.contact.db.Person
* </pre>
*
* 2. demo.data.yml
*
* <pre>
* - !Group: &family
* name: family
* title: Family
*
* - !Group: &friends
* name: friends
* title: Friends
*
* - !Group: &business
* name: business
* title: Business
*
* - !Person:
* name: Some
* age: 27
* lang: en
* groups:
* - *family
*
* - !Person:
* name: One
* age: 23
* lang: fr
* groups:
* - *friends
* - *business
*
* - !Person:
* name: Else
* age: 31
* lang: hi
* groups:
* - *business
* </pre>
*
* <p>
* In order to use the fixture data, you should inject Guice {@link Injector}
* object before using the {@link Fixture} instance.
*
* <pre>
* @RunWith(GuiceRunner.class)
* @GuiceModules({MyModule.class})
* class FixtureTest {
*
* @Inject
* Fixture fixture;
*
* @Inject
* Manager<Person> mp;
*
* @Inject
* Manager<Group> mg;
*
* @Before
* public void setUp() {
* fixture.load("data");
* fixture.load("some_other_fixture");
* }
*
* @Test
* public void testCount() {
* Assert.assertEqual(3, mg.all().count());
* ...
* }
* ...
* }
* </pre>
*/
public class Fixture {
private InputStream read(String resource) {
return Thread.currentThread().getContextClassLoader()
.getResourceAsStream(("META-INF/fixtures/" + resource));
}
@SuppressWarnings("unchecked")
@Transactional
public void load(String fixture) {
Yaml yaml = new Yaml();
InputStream is = read(fixture + ".resolver.yml");
InputStream ds = read(fixture + ".data.yml");
if (is == null || ds == null) {
throw new IllegalArgumentException("No such fixture: " + fixture
+ ".yml");
}
final Map<String, String> classes = (Map<String, String>) yaml.load(is);
final Map<Node, Object> objects = Maps.newLinkedHashMap();
Constructor ctor = new Constructor() {
{
yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct());
}
class TimeStampConstruct extends Constructor.ConstructScalar {
Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP);
@Override
public Object construct(Node nnode) {
if (nnode.getTag().equals(Tag.TIMESTAMP)) {
Date date = (Date) dateConstructor.construct(nnode);
if (nnode.getType() == LocalDate.class) {
return new LocalDate(date, DateTimeZone.UTC);
}
if (nnode.getType() == LocalDateTime.class) {
return new LocalDateTime(date, DateTimeZone.UTC);
}
return new DateTime(date, DateTimeZone.UTC);
} else {
return super.construct(nnode);
}
}
}
@Override
protected Object constructObject(Node node) {
Object obj = super.constructObject(node);
if (objects.containsKey(node)) {
return objects.get(node);
}
if (obj instanceof Model) {
objects.put(node, obj);
return obj;
}
return obj;
}
};
for (String key : classes.keySet()) {
try {
Class<?> klass = Class.forName(classes.get(key));
ctor.addTypeDescription(new TypeDescription(klass, "!" + key
+ ":"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(String.format(
"Invalid fixture resolver '%s': %s: %s", fixture, key,
classes.get(key)));
}
}
Yaml data = new Yaml(ctor);
data.load(ds);
for(Object item : Lists.reverse(Lists.newArrayList(objects.values()))) {
try {
JPA.manage((Model) item);
}catch(Exception e) {
}
}
}
} |
package eg.utils;
/**
* Static methods to search for elements in text
*/
public class LinesFinder {
/**
* Returns the line which includes the specified position
*
* @param text the text
* @param pos the pos that is in the searched line
* @return the line that includes '{@code pos}'
*/
public static String lineAtPos(String text, int pos) {
int lastNewline = LinesFinder.lastNewline(text, pos);
int nextNewline = LinesFinder.nextNewline(text, pos);
if (lastNewline != -1) {
return text.substring(lastNewline + 1, nextNewline);
}
else {
return text.substring(0, nextNewline);
}
}
/**
* Returns the full lines of text which include the specified section
*
* @param text the text
* @param section a section of the text
* @param pos the position where <code>section</code> starts
* @return the full lines of text which include <code>section</code>
*/
public static String allLinesAtPos(String text, String section, int pos) {
String lines;
String[] sectionArr = section.split("\n");
String firstLine = LinesFinder.lineAtPos(text, pos);
if (sectionArr.length > 0 && sectionArr.length > 1) {
sectionArr[0] = firstLine;
String lastLine = LinesFinder.lineAtPos(text, pos + section.length());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sectionArr.length - 1; i++) {
sb.append(sectionArr[i]);
sb.append("\n");
}
sb.append(lastLine);
lines = sb.toString();
}
else {
lines = firstLine;
}
return lines;
}
/**
* Returns the position of the last newline before the specified
* position
*
* @param text the text
* @param pos the position relative to which the last newline
* is searched
* @return the position of the last newline character before '{@code pos}'
*/
public static int lastNewline(String text, int pos) {
int i = text.lastIndexOf("\n", pos);
if (i == pos) {
i = text.lastIndexOf("\n", pos - 1);
}
return i;
}
/**
* Returns the position of the next newline after the specified
* position
*
* @param text the text
* @param pos the position relative to which the next newline
* is searched
* @return the position of the next newline character
*/
public static int nextNewline(String text, int pos) {
int i = text.indexOf("\n", pos);
if (i == -1) {
i = text.length();
}
return i;
}
/**
* Returns the number of the line where the specified
* position is located
*
* @param text the text
* @param pos the position in the text
* @return the number of the line where the specified
* position is located
*/
public static int lineNrAtPos(String text, int pos) {
int count = 0;
int i = 0;
while (i != -1) {
i = text.indexOf("\n", i);
if (i != -1) {
if (i >= pos) {
break;
}
count++;
i++;
}
}
return count + 1;
}
} |
package eu.ydp.empiria.player.client.util;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.Window;
public class PathUtil {
public static String resolvePath(String path, String base){
if (path.contains("://") || path.startsWith("/")){
return path;
} else {
return base + path;
}
}
private static String playerPathDir;
public static String getPlayerPathDir(){
if (playerPathDir != null)
return playerPathDir;
playerPathDir = findPlayerPathDir();
return playerPathDir;
}
private static String findPlayerPathDir(){
NodeList<Element> scriptNodes = Document.get().getElementsByTagName("script");
String empiriaPlayerFileName = "/empiria.player.nocache.js";
for (int s = 0 ; s < scriptNodes.getLength() ; s ++){
if (((Element)scriptNodes.getItem(s)).hasAttribute("src")){
String src = ((Element)scriptNodes.getItem(s)).getAttribute("src");
if (src.endsWith(empiriaPlayerFileName)){
return src.substring(0, src.indexOf(empiriaPlayerFileName) +1);
}
}
}
return "";
}
public static String normalizePath(String path){
while (path.matches(".*\\\\[^\\\\]*\\\\[.]{2}.*")){
path = path.replaceAll("\\\\[^\\\\]*\\\\[.]{2}", "");
}
while (path.matches(".*/[^/]*/[.]{2}.*")){
path = path.replaceAll("/[^/]*/[.]{2}", "");
}
return path;
}
} |
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.config;
import java.beans.PropertyEditorSupport;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.log4j.Category;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.MatchTable;
import org.opennms.core.utils.PropertiesUtils;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.ConfigFileConstants;
import org.opennms.netmgt.config.translator.Assignment;
import org.opennms.netmgt.config.translator.EventTranslationSpec;
import org.opennms.netmgt.config.translator.EventTranslatorConfiguration;
import org.opennms.netmgt.config.translator.Mapping;
import org.opennms.netmgt.config.translator.Translation;
import org.opennms.netmgt.config.translator.Value;
import org.opennms.netmgt.eventd.EventUtil;
import org.opennms.netmgt.utils.SingleResultQuerier;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.netmgt.xml.event.Parms;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.FatalBeanException;
public final class EventTranslatorConfigFactory implements EventTranslatorConfig {
/**
* The singleton instance of this factory
*/
private static EventTranslatorConfig m_singleton = null;
/**
* The config class loaded from the config file
*/
private EventTranslatorConfiguration m_config;
private List m_translationSpecs;
/**
* This member is set to true if the configuration file has been loaded.
*/
private static boolean m_loaded = false;
/**
* connection factory for use with sql-value
*/
private DataSource m_dbConnFactory;
/**
* Private constructor
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
*
*/
private EventTranslatorConfigFactory(String configFile, DataSource dbConnFactory) throws IOException, MarshalException, ValidationException {
Reader rdr = new InputStreamReader(new FileInputStream(configFile));
marshallReader(rdr, dbConnFactory);
rdr.close();
}
public EventTranslatorConfigFactory(Reader rdr, DataSource dbConnFactory) throws MarshalException, ValidationException {
marshallReader(rdr, dbConnFactory);
}
private synchronized void marshallReader(Reader rdr, DataSource dbConnFactory) throws MarshalException, ValidationException {
m_config = (EventTranslatorConfiguration) Unmarshaller.unmarshal(EventTranslatorConfiguration.class, rdr);
m_dbConnFactory = dbConnFactory;
}
/**
* Load the config from the default config file and create the singleton
* instance of this factory.
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws ClassNotFoundException
*/
public static synchronized void init() throws IOException, MarshalException, ValidationException, ClassNotFoundException, SQLException, PropertyVetoException {
if (m_loaded) {
// init already called - return
// to reload, reload() will need to be called
return;
}
DataSourceFactory.init();
File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.TRANSLATOR_CONFIG_FILE_NAME);
m_singleton = new EventTranslatorConfigFactory(cfgFile.getPath(), DataSourceFactory.getInstance());
m_loaded = true;
}
/**
* Reload the config from the default config file
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read/loaded
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws ClassNotFoundException
*/
public static synchronized void reload() throws IOException, MarshalException, ValidationException, ClassNotFoundException, SQLException, PropertyVetoException {
m_singleton = null;
m_loaded = false;
init();
}
public static synchronized EventTranslatorConfig getInstance() {
if (!m_loaded)
throw new IllegalStateException("getInstance: The factory has not been initialized");
return m_singleton;
}
public static void setInstance(EventTranslatorConfig singleton) {
m_singleton=singleton;
m_loaded=true;
}
private Category log() {
return ThreadCategory.getInstance(EventTranslatorConfig.class);
}
/**
* Return the PassiveStatus configuration.
*
* @return the PassiveStatus configuration
*/
private synchronized EventTranslatorConfiguration getConfig() {
return m_config;
}
/*
* (non-Javadoc)
* @see org.opennms.netmgt.config.PassiveStatusConfig#getUEIList()
*/
public List getUEIList() {
return getTranslationUEIs();
}
private List getTranslationUEIs() {
Translation translation = getConfig().getTranslation();
if (translation == null)
return Collections.EMPTY_LIST;
List translatedEvents = translation.getEventTranslationSpecCollection();
List ueis = new ArrayList();
for (Iterator it = translatedEvents.iterator(); it.hasNext();) {
EventTranslationSpec event = (EventTranslationSpec) it.next();
ueis.add(event.getUei());
}
return ueis;
}
static class TranslationFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
TranslationFailedException(String msg) {
super(msg);
}
}
public boolean isTranslationEvent(Event e) {
List specs = getTranslationSpecs();
for (Iterator it = specs.iterator(); it.hasNext();) {
TranslationSpec spec = (TranslationSpec) it.next();
if (spec.matches(e))
return true;
}
return false;
}
public List translateEvent(Event e) {
ArrayList events = new ArrayList();
for (Iterator it = getTranslationSpecs().iterator(); it.hasNext();) {
TranslationSpec spec = (TranslationSpec) it.next();
events.addAll(spec.translate(e));
}
return events;
}
private List getTranslationSpecs() {
if (m_translationSpecs == null)
m_translationSpecs = constructTranslationSpecs();
return m_translationSpecs;
}
private List constructTranslationSpecs() {
List specs = new ArrayList();
for (Iterator it = m_config.getTranslation().getEventTranslationSpecCollection().iterator(); it.hasNext();) {
EventTranslationSpec eventTrans = (EventTranslationSpec) it.next();
specs.add(new TranslationSpec(eventTrans));
}
return specs;
}
class TranslationSpec {
private EventTranslationSpec m_spec;
private List m_translationMappings;
TranslationSpec(EventTranslationSpec spec) {
m_spec = spec;
m_translationMappings = null; // lazy init
}
public List translate(Event e) {
// short circuit here is the uei doesn't match
if (!ueiMatches(e)) return Collections.EMPTY_LIST;
// uei matches now go thru the mappings
ArrayList events = new ArrayList();
for (Iterator it = getTranslationMappings().iterator(); it.hasNext();) {
TranslationMapping mapping = (TranslationMapping) it.next();
Event translatedEvent = mapping.translate(e);
if (translatedEvent != null)
events.add(translatedEvent);
}
return events;
}
String getUei() { return m_spec.getUei(); }
public EventTranslationSpec getEventTranslationSpec() {
return m_spec;
}
private List constructTranslationMappings() {
if (m_spec.getMappings() == null) return Collections.EMPTY_LIST;
List mappings = m_spec.getMappings().getMappingCollection();
List transMaps = new ArrayList(mappings.size());
for (Iterator it = mappings.iterator(); it.hasNext();) {
Mapping mapping = (Mapping) it.next();
TranslationMapping transMap = new TranslationMapping(mapping);
transMaps.add(transMap);
}
return transMaps;
}
List getTranslationMappings() {
if (m_translationMappings == null)
m_translationMappings = constructTranslationMappings();
return m_translationMappings;
}
boolean matches(Event e) {
// short circuit if the eui doesn't match
if (!ueiMatches(e)) {
log().debug("TransSpec.matches: No match comparing spec UEI: "+m_spec.getUei()+" with event UEI: "+e.getUei());
return false;
}
// uei matches to go thru the mappings
log().debug("TransSpec.matches: checking mappings for spec.");
List transMaps = getTranslationMappings();
for (Iterator it = transMaps.iterator(); it.hasNext();) {
TranslationMapping transMap = (TranslationMapping) it.next();
if (transMap.matches(e))
return true;
}
return false;
}
private boolean ueiMatches(Event e) {
return e.getUei().equals(m_spec.getUei())
|| m_spec.getUei().endsWith("/")
&& e.getUei().startsWith(m_spec.getUei());
}
}
class TranslationMapping {
Mapping m_mapping;
List m_assignments;
TranslationMapping(Mapping mapping) {
m_mapping = mapping;
m_assignments = null; // lazy init
}
public Event translate(Event srcEvent) {
// if the event doesn't match the mapping then don't apply the translation
if (!matches(srcEvent)) return null;
Event targetEvent = cloneEvent(srcEvent);
for (Iterator it = getAssignmentSpecs().iterator(); it.hasNext();) {
AssignmentSpec assignSpec = (AssignmentSpec) it.next();
assignSpec.apply(srcEvent, targetEvent);
}
targetEvent.setSource(TRANSLATOR_NAME);
return targetEvent;
}
private Event cloneEvent(Event srcEvent) {
Event clonedEvent = EventUtil.cloneEvent(srcEvent);
/* since alarmData and severity are computed based on translated information in
* eventd using the data from eventconf, we unset it here to eventd
* can reset to the proper new settings.
*/
clonedEvent.setAlarmData(null);
clonedEvent.setSeverity(null);
return clonedEvent;
}
public Mapping getMapping() {
return m_mapping;
}
private List getAssignmentSpecs() {
if (m_assignments == null)
m_assignments = constructAssignmentSpecs();
return m_assignments;
}
private List constructAssignmentSpecs() {
Mapping mapping = getMapping();
List assignments = new ArrayList();
for (Iterator iter = mapping.getAssignmentCollection().iterator(); iter.hasNext();) {
Assignment assign = (Assignment) iter.next();
AssignmentSpec assignSpec =
("parameter".equals(assign.getType()) ?
(AssignmentSpec)new ParameterAssignmentSpec(assign) :
(AssignmentSpec)new FieldAssignmentSpec(assign)
);
assignments.add(assignSpec);
}
return assignments;
}
private boolean assignmentsMatch(Event e) {
AssignmentSpec assignSpec = null;
for (Iterator it = getAssignmentSpecs().iterator(); it.hasNext();) {
assignSpec = (AssignmentSpec) it.next();
if (!assignSpec.matches(e)) {
log().debug("TranslationMapping.assignmentsMatch: assignmentSpec: "+assignSpec.getAttributeName()+" doesn't match.");
return false;
}
}
log().debug("TranslationMapping.assignmentsMatch: assignmentSpec: "+assignSpec.getAttributeName()+" matches!");
return true;
}
boolean matches(Event e) {
return assignmentsMatch(e);
}
}
abstract class AssignmentSpec {
private Assignment m_assignment;
private ValueSpec m_valueSpec;
AssignmentSpec(Assignment assignment) {
m_assignment = assignment;
m_valueSpec = null; // lazy init
}
public void apply(Event srcEvent, Event targetEvent) {
setValue(targetEvent, getValueSpec().getResult(srcEvent));
}
private Assignment getAssignment() { return m_assignment; }
protected String getAttributeName() { return getAssignment().getName(); }
private ValueSpec constructValueSpec() {
Value val = getAssignment().getValue();
return EventTranslatorConfigFactory.this.getValueSpec(val);
}
protected abstract void setValue(Event targetEvent, String value);
private ValueSpec getValueSpec() {
if (m_valueSpec == null)
m_valueSpec = constructValueSpec();
return m_valueSpec;
}
boolean matches(Event e) {
return getValueSpec().matches(e);
}
}
class FieldAssignmentSpec extends AssignmentSpec {
FieldAssignmentSpec(Assignment field) { super(field); }
protected void setValue(Event targetEvent, String value) {
try {
BeanWrapperImpl bean = new BeanWrapperImpl(targetEvent);
bean.setPropertyValue(getAttributeName(), value);
} catch(FatalBeanException e) {
log().error("Unable to set value for attribute "+getAttributeName()+"to value "+value+
" Exception:" +e);
throw new TranslationFailedException("Unable to set value for attribute "+getAttributeName()+" to value "+value);
}
}
}
class ParameterAssignmentSpec extends AssignmentSpec {
ParameterAssignmentSpec(Assignment assign) {
super(assign);
}
protected void setValue(Event targetEvent, String value) {
Parms parms = targetEvent.getParms();
if (parms == null) {
parms = new Parms();
targetEvent.setParms(parms);
}
for (Iterator it = parms.getParmCollection().iterator(); it.hasNext();) {
Parm parm = (Parm) it.next();
if (parm.getParmName().equals(getAttributeName())) {
org.opennms.netmgt.xml.event.Value val = parm.getValue();
if (val == null) {
val = new org.opennms.netmgt.xml.event.Value();
parm.setValue(val);
}
log().debug("Overriding value of parameter "+getAttributeName()+". Setting it to "+value);
val.setContent(value);
return;
}
}
// if we got here then we didn't find the existing parm
Parm newParm = new Parm();
parms.addParm(newParm);
newParm.setParmName(getAttributeName());
org.opennms.netmgt.xml.event.Value val = new org.opennms.netmgt.xml.event.Value();
newParm.setValue(val);
log().debug("Setting value of parameter "+getAttributeName()+" to "+value);
val.setContent(value);
}
}
ValueSpec getValueSpec(Value val) {
if ("field".equals(val.getType()))
return new FieldValueSpec(val);
else if ("parameter".equals(val.getType()))
return new ParameterValueSpec(val);
else if ("constant".equals(val.getType()))
return new ConstantValueSpec(val);
else if ("sql".equals(val.getType()))
return new SqlValueSpec(val);
else
return new ValueSpecUnspecified();
}
abstract class ValueSpec {
public abstract boolean matches(Event e);
public abstract String getResult(Event srcEvent);
}
class ConstantValueSpec extends ValueSpec {
Value m_constant;
public ConstantValueSpec(Value constant) {
m_constant = constant;
}
public boolean matches(Event e) {
if (m_constant.getMatches() != null) {
log().warn("ConstantValueSpec.matches: matches not allowed for constant value.");
throw new IllegalStateException("Illegal to use matches with constant type values");
}
return true;
}
public String getResult(Event srcEvent) {
return m_constant.getResult();
}
}
class ValueSpecUnspecified extends ValueSpec {
public boolean matches(Event e) {
// TODO: this should probably throw an exception since it makes no sense
return true;
}
public String getResult(Event srcEvent) {
return "value unspecified";
}
}
class SqlValueSpec extends ValueSpec {
Value m_val;
List m_nestedValues;
public SqlValueSpec(Value val) {
m_val = val;
m_nestedValues = null; // lazy init
}
public List getNestedValues() {
if (m_nestedValues == null)
m_nestedValues = constructNestedValues();
return m_nestedValues;
}
private List constructNestedValues() {
List nestedValues = new ArrayList();
for (Iterator it = m_val.getValueCollection().iterator(); it.hasNext();) {
Value val = (Value) it.next();
nestedValues.add(EventTranslatorConfigFactory.this.getValueSpec(val));
}
return nestedValues;
}
public boolean matches(Event e) {
for (Iterator it = getNestedValues().iterator(); it.hasNext();) {
ValueSpec nestedVal = (ValueSpec) it.next();
if (!nestedVal.matches(e))
return false;
}
return true;
}
public String getResult(Event srcEvent) {
SingleResultQuerier querier = new SingleResultQuerier(m_dbConnFactory, m_val.getResult());
Object[] args = new Object[getNestedValues().size()];
for (int i = 0; i < args.length; i++) {
args[i] = ((ValueSpec)getNestedValues().get(i)).getResult(srcEvent);
}
querier.execute(args);
if (querier.getCount() < 1) {
log().warn("No results found for query "+querier.reproduceStatement(args)+". Returning null");
return null;
}
else
return querier.getResult().toString();
}
}
abstract class AttributeValueSpec extends ValueSpec {
Value m_val;
AttributeValueSpec(Value val) { m_val = val; }
public boolean matches(Event e) {
String attributeValue = getAttributeValue(e);
if (attributeValue == null) {
log().debug("AttributeValueSpec.matches: Event attributeValue doesn't match because attributeValue itself is null");
return false;
}
if (m_val.getMatches() == null) {
log().debug("AttributeValueSpec.matches: Event attributeValue: "+attributeValue+" matches because pattern is null");
return true;
}
Pattern p = Pattern.compile(m_val.getMatches());
Matcher m = p.matcher(attributeValue);
if (m.matches()) {
log().debug("AttributeValueSpec.matches: Event attributeValue: "+attributeValue+" matches pattern: "+m_val.getMatches());
return true;
} else {
log().debug("AttributeValueSpec.matches: Event attributeValue: "+attributeValue+" doesn't match pattern: "+m_val.getMatches());
return false;
}
}
public String getResult(Event srcEvent) {
if (m_val.getMatches() == null) return m_val.getResult();
String attributeValue = getAttributeValue(srcEvent);
if (attributeValue == null) {
throw new TranslationFailedException("failed to match null against '"+m_val.getMatches()+"' for attribute "+getAttributeName());
}
Pattern p = Pattern.compile(m_val.getMatches());
final Matcher m = p.matcher(attributeValue);
if (!m.matches())
throw new TranslationFailedException("failed to match "+attributeValue+" against '"+m_val.getMatches()+"' for attribute "+getAttributeName());
MatchTable matches = new MatchTable(m);
return PropertiesUtils.substitute(m_val.getResult(), matches);
}
public String getAttributeName() { return m_val.getName(); }
abstract public String getAttributeValue(Event e);
}
// XXX: This is here because Spring converting to a String appears
// to be broken. It if probably a Hack and we probably need to have
// a better way to access the Spring property editors and convert
// to a string more correctly.
class StringPropertyEditor extends PropertyEditorSupport {
@Override
public void setValue(Object value) {
if (value == null || value instanceof String)
super.setValue(value);
else
super.setValue(value.toString());
}
@Override
public String getAsText() {
return (String)super.getValue();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
super.setValue(text);
}
}
class FieldValueSpec extends AttributeValueSpec {
public FieldValueSpec(Value val) {
super(val);
}
public String getAttributeValue(Event e) {
try {
BeanWrapperImpl bean = getBeanWrapper(e);
return (String)bean.convertIfNecessary(bean.getPropertyValue(getAttributeName()), String.class);
} catch (FatalBeanException ex) {
log().error("Property "+getAttributeName()+" does not exist on Event", ex);
throw new TranslationFailedException("Property "+getAttributeName()+" does not exist on Event");
}
}
private BeanWrapperImpl getBeanWrapper(Event e) {
BeanWrapperImpl bean = new BeanWrapperImpl(e);
bean.registerCustomEditor(String.class, new StringPropertyEditor());
return bean;
}
}
class ParameterValueSpec extends AttributeValueSpec {
ParameterValueSpec(Value val) { super(val); }
public String getAttributeValue(Event e) {
String attrName = getAttributeName();
Parms parms = e.getParms();
if (parms == null) return null;
for (Iterator it = parms.getParmCollection().iterator(); it.hasNext();) {
Parm parm = (Parm) it.next();
if (parm.getParmName().equals(attrName))
return (parm.getValue() == null ? "" : parm.getValue().getContent());
}
return null;
}
}
} |
package org.caleydo.view.datagraph.bandlayout;
import gleem.linalg.Vec3f;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.media.opengl.GL2;
import org.caleydo.core.data.container.ADimensionGroupData;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.core.view.opengl.camera.ViewFrustum;
import org.caleydo.core.view.opengl.canvas.PixelGLConverter;
import org.caleydo.core.view.opengl.util.spline.ConnectionBandRenderer;
import org.caleydo.view.datagraph.IDataGraphNode;
public class EdgeBandRenderer {
private final static int SPACING_PIXELS = 2;
protected final static int MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS = 20;
protected final static int DEFAULT_MAX_BAND_WIDTH = 30;
protected IDataGraphNode node1;
protected IDataGraphNode node2;
protected PixelGLConverter pixelGLConverter;
protected ViewFrustum viewFrustum;
protected int maxBandWidth = DEFAULT_MAX_BAND_WIDTH;
public EdgeBandRenderer(IDataGraphNode node1, IDataGraphNode node2,
PixelGLConverter pixelGLConverter, ViewFrustum viewFrustum) {
this.node1 = node1;
this.node2 = node2;
this.pixelGLConverter = pixelGLConverter;
this.viewFrustum = viewFrustum;
}
public void renderEdgeBand(GL2 gl, IEdgeRoutingStrategy edgeRoutingStrategy) {
List<ADimensionGroupData> commonDimensionGroupsNode1 = new ArrayList<ADimensionGroupData>();
List<ADimensionGroupData> commonDimensionGroupsNode2 = new ArrayList<ADimensionGroupData>();
for (ADimensionGroupData dimensionGroupData1 : node1
.getDimensionGroups()) {
for (ADimensionGroupData dimensionGroupData2 : node2
.getDimensionGroups()) {
if (dimensionGroupData1.getID() == dimensionGroupData2.getID()) {
commonDimensionGroupsNode1.add(dimensionGroupData1);
commonDimensionGroupsNode2.add(dimensionGroupData2);
}
}
}
ConnectionBandRenderer connectionBandRenderer = new ConnectionBandRenderer();
connectionBandRenderer.init(gl);
if (!commonDimensionGroupsNode1.isEmpty()) {
renderBundledBand(gl, node1, node2, commonDimensionGroupsNode1,
commonDimensionGroupsNode2, edgeRoutingStrategy,
connectionBandRenderer);
} else {
Point2D position1 = node1.getPosition();
Point2D position2 = node2.getPosition();
float deltaX = (float) (position1.getX() - position2.getX());
float deltaY = (float) (position1.getY() - position2.getY());
IDataGraphNode leftNode = null;
IDataGraphNode rightNode = null;
IDataGraphNode bottomNode = null;
IDataGraphNode topNode = null;
if (deltaX < 0) {
if (deltaY < 0) {
leftNode = node1;
rightNode = node2;
bottomNode = node1;
topNode = node2;
} else {
leftNode = node1;
rightNode = node2;
bottomNode = node2;
topNode = node1;
}
} else {
if (deltaY < 0) {
leftNode = node2;
rightNode = node1;
bottomNode = node1;
topNode = node2;
} else {
leftNode = node2;
rightNode = node1;
bottomNode = node2;
topNode = node1;
}
}
float spacingX = (float) ((rightNode.getPosition().getX() - rightNode
.getWidth() / 2.0f) - (leftNode.getPosition().getX() + leftNode
.getWidth() / 2.0f));
float spacingY = (float) ((topNode.getPosition().getY() - topNode
.getHeight() / 2.0f) - (bottomNode.getPosition().getY() + topNode
.getHeight() / 2.0f));
if (spacingX > spacingY) {
renderHorizontalBand(gl, leftNode, rightNode,
edgeRoutingStrategy, connectionBandRenderer);
} else {
renderVerticalBand(gl, bottomNode, topNode,
edgeRoutingStrategy, connectionBandRenderer);
}
}
}
protected void renderBundledBand(GL2 gl, IDataGraphNode node1,
IDataGraphNode node2,
List<ADimensionGroupData> commonDimensionGroupsNode1,
List<ADimensionGroupData> commonDimensionGroupsNode2,
IEdgeRoutingStrategy edgeRoutingStrategy,
ConnectionBandRenderer connectionBandRenderer) {
Point2D bundlingPoint1 = calcBundlingPoint(node1,
commonDimensionGroupsNode1);
Point2D bundlingPoint2 = calcBundlingPoint(node2,
commonDimensionGroupsNode2);
Map<ADimensionGroupData, Integer> bandWidthMap = new HashMap<ADimensionGroupData, Integer>();
int bandWidth = 0;
for (ADimensionGroupData dimensionGroupData : commonDimensionGroupsNode1) {
int width = calcDimensionGroupBandWidthPixels(dimensionGroupData);
bandWidth += width;
bandWidthMap.put(dimensionGroupData, width);
}
for (ADimensionGroupData dimensionGroupData : commonDimensionGroupsNode2) {
int width = calcDimensionGroupBandWidthPixels(dimensionGroupData);
bandWidthMap.put(dimensionGroupData, width);
}
if (bandWidth > maxBandWidth)
bandWidth = maxBandWidth;
// GLHelperFunctions.drawPointAt(gl, (float) bundlingPoint1.getX(),
// (float) bundlingPoint1.getY(), 0);
// GLHelperFunctions.drawPointAt(gl, (float) bundlingPoint2.getX(),
// (float) bundlingPoint2.getY(), 0);
// TODO: calc dimension group data size in comparison to
List<Point2D> edgePoints = new ArrayList<Point2D>();
edgePoints.add(bundlingPoint1);
edgePoints.add(bundlingPoint2);
edgeRoutingStrategy.createEdge(edgePoints);
edgePoints.add(0, new Point2D.Float((float) bundlingPoint1.getX(),
(float) node1.getPosition().getY()));
edgePoints.add(new Point2D.Float((float) bundlingPoint2.getX(),
(float) node2.getPosition().getY()));
List<Vec3f> bandPoints = connectionBandRenderer.calcInterpolatedBand(
gl, edgePoints, bandWidth, pixelGLConverter);
connectionBandRenderer.render(gl, bandPoints);
Point2D bandStartPointAnchorNode1 = new Point2D.Float(bandPoints.get(0)
.x(), bandPoints.get(0).y());
Point2D bandEndPointAnchorNode1 = new Point2D.Float(bandPoints.get(
bandPoints.size() - 1).x(), bandPoints.get(
bandPoints.size() - 1).y());
float vecBandEndX = (float) (bandEndPointAnchorNode1.getX() - bandStartPointAnchorNode1
.getX()) / bandWidth;
float vecBandEndY = (float) (bandEndPointAnchorNode1.getY() - bandStartPointAnchorNode1
.getY()) / bandWidth;
float vecNormalX = vecBandEndY;
float vecNormalY = -vecBandEndX;
Point2D leftBandBundleConnecionPoint = null;
Point2D rightBandBundleConnecionPoint = null;
Point2D leftBundleConnectionPointOffsetAnchor = null;
Point2D rightBundleConnectionPointOffsetAnchor = null;
if (bandStartPointAnchorNode1.getY() > bandEndPointAnchorNode1.getY()) {
leftBandBundleConnecionPoint = bandStartPointAnchorNode1;
rightBandBundleConnecionPoint = new Point2D.Float(
(float) bandStartPointAnchorNode1.getX()
+ pixelGLConverter
.getGLWidthForPixelWidth(bandWidth),
(float) bandStartPointAnchorNode1.getY());
leftBundleConnectionPointOffsetAnchor = leftBandBundleConnecionPoint;
float minY = (float) bandEndPointAnchorNode1.getY() - 0.1f;
float maxY = (float) rightBandBundleConnecionPoint.getY();
rightBundleConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
bandEndPointAnchorNode1, vecNormalX, vecNormalY,
(float) rightBandBundleConnecionPoint.getX(), minY, maxY,
minY, maxY);
} else {
leftBandBundleConnecionPoint = new Point2D.Float(
(float) bandEndPointAnchorNode1.getX()
- pixelGLConverter
.getGLWidthForPixelWidth(bandWidth),
(float) bandEndPointAnchorNode1.getY());
rightBandBundleConnecionPoint = bandEndPointAnchorNode1;
rightBundleConnectionPointOffsetAnchor = rightBandBundleConnecionPoint;
float minY = (float) bandStartPointAnchorNode1.getY() - 0.1f;
float maxY = (float) leftBandBundleConnecionPoint.getY();
leftBundleConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
bandStartPointAnchorNode1, vecNormalX, vecNormalY,
(float) leftBandBundleConnecionPoint.getX(), minY, maxY,
minY, maxY);
}
List<Pair<Point2D, Point2D>> anchorPoints = new ArrayList<Pair<Point2D, Point2D>>();
anchorPoints.add(new Pair<Point2D, Point2D>(bandStartPointAnchorNode1,
bandEndPointAnchorNode1));
anchorPoints.add(new Pair<Point2D, Point2D>(
leftBundleConnectionPointOffsetAnchor,
rightBundleConnectionPointOffsetAnchor));
anchorPoints.add(new Pair<Point2D, Point2D>(
leftBandBundleConnecionPoint, rightBandBundleConnecionPoint));
connectionBandRenderer.renderComplexBand(gl, anchorPoints, false,
new float[] { 0, 0, 0 }, 1);
Point2D prevBandAnchorPoint = leftBandBundleConnecionPoint;
for (ADimensionGroupData dimensionGroupData : commonDimensionGroupsNode1) {
anchorPoints = new ArrayList<Pair<Point2D, Point2D>>();
Pair<Point2D, Point2D> dimensionGroupAnchorPoints = node1
.getBottomDimensionGroupAnchorPoints(dimensionGroupData);
Pair<Point2D, Point2D> dimensionGroupAnchorOffsetPoints = new Pair<Point2D, Point2D>();
dimensionGroupAnchorOffsetPoints
.setFirst(new Point2D.Float(
(float) dimensionGroupAnchorPoints.getFirst()
.getX(), (float) dimensionGroupAnchorPoints
.getFirst().getY() - 0.1f));
dimensionGroupAnchorOffsetPoints
.setSecond(new Point2D.Float(
(float) dimensionGroupAnchorPoints.getSecond()
.getX(), (float) dimensionGroupAnchorPoints
.getSecond().getY() - 0.1f));
int width = bandWidthMap.get(dimensionGroupData);
Point2D nextBandAnchorPoint = new Point2D.Float(
(float) prevBandAnchorPoint.getX()
+ pixelGLConverter.getGLWidthForPixelWidth(width),
(float) prevBandAnchorPoint.getY());
Point2D bandOffsetPoint1 = new Point2D.Float(
(float) prevBandAnchorPoint.getX(),
(float) dimensionGroupAnchorPoints.getFirst().getY() - 0.18f);
Point2D bandOffsetPoint2 = new Point2D.Float(
(float) nextBandAnchorPoint.getX(),
(float) dimensionGroupAnchorPoints.getSecond().getY() - 0.18f);
anchorPoints.add(dimensionGroupAnchorPoints);
anchorPoints.add(dimensionGroupAnchorOffsetPoints);
anchorPoints.add(new Pair<Point2D, Point2D>(bandOffsetPoint1,
bandOffsetPoint2));
anchorPoints.add(new Pair<Point2D, Point2D>(prevBandAnchorPoint,
nextBandAnchorPoint));
connectionBandRenderer.renderComplexBand(gl, anchorPoints, false,
new float[] { 0, 0, 0 }, 1);
prevBandAnchorPoint = nextBandAnchorPoint;
}
}
protected int calcDimensionGroupBandWidthPixels(
ADimensionGroupData dimensionGroupData) {
// TODO: implement properly
return 5;
}
protected Point2D calcBundlingPoint(IDataGraphNode node,
List<ADimensionGroupData> dimensionGroups) {
float summedX = 0;
for (ADimensionGroupData dimensionGroupData : dimensionGroups) {
Pair<Point2D, Point2D> anchorPoints = node
.getBottomDimensionGroupAnchorPoints(dimensionGroupData);
summedX += anchorPoints.getFirst().getX()
+ anchorPoints.getSecond().getX();
}
return new Point2D.Float(summedX
/ ((float) dimensionGroups.size() * 2.0f), (float) node
.getBoundingBox().getMinY() - 0.1f);
}
protected void renderVerticalBand(GL2 gl, IDataGraphNode bottomNode,
IDataGraphNode topNode, IEdgeRoutingStrategy edgeRoutingStrategy,
ConnectionBandRenderer connectionBandRenderer) {
Point2D positionBottom = bottomNode.getPosition();
Point2D positionTop = topNode.getPosition();
float spacingY = (float) ((positionTop.getY() - topNode.getHeight() / 2.0f) - (positionBottom
.getY() + bottomNode.getHeight() / 2.0f));
float deltaX = (float) (positionBottom.getX() - positionTop.getX());
ArrayList<Point2D> edgePoints = new ArrayList<Point2D>();
Pair<Point2D, Point2D> anchorPointsBottom = bottomNode
.getTopAnchorPoints();
Pair<Point2D, Point2D> anchorPointsTop = topNode
.getBottomAnchorPoints();
float ratioX = deltaX / viewFrustum.getWidth();
float bottomEdgeAnchorX = (float) positionBottom.getX() - ratioX
* bottomNode.getWidth() / 2.0f;
float bottomEdgeAnchorY = (float) (anchorPointsBottom.getFirst().getY() + Math
.min(0.2f * spacingY,
pixelGLConverter
.getGLHeightForPixelHeight(MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS)));
Point2D edgeAnchorPointBottom = new Point2D.Float(bottomEdgeAnchorX,
bottomEdgeAnchorY);
float topEdgeAnchorX = (float) positionTop.getX() + ratioX
* topNode.getWidth() / 2.0f;
float topEdgeAnchorY = (float) (anchorPointsTop.getFirst().getY() - Math
.min(0.2f * spacingY,
pixelGLConverter
.getGLHeightForPixelHeight(MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS)));
Point2D edgeAnchorPointTop = new Point2D.Float(topEdgeAnchorX,
topEdgeAnchorY);
edgePoints.add(edgeAnchorPointBottom);
edgePoints.add(edgeAnchorPointTop);
edgeRoutingStrategy.createEdge(edgePoints);
Point2D edgeRoutingHelperPointBottom = new Point2D.Float(
(float) edgeAnchorPointBottom.getX(),
(float) anchorPointsBottom.getFirst().getY());
Point2D edgeRoutingHelperPointTop = new Point2D.Float(
(float) edgeAnchorPointTop.getX(), (float) anchorPointsTop
.getFirst().getY());
edgePoints.add(edgeRoutingHelperPointTop);
edgePoints.add(0, edgeRoutingHelperPointBottom);
float nodeEdgeAnchorSpacingBottom = (float) edgeAnchorPointBottom
.getY() - (float) anchorPointsBottom.getFirst().getY();
Pair<Point2D, Point2D> offsetAnchorPointsBottom = new Pair<Point2D, Point2D>();
offsetAnchorPointsBottom.setFirst(new Point2D.Float(
(float) anchorPointsBottom.getFirst().getX(),
(float) anchorPointsBottom.getFirst().getY() + 0.3f
* nodeEdgeAnchorSpacingBottom));
offsetAnchorPointsBottom.setSecond(new Point2D.Float(
(float) anchorPointsBottom.getSecond().getX(),
(float) anchorPointsBottom.getSecond().getY() + 0.3f
* nodeEdgeAnchorSpacingBottom));
float nodeEdgeAnchorSpacingTop = (float) Math.abs(edgeAnchorPointTop
.getY() - (float) anchorPointsTop.getFirst().getY());
Pair<Point2D, Point2D> offsetAnchorPointsTop = new Pair<Point2D, Point2D>();
offsetAnchorPointsTop.setFirst(new Point2D.Float(
(float) anchorPointsTop.getFirst().getX(),
(float) anchorPointsTop.getFirst().getY() - 0.3f
* nodeEdgeAnchorSpacingTop));
offsetAnchorPointsTop.setSecond(new Point2D.Float(
(float) anchorPointsTop.getSecond().getX(),
(float) anchorPointsTop.getSecond().getY() - 0.3f
* nodeEdgeAnchorSpacingTop));
gl.glColor4f(0, 0, 0, 0.5f);
List<Vec3f> bandPoints = connectionBandRenderer.calcInterpolatedBand(
gl, edgePoints, 20, pixelGLConverter);
connectionBandRenderer.render(gl, bandPoints);
gl.glColor4f(0, 0, 0, 1f);
gl.glBegin(GL2.GL_LINE_STRIP);
for (int i = 0; i < bandPoints.size() / 2; i++) {
gl.glVertex3f(bandPoints.get(i).x(), bandPoints.get(i).y(),
bandPoints.get(i).z());
}
gl.glEnd();
gl.glBegin(GL2.GL_LINE_STRIP);
for (int i = bandPoints.size() / 2; i < bandPoints.size(); i++) {
gl.glVertex3f(bandPoints.get(i).x(), bandPoints.get(i).y(),
bandPoints.get(i).z());
}
gl.glEnd();
Point2D bandAnchorPoint1Bottom = new Point2D.Float(bandPoints.get(0)
.x(), bandPoints.get(0).y());
Point2D bandAnchorPoint2Bottom = new Point2D.Float(bandPoints.get(
bandPoints.size() - 1).x(), bandPoints.get(
bandPoints.size() - 1).y());
Pair<Point2D, Point2D> bandAnchorPointsBottom = new Pair<Point2D, Point2D>(
bandAnchorPoint2Bottom, bandAnchorPoint1Bottom);
float vecXPoint1Bottom = (float) bandAnchorPoint1Bottom.getX()
- bandPoints.get(1).x();
float vecYPoint1Bottom = (float) bandAnchorPoint1Bottom.getY()
- bandPoints.get(1).y();
float vecXPoint2Bottom = (float) bandAnchorPoint2Bottom.getX()
- bandPoints.get(bandPoints.size() - 2).x();
float vecYPoint2Bottom = (float) bandAnchorPoint2Bottom.getY()
- bandPoints.get(bandPoints.size() - 2).y();
Point2D bandOffsetAnchorPoint1Bottom = calcPointOnLineWithFixedY(
bandAnchorPoint1Bottom, vecXPoint1Bottom, vecYPoint1Bottom,
(float) offsetAnchorPointsBottom.getFirst().getY(),
(float) offsetAnchorPointsBottom.getFirst().getX(),
(float) offsetAnchorPointsBottom.getSecond().getX(),
(float) offsetAnchorPointsBottom.getSecond().getX(),
(float) offsetAnchorPointsBottom.getSecond().getX());
Point2D bandOffsetAnchorPoint2Bottom = calcPointOnLineWithFixedY(
bandAnchorPoint2Bottom, vecXPoint2Bottom, vecYPoint2Bottom,
(float) offsetAnchorPointsBottom.getSecond().getY(),
(float) offsetAnchorPointsBottom.getFirst().getX(),
(float) offsetAnchorPointsBottom.getSecond().getX(),
(float) offsetAnchorPointsBottom.getFirst().getX(),
(float) offsetAnchorPointsBottom.getFirst().getX());
Pair<Point2D, Point2D> bandOffsetAnchorPointsBottom = new Pair<Point2D, Point2D>(
bandOffsetAnchorPoint2Bottom, bandOffsetAnchorPoint1Bottom);
Point2D bandAnchorPoint1Top = new Point2D.Float(bandPoints.get(
bandPoints.size() / 2 - 1).x(), bandPoints.get(
bandPoints.size() / 2 - 1).y());
Point2D bandAnchorPoint2Top = new Point2D.Float(bandPoints.get(
bandPoints.size() / 2).x(), bandPoints.get(
bandPoints.size() / 2).y());
Pair<Point2D, Point2D> bandAnchorPointsTop = new Pair<Point2D, Point2D>(
bandAnchorPoint2Top, bandAnchorPoint1Top);
float vecXPoint1Top = (float) bandAnchorPoint1Top.getX()
- bandPoints.get(bandPoints.size() / 2 - 2).x();
float vecYPoint1Top = (float) bandAnchorPoint1Top.getY()
- bandPoints.get(bandPoints.size() / 2 - 2).y();
float vecXPoint2Top = (float) bandAnchorPoint2Top.getX()
- bandPoints.get(bandPoints.size() / 2 + 1).x();
float vecYPoint2Top = (float) bandAnchorPoint2Top.getY()
- bandPoints.get(bandPoints.size() / 2 + 1).y();
Point2D bandOffsetAnchorPoint1Top = calcPointOnLineWithFixedY(
bandAnchorPoint1Top, vecXPoint1Top, vecYPoint1Top,
(float) offsetAnchorPointsTop.getFirst().getY(),
(float) offsetAnchorPointsTop.getFirst().getX(),
(float) offsetAnchorPointsTop.getSecond().getX(),
(float) offsetAnchorPointsTop.getSecond().getX(),
(float) offsetAnchorPointsTop.getSecond().getX());
Point2D bandOffsetAnchorPoint2Top = calcPointOnLineWithFixedY(
bandAnchorPoint2Top, vecXPoint2Top, vecYPoint2Top,
(float) offsetAnchorPointsTop.getSecond().getY(),
(float) offsetAnchorPointsTop.getFirst().getX(),
(float) offsetAnchorPointsTop.getSecond().getX(),
(float) offsetAnchorPointsTop.getFirst().getX(),
(float) offsetAnchorPointsTop.getFirst().getX());
Pair<Point2D, Point2D> bandOffsetAnchorPointsTop = new Pair<Point2D, Point2D>(
bandOffsetAnchorPoint2Top, bandOffsetAnchorPoint1Top);
List<Pair<Point2D, Point2D>> bottomBandConnectionPoints = new ArrayList<Pair<Point2D, Point2D>>();
bottomBandConnectionPoints.add(anchorPointsBottom);
bottomBandConnectionPoints.add(offsetAnchorPointsBottom);
bottomBandConnectionPoints.add(bandOffsetAnchorPointsBottom);
bottomBandConnectionPoints.add(bandAnchorPointsBottom);
List<Pair<Point2D, Point2D>> topBandConnectionPoints = new ArrayList<Pair<Point2D, Point2D>>();
topBandConnectionPoints.add(anchorPointsTop);
topBandConnectionPoints.add(offsetAnchorPointsTop);
topBandConnectionPoints.add(bandOffsetAnchorPointsTop);
topBandConnectionPoints.add(bandAnchorPointsTop);
// GLHelperFunctions.drawPointAt(gl, (float)
// bandOffsetAnchorPointsBottom
// .getFirst().getX(), (float) bandOffsetAnchorPointsBottom
// .getFirst().getY(), 0);
// GLHelperFunctions.drawPointAt(gl, (float) offsetAnchorPointsBottom
// .getFirst().getX(), (float) offsetAnchorPointsBottom.getFirst()
// .getY(), 0);
// GLHelperFunctions.drawPointAt(gl, (float) bandAnchorPointsBottom
// .getFirst().getX(), (float) bandAnchorPointsBottom.getFirst()
// .getY(), 0);
connectionBandRenderer.renderComplexBand(gl,
bottomBandConnectionPoints, false, new float[] { 0, 0, 0 },
0.5f);
connectionBandRenderer.renderComplexBand(gl, topBandConnectionPoints,
false, new float[] { 0, 0, 0 }, 0.5f);
}
protected Point2D calcPointOnLineWithFixedX(Point2D pointOnLine,
float vecX, float vecY, float fixedX, float minY, float maxY,
float exceedingMinLimitValY, float exceedingMaxLimitValY) {
float lambda = 0;
if (vecX != 0)
lambda = vecY / vecX;
float pointY = (float) pointOnLine.getY()
- ((float) pointOnLine.getX() - fixedX) * lambda;
if (pointY < minY) {
pointY = exceedingMinLimitValY;
}
if (pointY > maxY) {
pointY = exceedingMaxLimitValY;
}
return new Point2D.Float(fixedX, pointY);
}
protected Point2D calcPointOnLineWithFixedY(Point2D pointOnLine,
float vecX, float vecY, float fixedY, float minX, float maxX,
float exceedingMinLimitValX, float exceedingMaxLimitValX) {
float lambda = 0;
if (vecX != 0)
lambda = vecY / vecX;
float pointX = (float) pointOnLine.getX()
- (lambda == 0 ? 0 : ((float) pointOnLine.getY() - fixedY)
/ lambda);
if (pointX < minX) {
pointX = exceedingMinLimitValX;
}
if (pointX > maxX) {
pointX = exceedingMaxLimitValX;
}
return new Point2D.Float(pointX, fixedY);
}
protected void renderHorizontalBand(GL2 gl, IDataGraphNode leftNode,
IDataGraphNode rightNode, IEdgeRoutingStrategy edgeRoutingStrategy,
ConnectionBandRenderer connectionBandRenderer) {
Point2D positionLeft = leftNode.getPosition();
Point2D positionRight = rightNode.getPosition();
float spacingX = (float) ((positionRight.getX() - rightNode.getWidth() / 2.0f) - (positionLeft
.getX() + leftNode.getWidth() / 2.0f));
float deltaY = (float) (positionLeft.getY() - positionRight.getY());
Pair<Point2D, Point2D> anchorPointsLeft = leftNode
.getRightAnchorPoints();
Pair<Point2D, Point2D> anchorPointsRight = rightNode
.getLeftAnchorPoints();
ArrayList<Point2D> edgePoints = new ArrayList<Point2D>();
float ratioY = deltaY / viewFrustum.getHeight();
float leftEdgeAnchorY = (float) positionLeft.getY() - ratioY
* leftNode.getHeight() / 2.0f;
float leftEdgeAnchorX = (float) (anchorPointsLeft.getFirst().getX() + Math
.min(0.2f * spacingX,
pixelGLConverter
.getGLWidthForPixelWidth(MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS)));
Point2D edgeAnchorPointLeft = new Point2D.Float(leftEdgeAnchorX,
leftEdgeAnchorY);
float rightEdgeAnchorY = (float) positionRight.getY() + ratioY
* rightNode.getHeight() / 2.0f;
float rightEdgeAnchorX = (float) (anchorPointsRight.getFirst().getX() - Math
.min(0.2f * spacingX,
pixelGLConverter
.getGLWidthForPixelWidth(MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS)));
Point2D edgeAnchorPointRight = new Point2D.Float(rightEdgeAnchorX,
rightEdgeAnchorY);
edgePoints.add(edgeAnchorPointLeft);
edgePoints.add(edgeAnchorPointRight);
edgeRoutingStrategy.createEdge(edgePoints);
Point2D bandRoutingHelperPointLeft = new Point2D.Float(
(float) anchorPointsLeft.getFirst().getX(),
(float) edgeAnchorPointLeft.getY());
Point2D bandRoutingHelperPointRight = new Point2D.Float(
(float) anchorPointsRight.getFirst().getX(),
(float) edgeAnchorPointRight.getY());
edgePoints.add(bandRoutingHelperPointRight);
edgePoints.add(0, bandRoutingHelperPointLeft);
float nodeEdgeAnchorSpacingLeft = (float) edgeAnchorPointLeft.getX()
- (float) anchorPointsLeft.getFirst().getX();
Pair<Point2D, Point2D> offsetAnchorPointsLeft = new Pair<Point2D, Point2D>();
offsetAnchorPointsLeft.setFirst(new Point2D.Float(
(float) anchorPointsLeft.getFirst().getX() + 0.3f
* nodeEdgeAnchorSpacingLeft, (float) anchorPointsLeft
.getFirst().getY()));
offsetAnchorPointsLeft.setSecond(new Point2D.Float(
(float) anchorPointsLeft.getSecond().getX() + 0.3f
* nodeEdgeAnchorSpacingLeft, (float) anchorPointsLeft
.getSecond().getY()));
float nodeEdgeAnchorSpacingRight = (float) Math
.abs(edgeAnchorPointRight.getX()
- (float) anchorPointsRight.getFirst().getX());
Pair<Point2D, Point2D> offsetAnchorPointsRight = new Pair<Point2D, Point2D>();
offsetAnchorPointsRight.setFirst(new Point2D.Float(
(float) anchorPointsRight.getFirst().getX() - 0.3f
* nodeEdgeAnchorSpacingRight, (float) anchorPointsRight
.getFirst().getY()));
offsetAnchorPointsRight.setSecond(new Point2D.Float(
(float) anchorPointsRight.getSecond().getX() - 0.3f
* nodeEdgeAnchorSpacingRight, (float) anchorPointsRight
.getSecond().getY()));
gl.glColor4f(0, 0, 0, 0.5f);
List<Vec3f> bandPoints = connectionBandRenderer.calcInterpolatedBand(
gl, edgePoints, 20, pixelGLConverter);
connectionBandRenderer.render(gl, bandPoints);
gl.glColor4f(0, 0, 0, 1f);
gl.glBegin(GL2.GL_LINE_STRIP);
for (int i = 0; i < bandPoints.size() / 2; i++) {
gl.glVertex3f(bandPoints.get(i).x(), bandPoints.get(i).y(),
bandPoints.get(i).z());
}
gl.glEnd();
gl.glBegin(GL2.GL_LINE_STRIP);
for (int i = bandPoints.size() / 2; i < bandPoints.size(); i++) {
gl.glVertex3f(bandPoints.get(i).x(), bandPoints.get(i).y(),
bandPoints.get(i).z());
}
gl.glEnd();
Point2D bandAnchorPoint1Left = new Point2D.Float(bandPoints.get(0).x(),
bandPoints.get(0).y());
Point2D bandAnchorPoint2Left = new Point2D.Float(bandPoints.get(
bandPoints.size() - 1).x(), bandPoints.get(
bandPoints.size() - 1).y());
Pair<Point2D, Point2D> bandAnchorPointsLeft = new Pair<Point2D, Point2D>(
bandAnchorPoint2Left, bandAnchorPoint1Left);
float vecXPoint1Left = (float) bandAnchorPoint1Left.getX()
- bandPoints.get(1).x();
float vecYPoint1Left = (float) bandAnchorPoint1Left.getY()
- bandPoints.get(1).y();
float vecXPoint2Left = (float) bandAnchorPoint2Left.getX()
- bandPoints.get(bandPoints.size() - 2).x();
float vecYPoint2Left = (float) bandAnchorPoint2Left.getY()
- bandPoints.get(bandPoints.size() - 2).y();
Point2D bandOffsetAnchorPoint1Left = calcPointOnLineWithFixedX(
bandAnchorPoint1Left, vecXPoint1Left, vecYPoint1Left,
(float) offsetAnchorPointsLeft.getSecond().getX(),
(float) offsetAnchorPointsLeft.getSecond().getY(),
(float) offsetAnchorPointsLeft.getFirst().getY(),
(float) offsetAnchorPointsLeft.getSecond().getY(),
(float) offsetAnchorPointsLeft.getSecond().getY());
Point2D bandOffsetAnchorPoint2Left = calcPointOnLineWithFixedX(
bandAnchorPoint2Left, vecXPoint2Left, vecYPoint2Left,
(float) offsetAnchorPointsLeft.getFirst().getX(),
(float) offsetAnchorPointsLeft.getSecond().getY(),
(float) offsetAnchorPointsLeft.getFirst().getY(),
(float) offsetAnchorPointsLeft.getFirst().getY(),
(float) offsetAnchorPointsLeft.getFirst().getY());
Pair<Point2D, Point2D> bandOffsetAnchorPointsLeft = new Pair<Point2D, Point2D>(
bandOffsetAnchorPoint2Left, bandOffsetAnchorPoint1Left);
Point2D bandAnchorPoint1Right = new Point2D.Float(bandPoints.get(
bandPoints.size() / 2 - 1).x(), bandPoints.get(
bandPoints.size() / 2 - 1).y());
Point2D bandAnchorPoint2Right = new Point2D.Float(bandPoints.get(
bandPoints.size() / 2).x(), bandPoints.get(
bandPoints.size() / 2).y());
Pair<Point2D, Point2D> bandAnchorPointsRight = new Pair<Point2D, Point2D>(
bandAnchorPoint2Right, bandAnchorPoint1Right);
float vecXPoint1Right = (float) bandAnchorPoint1Right.getX()
- bandPoints.get(bandPoints.size() / 2 - 2).x();
float vecYPoint1Right = (float) bandAnchorPoint1Right.getY()
- bandPoints.get(bandPoints.size() / 2 - 2).y();
float vecXPoint2Right = (float) bandAnchorPoint2Right.getX()
- bandPoints.get(bandPoints.size() / 2 + 1).x();
float vecYPoint2Right = (float) bandAnchorPoint2Right.getY()
- bandPoints.get(bandPoints.size() / 2 + 1).y();
Point2D bandOffsetAnchorPoint1Right = calcPointOnLineWithFixedX(
bandAnchorPoint1Right, vecXPoint1Right, vecYPoint1Right,
(float) offsetAnchorPointsRight.getSecond().getX(),
(float) offsetAnchorPointsRight.getSecond().getY(),
(float) offsetAnchorPointsRight.getFirst().getY(),
(float) offsetAnchorPointsRight.getSecond().getY(),
(float) offsetAnchorPointsRight.getSecond().getY());
Point2D bandOffsetAnchorPoint2Right = calcPointOnLineWithFixedX(
bandAnchorPoint2Right, vecXPoint2Right, vecYPoint2Right,
(float) offsetAnchorPointsRight.getFirst().getX(),
(float) offsetAnchorPointsRight.getSecond().getY(),
(float) offsetAnchorPointsRight.getFirst().getY(),
(float) offsetAnchorPointsRight.getFirst().getY(),
(float) offsetAnchorPointsRight.getFirst().getY());
Pair<Point2D, Point2D> bandOffsetAnchorPointsRight = new Pair<Point2D, Point2D>(
bandOffsetAnchorPoint2Right, bandOffsetAnchorPoint1Right);
List<Pair<Point2D, Point2D>> leftBandConnectionPoints = new ArrayList<Pair<Point2D, Point2D>>();
leftBandConnectionPoints.add(anchorPointsLeft);
leftBandConnectionPoints.add(offsetAnchorPointsLeft);
leftBandConnectionPoints.add(bandOffsetAnchorPointsLeft);
leftBandConnectionPoints.add(bandAnchorPointsLeft);
List<Pair<Point2D, Point2D>> rightBandConnectionPoints = new ArrayList<Pair<Point2D, Point2D>>();
rightBandConnectionPoints.add(anchorPointsRight);
rightBandConnectionPoints.add(offsetAnchorPointsRight);
rightBandConnectionPoints.add(bandOffsetAnchorPointsRight);
rightBandConnectionPoints.add(bandAnchorPointsRight);
connectionBandRenderer.renderComplexBand(gl, leftBandConnectionPoints,
false, new float[] { 0, 0, 0 }, 0.5f);
connectionBandRenderer.renderComplexBand(gl, rightBandConnectionPoints,
false, new float[] { 0, 0, 0 }, 0.5f);
}
public int getMaxBandWidth() {
return maxBandWidth;
}
public void setMaxBandWidth(int maxBandWidth) {
this.maxBandWidth = maxBandWidth;
}
} |
package org.lamport.tla.toolbox.spec.manager;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.lamport.tla.toolbox.spec.Spec;
import org.lamport.tla.toolbox.spec.nature.TLANature;
import org.lamport.tla.toolbox.ui.handler.CloseSpecHandler;
import org.lamport.tla.toolbox.ui.handler.OpenSpecHandler;
import org.lamport.tla.toolbox.ui.property.GenericSelectionProvider;
import org.lamport.tla.toolbox.util.ResourceHelper;
import org.lamport.tla.toolbox.util.UIHelper;
import org.lamport.tla.toolbox.util.pref.IPreferenceConstants;
import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;
/**
* Specification manager based on the Workspace
* @version $Id$
* @author Simon Zambrovski
*/
public class WorkspaceSpecManager extends GenericSelectionProvider implements ISpecManager, IResourceChangeListener,
IAdaptable
{
private Hashtable specStorage = new Hashtable(47);
private Spec loadedSpec = null;
/**
* Constructor
*/
public WorkspaceSpecManager()
{
IWorkspace ws = ResourcesPlugin.getWorkspace();
String specLoadedName = PreferenceStoreHelper.getInstancePreferenceStore().getString(
IPreferenceConstants.I_SPEC_LOADED);
IProject[] projects = ws.getRoot().getProjects();
try
{
Spec spec = null;
for (int i = 0; i < projects.length; i++)
{
// changed from projects[i].isAccessible()
if (projects[i].isOpen())
{
if (projects[i].hasNature(TLANature.ID))
{
spec = new Spec(projects[i]);
addSpec(spec);
// load the spec if found
if (spec.getName().equals(specLoadedName))
{
this.setSpecLoaded(spec);
}
}
} else
{
// DELETE closed projects
projects[i].delete(true, null);
}
}
} catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ws.addResourceChangeListener(this);
}
/**
* Destructor
*/
public void terminate()
{
IWorkspace ws = ResourcesPlugin.getWorkspace();
ws.removeResourceChangeListener(this);
if (this.loadedSpec != null
&& PreferenceStoreHelper.getInstancePreferenceStore().getBoolean(
IPreferenceConstants.I_RESTORE_LAST_SPEC))
{
PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED,
this.loadedSpec.getName());
} else
{
PreferenceStoreHelper.getInstancePreferenceStore().setValue(IPreferenceConstants.I_SPEC_LOADED, "");
}
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#addSpec(toolbox.spec.Spec)
*/
public void addSpec(Spec spec)
{
specStorage.put(spec.getName(), spec);
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#getLoadedSpec()
*/
public Spec getSpecLoaded()
{
return this.loadedSpec;
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#getRecentlyOpened()
*/
public Spec[] getRecentlyOpened()
{
Collection specs = specStorage.values();
return (Spec[]) specs.toArray(new Spec[specs.size()]);
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#getSpecByName(java.lang.String)
*/
public Spec getSpecByName(String specName)
{
return (Spec) specStorage.get(specName);
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#getSpecByRootModule(java.lang.String)
*/
public Spec getSpecByRootModule(String rootModulePath)
{
if (rootModulePath != null)
{
Iterator specI = specStorage.values().iterator();
if (specI.hasNext())
{
Spec spec = (Spec) specI.next();
if (spec.getRootFilename().equals(rootModulePath))
{
return spec;
}
}
}
return null;
}
/*
* (non-Javadoc)
* @see org.lamport.tla.toolbox.spec.manager.ISpecManager#setSpecLoaded(toolbox.spec.Spec)
*/
public void setSpecLoaded(Spec loadedSpec)
{
this.loadedSpec = loadedSpec;
if (this.loadedSpec != null)
{
// touch the spec
this.loadedSpec.setLastModified();
}
}
/*
* (non-Javadoc)
* @see
* org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent
* )
*/
public void resourceChanged(IResourceChangeEvent event)
{
/*
* remove elements from the storage if the projects are deleted
*/
IResource resource = event.getResource();
if (resource != null && IResource.PROJECT == resource.getType()
&& IResourceChangeEvent.PRE_DELETE == event.getType())
{
specStorage.remove(resource.getName());
}
}
/**
* Renames a spec
* @param spec
* @param newName
*/
public void renameSpec(Spec spec, String newName)
{
boolean setBack = false;
if (this.loadedSpec == spec)
{
// renaming current spec...
// close it here
UIHelper.runCommand(CloseSpecHandler.COMMAND_ID, new HashMap());
setBack = true;
}
specStorage.remove(spec.getName());
IProject project = ResourceHelper.projectRename(spec.getProject(), newName);
if (project != null)
{
spec = new Spec(project);
addSpec(spec);
}
// set the spec
if (setBack)
{
// reopen the spec
HashMap parameters = new HashMap();
parameters.put(OpenSpecHandler.PARAM_SPEC, newName);
UIHelper.runCommand(OpenSpecHandler.COMMAND_ID, parameters);
} else
{
spec.setLastModified();
}
}
/**
* Removes the specification
* @param spec specification to remove
*/
public void removeSpec(Spec spec)
{
if (this.loadedSpec == spec)
{
// deleting current spec...
// close it here
UIHelper.runCommand(CloseSpecHandler.COMMAND_ID, new HashMap());
}
ResourceHelper.deleteProject(spec.getProject());
specStorage.remove(spec.getName());
}
/**
* Constructs a specification name from the proposition string
* @param proposition a string with spec name
* @param firstRun a flag for the first run
* @return the name of a spec that is not already used.
*/
public String constructSpecName(String proposition, boolean firstRun)
{
Spec existingSpec = getSpecByName(proposition);
if (existingSpec != null)
{
if (firstRun)
{
return constructSpecName(proposition.concat("_1"), false);
} else
{
String oldNumber = proposition.substring(proposition.lastIndexOf("_"));
int number = Integer.parseInt(oldNumber) + 1;
proposition = proposition.substring(0, proposition.lastIndexOf("_"));
return constructSpecName(proposition + number, false);
}
}
return proposition;
}
/**
* Retrieves loaded spec encapsulated in to a selection object
*/
public ISelection getSelection()
{
if (this.loadedSpec != null)
{
return new StructuredSelection(this.loadedSpec);
} else
{
return null;
}
}
/**
* Sets the spec loaded
*/
public void setSelection(ISelection selection)
{
if (selection == null)
{
setSpecLoaded(null);
return;
}
if (selection instanceof IStructuredSelection)
{
IStructuredSelection sSelection = (IStructuredSelection) selection;
if (sSelection.toArray() instanceof Spec[])
{
Spec[] specs = (Spec[]) sSelection.toArray();
if (specs.length == 0)
{
setSpecLoaded(null);
} else if (specs.length == 1)
{
setSpecLoaded(specs[0]);
} else
{
throw new IllegalArgumentException("Only one specification can be selected");
}
} else
{
throw new IllegalArgumentException(
"Workspace specification manager only accepts specification objects to be selected");
}
} else
{
throw new IllegalArgumentException(
"Workspace specification manager only accepts specification object in a StructuredSelection");
}
}
/**
* Only support the interface, no real adaptivity
*/
public Object getAdapter(Class adapter)
{
return null;
}
} |
package org.xillium.base.beans;
import java.beans.*;
import java.lang.reflect.*;
import java.util.*;
import org.xillium.base.type.typeinfo;
import org.xillium.base.util.ValueOf;
/**
* A collection of commonly used bean manipulation utilities.
*/
public class Beans {
/**
* Tests whether a non-primitive type is directly displayable.
*
* @param type the class object to test
* @return whether the type is displayable
*/
public static boolean isDisplayable(Class<?> type) {
return Enum.class.isAssignableFrom(type)
|| type == java.net.URL.class || type == java.io.File.class
|| java.math.BigInteger.class.isAssignableFrom(type)
|| java.math.BigDecimal.class.isAssignableFrom(type)
|| java.util.Date.class.isAssignableFrom(type)
|| java.sql.Date.class.isAssignableFrom(type)
|| java.sql.Time.class.isAssignableFrom(type);
}
/**
* Class lookup by name, which also accepts primitive type names.
*
* @param name the full name of the class
* @return the class object
* @throws ClassNotFoundException if the class is not found
*/
public static Class<?> classForName(String name) throws ClassNotFoundException {
if ("void".equals(name)) return void.class;
if ("char".equals(name)) return char.class;
if ("boolean".equals(name)) return boolean.class;
if ("byte".equals(name)) return byte.class;
if ("short".equals(name)) return short.class;
if ("int".equals(name)) return int.class;
if ("long".equals(name)) return long.class;
if ("float".equals(name)) return float.class;
if ("double".equals(name)) return double.class;
return Class.forName(name);
}
/**
* Tests whether a class is a primitive type. Different from Class.isPrimitive, this method consider
* the following also as "primitive types".
* <ul>
* <li>Wrapper classes of the primitive types
* <li>Class
* <li>String
* </ul>
*
* @param type the type to test
* @return whether the type is primitive
*/
public static boolean isPrimitive(Class<?> type) {
return type == Class.class || type == String.class
|| type == Character.class || type == Character.TYPE
|| type == Boolean.class || type == Boolean.TYPE
|| type == Byte.class || type == Byte.TYPE
|| type == Short.class || type == Short.TYPE
|| type == Integer.class || type == Integer.TYPE
|| type == Long.class || type == Long.TYPE
|| type == Float.class || type == Float.TYPE
|| type == Double.class || type == Double.TYPE
|| type == Void.TYPE;
}
/**
* Converts a boxed type to its primitive counterpart.
*
* @param type the type to convert
* @return the primitive counterpart
*/
public static Class<?> toPrimitive(Class<?> type) {
if (type.isPrimitive()) {
return type;
} else if (type == Boolean.class) {
return Boolean.TYPE;
} else if (type == Character.class) {
return Character.TYPE;
} else if (type == Byte.class) {
return Byte.TYPE;
} else if (type == Short.class) {
return Short.TYPE;
} else if (type == Integer.class) {
return Integer.TYPE;
} else if (type == Long.class) {
return Long.TYPE;
} else if (type == Float.class) {
return Float.TYPE;
} else if (type == Double.class) {
return Double.TYPE;
} else {
return null;
}
}
/**
* Boxes a primitive type.
*
* @param type the primitive type to box
* @return the boxed type
*/
public static Class<?> boxPrimitive(Class<?> type) {
if (!type.isPrimitive()) {
return type;
} else if (type == byte.class) {
return Byte.class;
} else if (type == short.class) {
return Short.class;
} else if (type == int.class) {
return Integer.class;
} else if (type == long.class) {
return Long.class;
} else if (type == boolean.class) {
return Boolean.class;
} else if (type == float.class) {
return Float.class;
} else if (type == double.class) {
return Double.class;
} else if (type == char.class) {
return Character.class;
} else {
return type;
}
}
/**
* Boxes primitive types.
*
* @param types an array of primitive types to box
* @return an array of boxed types
*/
public static Class<?>[] boxPrimitives(Class<?>[] types) {
for (int i = 0; i < types.length; ++i) {
types[i] = boxPrimitive(types[i]);
}
return types;
}
/**
* Returns a known field by name from the given class disregarding its access control setting, looking through
* all super classes if needed.
*
* @param type the class to start with
* @param name the name of the field
* @return a Field object representing the known field
* @throws NoSuchFieldException if the field is not found
*/
public static Field getKnownField(Class<?> type, String name) throws NoSuchFieldException {
NoSuchFieldException last = null;
do {
try {
Field field = type.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException x) {
last = x;
type = type.getSuperclass();
}
} while (type != null);
throw last;
}
/**
* Returns all known fields in the given class and all its super classes.
*
* @param type the class to start with
* @return an array of Field objects representing all known fields
* @throws SecurityException if a security manager denies access
*/
public static Field[] getKnownFields(Class<?> type) throws SecurityException {
List<Field> fields = new ArrayList<Field>();
while (type != null) {
for (Field field: type.getDeclaredFields()) {
field.setAccessible(true);
fields.add(field);
}
type = type.getSuperclass();
}
return fields.toArray(new Field[fields.size()]);
}
/**
* Returns all known fields in the given class and all its super classes.
*
* @param type the class to start with
* @return an array of Field objects representing all known instance fields
* @throws SecurityException if a security manager denies access
*/
public static Field[] getKnownInstanceFields(Class<?> type) throws SecurityException {
List<Field> fields = new ArrayList<Field>();
while (type != null) {
for (Field field: type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) continue;
field.setAccessible(true);
fields.add(field);
}
type = type.getSuperclass();
}
return fields.toArray(new Field[fields.size()]);
}
/**
* Overrides access control of an AccessibleObject, facilitating fluent coding style.
*
* @param <T> the type of the accessible object
* @param object the object to start with
* @return the same object with its access control overridden to allow all access
* @throws SecurityException if a security manager denies access
*/
public static <T extends AccessibleObject> T accessible(T object) throws SecurityException {
object.setAccessible(true);
return object;
}
public static <T> T create(Class<T> type, Object... args) throws
NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?>[] argumentTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
argumentTypes[i] = args[i].getClass();
}
return type.cast(choose(type.getConstructors(), new ConstructorParameterExtractor<T>(), null, argumentTypes).newInstance(args));
}
public static <T> T create(Class<T> type, Object[] args, int offset, int count) throws
NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (offset != 0 || count != args.length) {
return create(type, Arrays.copyOfRange(args, offset, offset + count));
} else {
return create(type, args);
}
}
public static Object invoke(Object bean, String name, Object[] args, int offset, int count) throws
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (offset != 0 || count != args.length) {
return invoke(bean, name, Arrays.copyOfRange(args, offset, offset + count));
} else {
return invoke(bean, name, args);
}
}
public static Object invoke(Object bean, String name, Object... args) throws
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Class<?>[] argumentTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
argumentTypes[i] = args[i].getClass();
}
return choose(bean.getClass().getMethods(), new MethodParameterExtractor(), name, argumentTypes).invoke(bean, args);
}
/**
* Chooses a method/constructor of a given name, whose signature best matches the given list of argument types.
*
* @param <T> the type of the member/constructor to return
* @param candidates the list of method/constructor candidates to choose from
* @param pe the ParameterExtractor
* @param name the name of the method/constructor
* @param argumentTypes the argument types
* @return the method/constructor
* @throws NoSuchMethodException if an appropriate method/constructor cannot be found
*/
public static <T extends AccessibleObject & Member> T choose(T[] candidates, ParameterExtractor pe, String name, Class<?>[] argumentTypes)
throws NoSuchMethodException {
T chosenCandidate = null;
Class<?>[] chosenParamTypes = null;
// try to find the most applicable candidate
Search: for (int i = 0; i < candidates.length; i++) {
//System.err.println("Looking at candidate " + candidates[i]);
// ignore functions with different name
if (name != null && !candidates[i].getName().equals(name)) continue;
// ignore covariance on static candidates
if (Modifier.isStatic(candidates[i].getModifiers())) continue;
//Class<?>[] parameterTypes = candidates[i].getParameterTypes();
Class<?>[] parameterTypes = pe.getParameterTypes(candidates[i]);
// ignore functions with wrong number of parameters
if (parameterTypes.length != argumentTypes.length) continue;
// coerce the primitives to objects
boxPrimitives(parameterTypes);
// ignore functions with incompatible parameter types
for (int j = 0; j < parameterTypes.length; j++) {
if (!parameterTypes[j].isAssignableFrom(argumentTypes[j])) continue Search;
}
//System.err.println("Considering candidate " + candidates[i]);
// if this is the first match then save it
if (chosenCandidate == null) {
chosenCandidate = candidates[i];
chosenParamTypes = parameterTypes;
} else {
// if this candidate is more specific in compatibility then save it
for (int j = 0; j < chosenParamTypes.length; j++) {
if (!chosenParamTypes[j].isAssignableFrom(parameterTypes[j])) continue Search;
}
// this is the best fit so far
chosenCandidate = candidates[i];
chosenParamTypes = parameterTypes;
//System.err.println("Best candidate so far " + chosenCandidate);
}
}
// return to the caller indicating that candidate was not found
if (chosenCandidate == null) {
throw(new NoSuchMethodException("Method not found: " + name));
}
//System.err.println("Chosen candidate is " + chosenCandidate);
// return the covariant candidate
return accessible(chosenCandidate); // Java bug #4071957 - have to call setAccessible even on public methods
}
private static interface ParameterExtractor {
public Class<?>[] getParameterTypes(Object object);
}
private static class ConstructorParameterExtractor<T> implements ParameterExtractor {
@SuppressWarnings("unchecked")
public Class<?>[] getParameterTypes(Object object) {
return ((Constructor<T>)object).getParameterTypes();
}
}
private static class MethodParameterExtractor implements ParameterExtractor {
public Class<?>[] getParameterTypes(Object object) {
return ((Method)object).getParameterTypes();
}
}
@SuppressWarnings("unchecked")
public static void setValue(Object object, Field field, Object value) throws IllegalArgumentException, IllegalAccessException {
if (value == null) {
//if (Number.class.isAssignableFrom(field.getType())) {
//value = java.math.BigDecimal.ZERO;
//} else return;
return;
}
try {
field.setAccessible(true);
field.set(object, value);
} catch (IllegalArgumentException x) {
@SuppressWarnings("rawtypes")
Class ftype = field.getType();
if (value instanceof Number) {
// size of "value" bigger than that of "field"?
try {
Number number = (Number)value;
if (Enum.class.isAssignableFrom(ftype)) {
field.set(object, ftype.getEnumConstants()[number.intValue()]);
} else if (Double.TYPE == ftype || Double.class.isAssignableFrom(ftype)) {
field.set(object, number.doubleValue());
} else if (Float.TYPE == ftype || Float.class.isAssignableFrom(ftype)) {
field.set(object, number.floatValue());
} else if (Long.TYPE == ftype || Long.class.isAssignableFrom(ftype)) {
field.set(object, number.longValue());
} else if (Integer.TYPE == ftype || Integer.class.isAssignableFrom(ftype)) {
field.set(object, number.intValue());
} else if (Short.TYPE == ftype || Short.class.isAssignableFrom(ftype)) {
field.set(object, number.shortValue());
} else {
field.set(object, number.byteValue());
}
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
} else if (value instanceof java.sql.Timestamp) {
try {
field.set(object, new java.sql.Date(((java.sql.Timestamp)value).getTime()));
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
} else if (value instanceof String) {
field.set(object, new ValueOf(ftype, field.getAnnotation(typeinfo.class)).invoke((String)value));
} else {
throw new IllegalArgumentException(x);
}
}
}
@Deprecated
@SuppressWarnings("unchecked")
public static <T> T valueOf(Class<T> type, String value, typeinfo annotation) {
if (type.equals(String.class)) {
return type.cast(value);
} else {
try {
Class<?> boxed = boxPrimitive(type);
try {
return (T)boxed.getMethod("valueOf", String.class).invoke(null, value);
} catch (NoSuchMethodException x) {
try {
return (T)boxed.getMethod("valueOf", Class.class, String.class).invoke(null, annotation != null ? annotation.value()[0] : type, value);
} catch (NoSuchMethodException y) {
return (T)boxed.getConstructor(String.class).newInstance(value);
}
}
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage(), x);
}
}
}
public static <T> T valueOf(Class<T> type, String value) {
return valueOf(type, value, null);
}
/**
* Fills empty, identically named public fields with values from another object.
*
* @param <T> the class of the destination object
* @param destination a destination object
* @param source a source object
* @return the same destination object with fields filled by source
*/
public static <T> T fill(T destination, Object source) {
if (destination != source) {
Class<?> stype = source.getClass();
for (Field field: destination.getClass().getFields()) {
try {
Object value = field.get(destination);
if (value == null) {
field.set(destination, stype.getField(field.getName()).get(source));
}
} catch (Exception x) {
}
}
}
return destination;
}
/**
* Overrides identically named public fields with non-empty values from another object.
*
* @param <T> the class of the destination object
* @param destination a destination object
* @param source a source object
* @return the same destination object with fields overridden by source
*/
public static <T> T override(T destination, Object source) {
if (destination != source) {
Class<?> dtype = destination.getClass();
for (Field field: source.getClass().getFields()) {
try {
Object value = field.get(source);
if (value != null) {
dtype.getField(field.getName()).set(destination, value);
}
} catch (Exception x) {
}
}
}
return destination;
}
/**
* A convenience utility method to convert a bean to a formatted string.
*
* @param bean an object
* @return a string representation of the object
*/
public static String toString(Object bean) {
try {
return bean != null ? print(new StringBuilder(), bean, 0).toString() : null;
} catch (IntrospectionException x) {
return String.valueOf(bean) + "(***" + x.getMessage() + ')';
}
}
/**
* Prints a bean to the StringBuilder.
*
* @param sb a StringBuilder
* @param bean an object
* @param level indentation level
* @return the original StringBuilder
* @throws IntrospectionException if bean introspection fails by {@link java.beans.Introspector Introspector}
*/
public static StringBuilder print(StringBuilder sb, Object bean, int level) throws IntrospectionException {
return print(sb, Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()), bean, level);
}
private static StringBuilder print(StringBuilder sb, Set<Object> objects, Object bean, int level) throws IntrospectionException {
// reference loop detection
if (objects.contains(bean)) {
indent(sb, level+1);
sb.append("<reference>: ").append(bean.getClass().getName()).append('@').append(Integer.toHexString(bean.hashCode())).append('\n');
return sb;
} else {
objects.add(bean);
}
Class<?> type = bean.getClass();
if (isPrimitive(type) || isDisplayable(type)) {
indent(sb, level);
sb.append(bean);
} else {
// public fields including those declared by super classes
for (Field field: type.getFields()) {
int modifier = field.getModifiers();
if (!Modifier.isStatic(modifier) && !Modifier.isTransient(modifier)) {
try {
indent(sb, level);
printNameValue(sb, objects, field.getName(), field.get(bean), level+1);
} catch (IllegalAccessException x) {}
}
}
// properties
if (Map.class.isInstance(bean)) {
Iterator<?> it = ((Map<?, ?>)bean).keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
indent(sb, level);
printNameValue(sb, objects, String.valueOf(key), ((Map<?, ?>)bean).get(key), level+1);
}
} else if (Iterable.class.isInstance(bean)) {
Iterator<?> it = ((Iterable<?>)bean).iterator();
int index = 0;
while (it.hasNext()) {
indent(sb, level+1);
printNameValue(sb, objects, "[" + index + "]", it.next(), level+1);
++index;
}
} else if (type.isArray()) {
for (int i = 0; i < Array.getLength(bean); ++i) {
indent(sb, level+1);
printNameValue(sb, objects, "[" + i + "]", Array.get(bean, i), level+1);
}
} else {
PropertyDescriptor[] properties = Introspector.getBeanInfo(type, Object.class).getPropertyDescriptors();
for (PropertyDescriptor property : properties) {
Object value = null;
Class<?> ptype = property.getPropertyType();
if (ptype != null) {
try {
value = accessible(property.getReadMethod()).invoke(bean); // Java bug #4071957
} catch (Exception x) {
value = x.getMessage();
}
indent(sb, level);
printNameValue(sb, objects, property.getDisplayName() + '<' + ptype.getName() + '>', value, level);
} else {
try {
Method reader = accessible(((IndexedPropertyDescriptor)property).getIndexedReadMethod()); // Java bug #4071957
for (int i = 0; ; ++i) {
value = reader.invoke(bean, i);
indent(sb, level);
printNameValue(sb, objects, property.getDisplayName() + '[' + i + ']', value, level);
}
} catch (Exception x) {}
}
}
}
}
return sb;
}
private static void printNameValue(StringBuilder sb, Set<Object> objects, String name, Object value, int level) {
if (value == null) {
sb.append(name).append(":\n");
} else if (isPrimitive(value.getClass()) || isDisplayable(value.getClass())) {
sb.append(name).append(": ").append(value).append('\n');
} else {
//sb.append(name).append(": {\n");
sb.append(name).append(": ").append(value.getClass().getName()).append('@').append(Integer.toHexString(value.hashCode())).append(" {\n");
try {
print(sb, objects, value, level+1);
} catch (IntrospectionException x) {
indent(sb, level+1);
sb.append("!error! ").append(x.getMessage());
}
indent(sb, level);
sb.append("}\n");
}
}
private static void indent(StringBuilder sb, int level) {
for(int i = 0; i < level*INDENTATION; ++i) sb.append(' ');
}
private static int INDENTATION = 2;
} |
package fr.inria.jessy.benchmark.tpcc;
import java.util.Random;
/**
* @author Wang Haiyun & ZHAO Guang
*
*/
/*according to tpcc section 4.3.2.2, this class is used for generate random string, length: [x..y],
* the character set must has at least 26 lower case and 26 upper case, and the digits from 1...9
*/
public final class NString {
private NString(){
}
private static String set = "abcdefghjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static Random rand = new Random(System.currentTimeMillis());
public static String generate(int x, int y){
int i,length;
String result="";
length = rand.nextInt(y - x + 1) + x;
for(i=0; i<length; i++){
result = result + set.charAt(rand.nextInt(61));
}
return result;
}
public static String generateFix(int x){
//generate a String with a given fixed length x
int i;
String result="";
for(i=0; i<x; i++){
result = result + set.charAt(rand.nextInt(61));
}
return result;
}
public static String original(int x, int y){
/*this method is written for populate Item table( add substring "ORIGINAL" in a random position of a
* string, tpcc section 4.3.3.1
*/
int i, length, pos;
String result = "";
y = y-8;
x = x-8;
length = rand.nextInt(y-x+1)+x;
pos = rand.nextInt(length); //where we put "original"
for(i=0; i<length; i++){
if(i == pos){
result = result + "ORIGINAL";
}
result = result + set.charAt(rand.nextInt(61));
}
return result;
}
} |
package org.voltcore.utils;
import org.voltcore.logging.VoltLogger;
public class EstTimeUpdater {
//Report inconsistent update frequency at most every sixty seconds
public static final long maxErrorReportInterval = 60 * 1000;
public static long lastErrorReport = System.currentTimeMillis() - maxErrorReportInterval;
public static final int ESTIMATED_TIME_UPDATE_FREQUENCY = Integer.getInteger("ESTIMATED_TIME_UPDATE_FREQUENCY", 5);
public static final int ESTIMATED_TIME_WARN_INTERVAL = Integer.getInteger("ESTIMATED_TIME_WARN_INTERVAL", 2000);
public static volatile boolean pause = false;
private static final Thread updater = new Thread("Estimated Time Updater") {
@Override
public void run() {
while (true) {
try {
Thread.sleep(ESTIMATED_TIME_UPDATE_FREQUENCY);
} catch (InterruptedException e) {}
if (pause) continue;
Long delta = EstTimeUpdater.update(System.currentTimeMillis());
if ( delta != null ) {
new VoltLogger("HOST").info(delta +" estimated time update.");
}
}
}
};
static {
updater.setDaemon(true);
updater.start();
}
/**
* Don't call this unless you have paused the updater and intend to update yourself
* @param now
* @return
*/
public static Long update(final long now) {
final long estNow = EstTime.m_now;
if (estNow == now) {
return null;
}
EstTime.m_now = now;
/*
* Check if updating the estimated time was especially tardy.
* I am concerned that the thread responsible for updating the estimated
* time might be blocking on something and want to be able to log if
* that happens
*/
if (now - estNow > ESTIMATED_TIME_WARN_INTERVAL) {
/*
* Only report the error every 60 seconds to cut down on log spam
*/
if (lastErrorReport > now) {
//Time moves backwards on occasion, check and reset
lastErrorReport = now;
}
if (now - lastErrorReport > maxErrorReportInterval) {
lastErrorReport = now;
return now - estNow;
}
}
return null;
}
} |
package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.PrintStream;
import java.lang.StringBuilder;
import java.util.List;
import java.util.ArrayList;
public class BibliotecaAppTest {
@Test
public void testBibliotecaStartup() {
StringBuilder expectedOutput = new StringBuilder();
expectedOutput.append("Welcome to Biblioteca!\n");
expectedOutput.append("Main Menu (please select one of the following options by typing its number and pressing ENTER)\n");
expectedOutput.append("(1) List Books\n");
ByteArrayOutputStream outContent = initSystemOutStream();
BibliotecaApp.displayStartup();
assertEquals(expectedOutput.toString(), outContent.toString());
}
@Test
public void testSelectMenuOptionListBooks() {
StringBuilder expectedOutput = new StringBuilder();
expectedOutput.append(printBookList());
ByteArrayOutputStream outContent = initSystemOutStream();
BibliotecaApp.selectMenuOption(1);
assertEquals(expectedOutput.toString(), outContent.toString());
}
@Test
public void testSelectMenuOptionInvalidOption() {
StringBuilder expectedOutput = new StringBuilder();
expectedOutput.append("Select a valid option!");
ByteArrayOutputStream outContent = initSystemOutStream();
BibliotecaApp.selectMenuOption(-1);
assertEquals(expectedOutput.toString(), outContent.toString());
}
private ByteArrayOutputStream initSystemOutStream() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
return outContent;
}
private String printBookList() {
List<Book> bookList = generateBookList();
StringBuilder output = new StringBuilder();
output.append("Book List\n");
output.append(String.format("%-42s | %-32s | %-12s\n", "Title", "Author", "Year Published"));
String leftAlignFormat = "%-42s | %-32s | %-4d\n";
for (Book book : bookList) {
output.append(String.format(leftAlignFormat, book.getTitle(), book.getAuthor(), book.getYearPublished()));
}
return output.toString();
}
private List<Book> generateBookList() {
List<Book> bookList = new ArrayList<Book>();
bookList.add(new Book("Test-Driven Development By Example", "Kent Beck", 2003));
bookList.add(new Book("The Agile Samurai", "Jonathan Rasmusson", 2010));
bookList.add(new Book("Head First Java", "Kathy Sierra & Bert Bates", 2005));
bookList.add(new Book("Don't Make Me Think, Revisited", "Steve Krug", 2014));
return bookList;
}
} |
package at.rags.morpheus;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* AttributeMapper is used to map the json:api attribute node to
* your object fields.
* <p>
* You can create your own AttributeMapper and set it via {@link Morpheus#Morpheus(at.rags.morpheus.AttributeMapper)}.
*/
public class AttributeMapper {
private Deserializer deserializer;
private Gson gson;
public AttributeMapper() {
deserializer = new Deserializer();
gson = new Gson();
}
public AttributeMapper(Deserializer deserializer, Gson gson) {
this.deserializer = deserializer;
this.gson = gson;
}
/**
* Will map the attributes of the JSONAPI attribute object.
* JSONArrays will get mapped as {@literal List<Object>}.
* JSONObject will get mapped as {@literal ArrayMap<String, Object>}.
* Everything else will get mapped without changes.
*
* @param jsonApiResource Object extended with {@link Resource} that will get the field set.
* @param objClass
* @param attributesJsonObject {@link JSONObject} with json:api attributes object
* @param field Field that will be set.
* @param jsonFieldName Name of the json-field in attributesJsonObject to get data from.
*/
public void mapAttributeToObject(Resource jsonApiResource, Class<? extends Resource> objClass, JSONObject attributesJsonObject,
Field field, String jsonFieldName) {
Object object = null;
try {
object = attributesJsonObject.get(jsonFieldName);
} catch (JSONException e) {
Logger.debug("JSON attributes does not contain " + jsonFieldName);
return;
}
if (object instanceof JSONArray) {
List<Object> list = null;
try {
list = createListFromJSONArray(attributesJsonObject.getJSONArray(jsonFieldName), field);
} catch (JSONException e) {
Logger.debug(jsonFieldName + " is not an valid JSONArray.");
}
deserializer.setField(jsonApiResource, field.getName(), list);
} else if (object.getClass() == JSONObject.class) {
Object obj = gson.fromJson(object.toString(), field.getType());
deserializer.setField(jsonApiResource, field.getName(), obj);
} else if (!JSONObject.NULL.equals(object)) {
deserializer.setField(jsonApiResource, objClass, field.getName(), object);
}
}
/**
* Will loop through JSONArray and return values as List<Object>.
*
* @param jsonArray JSONArray with values.
* @return List<Object> of JSONArray values.
*/
private List<Object> createListFromJSONArray(JSONArray jsonArray, Field field) {
Type genericFieldType = field.getGenericType();
List<Object> objectArrayList = new ArrayList<>();
if (genericFieldType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
for (Type fieldArgType : fieldArgTypes) {
final Class fieldArgClass = (Class) fieldArgType;
for (int i = 0; jsonArray.length() > i; i++) {
Object obj = null;
Object jsonObject = null;
try {
jsonObject = jsonArray.get(i);
} catch (JSONException e) {
Logger.debug("JSONArray does not contain index " + i + ".");
continue;
}
// if this is a String, it wont use gson because it can throw a malformed json exception
// that case happens if there is a String with ":" in it.
if (fieldArgClass == String.class) {
obj = jsonObject.toString();
} else {
try {
obj = gson.fromJson(jsonArray.get(i).toString(), fieldArgClass);
} catch (JSONException e) {
Logger.debug("JSONArray does not contain index " + i + ".");
}
}
objectArrayList.add(obj);
}
}
}
return objectArrayList;
}
/**
* Will loop through JSONObject and return values as map.
*
* @param jsonObject JSONObject for meta.
* @return HashMap with meta values.
*/
public HashMap<String, Object> createMapFromJSONObject(JSONObject jsonObject) {
HashMap<String, Object> metaMap = new HashMap<>();
for (Iterator<String> iter = jsonObject.keys(); iter.hasNext(); ) {
String key = iter.next();
try {
metaMap.put(key, jsonObject.get(key));
} catch (JSONException e) {
Logger.debug("JSON does not contain " + key + ".");
}
}
return metaMap;
}
} |
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.inventory.AliquotBean;
import gov.nih.nci.calab.dto.inventory.ContainerBean;
import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.exception.InvalidSessionException;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* This class sets up session level or servlet context level variables to be used in
* various actions during the setup of query forms.
*
* @author pansu
*
*/
public class InitSessionSetup {
private static LookupService lookupService;
private static UserService userService;
private InitSessionSetup() throws Exception {
lookupService = new LookupService();
userService = new UserService(CalabConstants.CSM_APP_NAME);
}
public static InitSessionSetup getInstance() throws Exception {
return new InitSessionSetup();
}
public void setCurrentRun(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
String runId = (String) request.getParameter("runId");
if (runId == null && session.getAttribute("currentRun") == null) {
throw new InvalidSessionException(
"The session containing a run doesn't exists.");
} else if (runId == null && session.getAttribute("currentRun") != null) {
RunBean currentRun = (RunBean) session.getAttribute("currentRun");
runId = currentRun.getId();
}
if (session.getAttribute("currentRun") == null
|| session.getAttribute("newRunCreated") != null) {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
RunBean runBean = executeWorkflowService.getCurrentRun(runId);
session.setAttribute("currentRun", runBean);
}
session.removeAttribute("newRunCreated");
}
public void clearRunSession(HttpSession session) {
session.removeAttribute("currentRun");
}
public void setAllUsers(HttpSession session) throws Exception {
if ((session.getAttribute("newUserCreated") != null)
|| (session.getServletContext().getAttribute("allUsers") == null)) {
List allUsers = userService.getAllUsers();
session.getServletContext().setAttribute("allUsers", allUsers);
}
session.removeAttribute("newUserCreated");
}
public void setSampleSourceUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between sample source and samples that have unmasked aliquots
if (session.getAttribute("sampleSourceSamplesWithUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<SampleBean>> sampleSourceSamples = lookupService
.getSampleSourceSamplesWithUnmaskedAliquots();
session.setAttribute("sampleSourceSamplesWithUnmaskedAliquots",
sampleSourceSamples);
List<String> sources = new ArrayList<String>(sampleSourceSamples
.keySet());
session.setAttribute("allSampleSourcesWithUnmaskedAliquots",
sources);
}
setAllSampleUnmaskedAliquots(session);
session.removeAttribute("newAliquotCreated");
}
public void clearSampleSourcesWithUnmaskedAliquotsSession(
HttpSession session) {
session.removeAttribute("allSampleSourcesWithUnmaskedAliquots");
}
public void setAllSampleUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between samples and unmasked aliquots
if (session.getAttribute("allUnmaskedSampleAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<AliquotBean>> sampleAliquots = lookupService
.getUnmaskedSampleAliquots();
List<String> sampleNames = new ArrayList<String>(sampleAliquots
.keySet());
Collections.sort(sampleNames,
new CalabComparators.SortableNameComparator());
session.setAttribute("allUnmaskedSampleAliquots", sampleAliquots);
session.setAttribute("allSampleNamesWithAliquots", sampleNames);
}
session.removeAttribute("newAliquotCreated");
}
public void clearSampleUnmaskedAliquotsSession(HttpSession session) {
session.removeAttribute("allUnmaskedSampleAliquots");
session.removeAttribute("allSampleNamesWithAliquots");
}
public void setAllAssayTypeAssays(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.getServletContext().setAttribute("allAssayTypes",
assayTypes);
}
if (session.getServletContext().getAttribute("allAssayTypeAssays") == null) {
Map<String, SortedSet<AssayBean>> assayTypeAssays = lookupService
.getAllAssayTypeAssays();
List<String> assayTypes = new ArrayList<String>(assayTypeAssays
.keySet());
session.getServletContext().setAttribute("allAssayTypeAssays",
assayTypeAssays);
session.getServletContext().setAttribute("allAvailableAssayTypes",
assayTypes);
}
}
public void setAllSampleSources(HttpSession session) throws Exception {
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = lookupService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleSourcesSession(HttpSession session) {
session.removeAttribute("allSampleSources");
}
public void setAllSampleContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allSampleContainerTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List containerTypes = lookupService.getAllSampleContainerTypes();
session.setAttribute("allSampleContainerTypes", containerTypes);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainerTypesSession(HttpSession session) {
session.removeAttribute("allSampleContainerTypes");
}
public void setAllSampleTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.getServletContext().setAttribute("allSampleTypes",
sampleTypes);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleTypesSession(HttpSession session) {
session.removeAttribute("allSampleTypes");
}
public void setAllSampleSOPs(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSampleSOPs") == null) {
List sampleSOPs = lookupService.getAllSampleSOPs();
session.getServletContext().setAttribute("allSampleSOPs",
sampleSOPs);
}
}
public void setAllSampleContainerInfo(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("sampleContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.getServletContext().setAttribute("sampleContainerInfo",
containerInfo);
}
}
public void setCurrentUser(HttpSession session) throws Exception {
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
UserBean user = (UserBean) session.getAttribute("user");
creator = user.getLoginName();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
}
public void setAllAliquotContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allAliquotContainerTypes") == null
|| session.getAttribute("newAliquotCreated") != null) {
List containerTypes = lookupService.getAllAliquotContainerTypes();
session.setAttribute("allAliquotContainerTypes", containerTypes);
}
}
public void clearAliquotContainerTypesSession(HttpSession session) {
session.removeAttribute("allAliquotContainerTypes");
}
public void setAllAliquotContainerInfo(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.getServletContext().setAttribute("aliquotContainerInfo",
containerInfo);
}
}
public void setAllAliquotCreateMethods(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) {
List methods = lookupService.getAliquotCreateMethods();
session.getServletContext().setAttribute("aliquotCreateMethods",
methods);
}
}
public void setAllSampleContainers(HttpSession session) throws Exception {
if (session.getAttribute("allSampleContainers") == null
|| session.getAttribute("newSampleCreated") != null) {
Map<String, SortedSet<ContainerBean>> sampleContainers = lookupService
.getAllSampleContainers();
List<String> sampleNames = new ArrayList<String>(sampleContainers
.keySet());
Collections.sort(sampleNames,
new CalabComparators.SortableNameComparator());
session.setAttribute("allSampleContainers", sampleContainers);
session.setAttribute("allSampleNames", sampleNames);
}
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainersSession(HttpSession session) {
session.removeAttribute("allSampleContainers");
session.removeAttribute("allSampleNames");
}
public void setAllSourceSampleIds(HttpSession session) throws Exception {
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = lookupService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSourceSampleIdsSession(HttpSession session) {
session.removeAttribute("allSourceSampleIds");
}
public void clearWorkflowSession(HttpSession session) {
clearRunSession(session);
clearSampleSourcesWithUnmaskedAliquotsSession(session);
clearSampleUnmaskedAliquotsSession(session);
session.removeAttribute("httpFileUploadSessionData");
}
public void clearSearchSession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainerTypesSession(session);
clearAliquotContainerTypesSession(session);
clearSourceSampleIdsSession(session);
clearSampleSourcesSession(session);
session.removeAttribute("aliquots");
session.removeAttribute("sampleContainers");
}
public void clearInventorySession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainersSession(session);
clearSampleContainerTypesSession(session);
clearSampleUnmaskedAliquotsSession(session);
clearAliquotContainerTypesSession(session);
session.removeAttribute("createSampleForm");
session.removeAttribute("createAliquotForm");
session.removeAttribute("aliquotMatrix");
}
public static LookupService getLookupService() {
return lookupService;
}
public static UserService getUserService() {
return userService;
}
} |
package nakadi;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
class ResourceSupport {
public static final String CHARSET_UTF_8 = "UTF-8";
public static final String APPLICATION_JSON_CHARSET_UTF_8 =
"application/json; charset=" + CHARSET_UTF_8;
static String nextEid() {
return UUID.randomUUID().toString();
}
static String nextFlowId() {
return String.format("njc-%d-%016x", System.currentTimeMillis(),
ThreadLocalRandom.current().nextLong());
}
public static ResourceOptions options(String accept) {
return new ResourceOptions()
.header(ResourceOptions.HEADER_ACCEPT, accept)
.header(ResourceOptions.HEADER_ACCEPT_CHARSET, CHARSET_UTF_8)
.header("User-Agent", NakadiClient.USER_AGENT)
.flowId(ResourceSupport.nextFlowId());
}
public static ResourceOptions optionsWithJsonContent(ResourceOptions options) {
return options.header(ResourceOptions.HEADER_CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8);
}
} |
package jade.tools.introspector.gui;
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
/**
This panel contains the behaviour tree for a given agent. It adds a
TreeMouseListener component to the tree.
@author Andrea Squeri, - Universita` di Parma
*/
public class BehaviourPanel extends JSplitPane{
private JTree behaviourTree;
private JTextArea text;
private JScrollPane behaviourScroll;
private JScrollPane textScroll;
private JPanel treePanel;
private TreeMouseListener treeListener;
private Icon runningIcon;
private Icon blockedIcon;
public BehaviourPanel(DefaultTreeModel model ){
super();
behaviourTree=new JTree(model);
treeListener = new TreeMouseListener(this);
behaviourTree.addMouseListener(treeListener);
behaviourTree.setCellRenderer(new BehaviourCellRenderer());
this.build();
}
public void build(){
text=new JTextArea();
behaviourScroll=new JScrollPane();
textScroll=new JScrollPane();
treePanel=new JPanel();
treePanel.setLayout(new BorderLayout());
runningIcon = new ImageIcon(getClass().getResource("images/behaviour.gif"));
blockedIcon = new ImageIcon(getClass().getResource("images/blocked.gif"));
//behaviorTree.addMouseListener(new TreeListener);
behaviourTree.putClientProperty("JTree.lineStyle","Angled");
behaviourTree.setShowsRootHandles(true);
DefaultTreeCellRenderer rend = (DefaultTreeCellRenderer)behaviourTree.getCellRenderer();
rend.setLeafIcon(runningIcon);
rend.setOpenIcon(runningIcon);
rend.setClosedIcon(runningIcon);
treePanel.add(behaviourTree,BorderLayout.CENTER);
behaviourScroll.getViewport().add(treePanel,null);
textScroll.getViewport().add(text,null);
// behaviourScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//textScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(behaviourScroll,JSplitPane.LEFT);
this.add(textScroll,JSplitPane.RIGHT);
this.setContinuousLayout(true);
this.setDividerLocation(200);
}
public JTree getBehaviourTree(){
return behaviourTree;
}
public JTextArea getBehaviourText(){
return text;
}
/**
* The BehaviourCellRenderer class manages rendering nodes in the
* behaviour tree.
*/
class BehaviourCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
// Try to cast the object to a default mutable tree node.
// If we succeed, try to cast the user object to a behaviour
// tree node. If this succeeds, check the status of the object.
try
{
DefaultMutableTreeNode mut = (DefaultMutableTreeNode)value;
BehaviourTreeNode node = (BehaviourTreeNode)mut.getUserObject();
if (node.isBlocked()) {
changeIcon(blockedIcon);
} else {
changeIcon(runningIcon);
}
}
catch(Exception e)
{
setLeafIcon(getDefaultLeafIcon());
setOpenIcon(getDefaultOpenIcon());
setClosedIcon(getDefaultClosedIcon());
}
return super.getTreeCellRendererComponent(tree,
value,
sel,
expanded,
leaf,
row,
hasFocus);
}
private void changeIcon(Icon ico) {
setOpenIcon(ico);
setLeafIcon(ico);
setClosedIcon(ico);
}
}
} |
package com.tepidpond.tum.PlateTectonics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Util {
public static class ImageViewer {
private static final int maxInstances = 32;
private static ImageViewer _instances[] = new ImageViewer[maxInstances];
private JFrame frame;
private JLabel label;
private ImageViewer() { this(0); }
private ImageViewer(int index) {
if (index < 0 || index >= maxInstances)
throw new IllegalArgumentException(String.format("You only get %d instances of the viewer.", maxInstances));
_instances[index] = this;
if (index == 0)
frame = new JFrame(String.format("Image Viewer %d", index));
else
frame = new JFrame("Image Viewer");
label = new JLabel();
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
Hide(index);
}
public static void DisplayImage(BufferedImage bi) { DisplayImage(bi, 0); }
public static void DisplayImage(BufferedImage bi, int index) {
if (_instances[index] == null) _instances[index] = new ImageViewer(index);
_instances[index].label.setIcon(new ImageIcon(bi));
Insets ins = _instances[index].frame.getInsets();
_instances[index].frame.setSize(
bi.getWidth() + ins.left + ins.right,
bi.getHeight() + ins.bottom + ins.top);
Show(index);
}
public static void SetCaption(String caption) { SetCaption(caption, 0); }
public static void SetCaption(String caption, int index) {
if (_instances[index] == null) _instances[index] = new ImageViewer(index);
_instances[index].frame.setTitle(String.format("Image Viewer %d - ", index) + caption);
}
public static void Hide() { Hide(0); }
public static void Hide(int index) {
if (_instances[index] == null) _instances[index] = new ImageViewer(index);
_instances[index].frame.setVisible(false);
}
public static void Show() { Show(0); }
public static void Show(int index) {
if (_instances[index] == null) _instances[index] = new ImageViewer(index);
if (!_instances[index].frame.isVisible())
_instances[index].frame.setVisible(true);
}
}
// TODO: Derived from Google search. May be horribly wrong.
public static final float FLT_EPSILON = 1.19209290e-07f;
public static final int getTile(int x, int y, int mapSize) {
// heightmap is a torus
return getTile(x, y, mapSize, mapSize);
}
public static final int getTile(int x, int y, int mapWidth, int mapHeight) {
// heightmap is a torus
return ((y % mapHeight) * mapWidth + (x % mapWidth));
}
public static final int getX(int mapTile, int mapWidth) {
return (mapTile % mapWidth);
}
public static final int getY(int mapTile, int mapWidth) {
return mapTile / mapWidth;
}
public static float quadInterpolate(float[] map, int mapSideLength, float X, float Y) {
// round to nearest int
int mapOriginX = (int)Math.round(X);
int mapOriginY = (int)Math.round(Y);
// save fractional part for interpolating
X -= mapOriginX; Y -= mapOriginY;
// wrap into range (0,511)
mapOriginX %= mapSideLength; if (mapOriginX < 0) mapOriginX += mapSideLength;
mapOriginY %= mapSideLength; if (mapOriginY < 0) mapOriginY += mapSideLength;
// select x/y coordinates for points a(x0, y0), b(x1, y0), c(x0, y1), d(x1, y1)
// Wrapping at edges is most natural.
int x0 = mapOriginX, y0 = mapOriginY, x1, y1;
if (X > 0) {
x1 = (mapOriginX + 1) % mapSideLength;
} else {
x1 = mapOriginX == 0 ? mapSideLength - 1: mapOriginX - 1;
X = -X;
}
if (Y > 0) {
y1 = (mapOriginY + 1) % mapSideLength;
} else {
y1 = mapOriginY == 0 ? mapSideLength - 1: mapOriginY - 1;
Y = -Y;
}
// Calc indices for the points in the heightMap.
float a = map[Util.getTile(x0, y0, mapSideLength)];
float b = map[Util.getTile(x1, y0, mapSideLength)];
float c = map[Util.getTile(x0, y1, mapSideLength)];
float d = map[Util.getTile(x1, y1, mapSideLength)];
assert (x0 >= 0 && x0 < mapSideLength && x1 >= 0 && x1 < mapSideLength && x0 >= 0 && y0 < mapSideLength):
"Impossibilities in quadInterpolate, failed validation.";
// quadratic interpolation: a + (b-a)x + (c-a)y + (a-b-c+d)xy
return a + (b - a) * X + (c - a) * Y + (a + d - (b + c)) * X * Y;
}
public static BufferedImage renderIntmap(int intMap[], int mapWidth, int mapHeight) {
BufferedImage bi = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
int mapMin = Integer.MAX_VALUE;
int mapMax = 0;
for(int i = 0; i < intMap.length; i++) {
if (mapMin > intMap[i]) mapMin = intMap[i];
if (mapMax < intMap[i]) mapMax = intMap[i];
}
if (mapMin == mapMax || mapMax == Integer.MAX_VALUE || mapMin == Integer.MAX_VALUE)
return bi;
for (int x=0; x<mapWidth; x++) {
for (int y=0; y<mapHeight; y++) {
float h = intMap[getTile(x, y, mapWidth, mapHeight)];
h -= mapMin;
h /= (mapMax - mapMin);
g.setColor(new Color(h, h, h));
g.drawLine(x, y, x, y);
}
}
return bi;
}
public static BufferedImage renderHeightmap(float heightMap[], int mapWidth, int mapHeight) {
float hm[] = heightMap; //normalizeHeightMapCopy(heightMap);
BufferedImage bi = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
float COLOR_STEP = 1.5f;
for (int x=0; x<mapWidth; x++) {
for (int y=0; y<mapHeight; y++) {
float h = hm[getTile(x, y, mapWidth, mapHeight)];
if (h < 2 * FLT_EPSILON)
g.setColor(new Color(1, 0, 0));
else if (h < 0.5)
g.setColor(new Color(0.0f, 0.0f, 0.25f + 1.5f * h));
else if (h < 1.0)
g.setColor(new Color(0, 2 * (h - 0.5f), 1.0f));
else {
h -= 1.0;
if (h < COLOR_STEP)
g.setColor(new Color(0f, 0.5f + 0.5f * h / COLOR_STEP, 0f));
else if (h < 1.5 * COLOR_STEP)
g.setColor(new Color(2f * (h - COLOR_STEP) / COLOR_STEP, 1.0f, 0));
else if (h < 2.0 * COLOR_STEP)
g.setColor(new Color(1.0f, 1.0f - (h - 1.5f * COLOR_STEP) / COLOR_STEP, 0));
else if (h < 3.0 * COLOR_STEP)
g.setColor(new Color(1.0f - 0.5f * (h - 2.0f * COLOR_STEP) / COLOR_STEP, 0.5f - 0.25f * (h - 2.0f * COLOR_STEP) / COLOR_STEP, 0));
else if (h < 5.0 * COLOR_STEP)
g.setColor(new Color(
0.5f - 0.125f * (h - 3.0f * COLOR_STEP) / (2f * COLOR_STEP),
0.25f + 0.125f * (h - 3.0f * COLOR_STEP) / (2f * COLOR_STEP),
0.375f * (h - 3.0f * COLOR_STEP) / (2f * COLOR_STEP)));
else if (h < 8.0 * COLOR_STEP)
g.setColor(new Color(
0.375f + 0.625f * (h - 5.0f * COLOR_STEP) / (3f * COLOR_STEP),
0.375f + 0.625f * (h - 5.0f * COLOR_STEP) / (3f * COLOR_STEP),
0.375f + 0.625f * (h - 5.0f * COLOR_STEP) / (3f * COLOR_STEP)));
else
g.setColor(new Color(1, 1, 1));
}
g.drawLine(x, y, x, y);
}
}
return bi;
}
public static final void displayHeightmap(float heightMap[], int mapWidth, String tag) {
displayImage(renderHeightmap(heightMap, mapWidth, mapWidth), tag);
}
public static final void displayHeightmap(int index, float heightMap[], int mapWidth, int mapHeight, String tag) {
displayImage(renderHeightmap(heightMap, mapWidth, mapHeight), index, tag);
}
public static final void displayIntmap(int Intmap[], int mapWidth, String tag) {
displayImage(renderIntmap(Intmap, mapWidth, mapWidth), tag);
}
public static final void displayIntmap(int Intmap[], int mapWidth, int mapHeight, String tag) {
displayImage(renderIntmap(Intmap, mapWidth, mapHeight), tag);
}
public static final void saveHeightmap(float heightMap[], int mapWidth, String tag) {
saveImage(renderHeightmap(heightMap, mapWidth, mapWidth), tag);
}
public static final void saveHeightmap(float heightMap[], int mapWidth, int mapHeight, String tag) {
saveImage(renderHeightmap(heightMap, mapWidth, mapHeight), tag);
}
public static final void saveIntmap(int Intmap[], int mapWidth, String tag) {
saveImage(renderIntmap(Intmap, mapWidth, mapWidth), tag);
}
public static final void saveIntmap(int Intmap[], int mapWidth, int mapHeight, String tag) {
saveImage(renderIntmap(Intmap, mapWidth, mapHeight), tag);
}
public static final void displayImage(BufferedImage bi, String tag) { displayImage(bi, 0, tag); }
public static final void displayImage(BufferedImage bi, int index, String tag) {
ImageViewer.DisplayImage(bi, index);
ImageViewer.SetCaption(tag, index);
}
public static final void saveImage(BufferedImage bi, String tag) {
try {
File o = new File("HM" + Long.toString(System.currentTimeMillis()) + "." + tag + ".png");
ImageIO.write(bi, "PNG", o);
} catch (Exception e) {
System.out.println("Error saving heightmap.png because: " + e.getMessage());
}
}
// force values in the heightMap into a standard [0.0f ... 1.0f] range.
public static void normalizeHeightMap(float heightMap[]) {
int mapArea = heightMap.length;
float minHeight = heightMap[0], maxHeight = heightMap[0];
for (int i = 1; i < mapArea; i++) {
if (heightMap[i] < minHeight) minHeight = heightMap[i];
if (heightMap[i] > maxHeight) maxHeight = heightMap[i];
}
float scaleFactor = maxHeight - minHeight;
//if (min != 0.0f) minHeight -= min;
//if (min != 0.0f || max != 1.0f) scaleFactor /= (max - min);
for (int i = 0; i < mapArea; i++) {
heightMap[i] = (heightMap[i] - minHeight) / scaleFactor;
}
}
// force values in the heightMap into a standard [0.0f ... 1.0f] range.
public static float[] normalizeHeightMapCopy(float heightMap[]) {
float tmpHM[] = new float[heightMap.length];
System.arraycopy(heightMap, 0, tmpHM, 0, heightMap.length);
normalizeHeightMap(tmpHM);
return tmpHM;
}
} |
package org.apache.commons.lang;
import java.util.Iterator;
import java.util.Map;
/**
* <p>Performs basic variable interpolation on a String for variables within a Map.
* Variables of the form, ${var}, are supported.</p>
*
* @author Ken Fitzpatrick
* @author Henri Yandell
* @since 2.1
* @version $Id: Interpolation.java,v 1.3 2004/09/01 17:41:41 ggregory Exp $
*/
public class Interpolation {
/** The marker used to start a variable. */
private static final String SYMBOLIC_VALUE_MARKER_START = "${";
/** The marker used to end a variable. */
private static final String SYMBOLIC_VALUE_MARKER_END = "}";
/**
* <p>Interpolates a String to replace variables of the form <code>${...}</code>.</p>
*
* <p>This method is useful for enabling simple strings to be modified based
* on a map of data. A typical use case might be to add data from configuration
* to an error message. This method, and this class, does not seek to replace
* full interpolation mechanisms, for example Velocity.</p>
*
* <p>The expected format of <code>templateString</code> is:
* <code><pre>
* The ${animal} jumped over the ${target}.
* </pre></code>
* such that the key/value pairs found in <code>values</code>
* are substituted into the string at the <code>${key-name}</code> markers.
* In the above example, <code>valuesMap</code> could have been populated as:
* <code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "quick brown fox" );
* valuesMap.put( "target", "lazy dog" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap );
* </pre></code>
* yielding:
* <code><pre>
* The quick brown fox jumped over the lazy dog.
* </pre></code></p>
*
* <p>The same <code>templateString</code> from the above example could be reused as:
* <code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "cow" );
* valuesMap.put( "target", "moon" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap );
* </pre></code>
* yielding:
* <code><pre>
* The cow jumped over the moon.
* </pre></code></p>
*
* <p>The value of <code>templateString</code> is returned in an unaltered
* if <code>templateString</code> is null, empty, or contains no marked variables
* that can be resolved by the key/value pairs found in <code>valuesMap</code>,
* or if <code>valuesMap</code> is null, empty or has no key/value pairs that can be
* applied to the marked variables within <code>templateString</code>.</p>
*
* <p>If a <code>valuesMap</code> value is null, it will be treated as "".</p>
*
* @param templateString String containing any mixture of variable and non-variable
* content, to be used as a template for the value substitution process
* @param valuesMap Map containing the key/value pairs to be used to resolve
* the values of the marked variables found within <code>templateString</code>
* @return the interpolated String
*/
public static String interpolate(String templateString, Map valuesMap) {
// pre-conditions
if (templateString == null || valuesMap == null ||
templateString.length() == 0 || valuesMap.isEmpty()) {
return templateString;
}
// default the returned String to the templateString
String returnString = templateString;
String nextKey = null;
String substitutionValue = null;
String nextValueToBeSubstituted = null;
// get a list of substitution valuesMap
Iterator keys = valuesMap.keySet().iterator();
while (keys.hasNext()) {
nextKey = (String) keys.next();
substitutionValue = StringUtils.defaultString((String) valuesMap.get(nextKey));
nextValueToBeSubstituted = SYMBOLIC_VALUE_MARKER_START + nextKey + SYMBOLIC_VALUE_MARKER_END;
returnString = StringUtils.replace(returnString, nextValueToBeSubstituted, substitutionValue);
}
return returnString;
}
/**
* <p>Interpolates a String to replace variables of the form <code>${...}</code>
* where the replace strings may also contain variables to interpolate.</p>
*
* <p>This method is useful for enabling simple strings to be modified based
* on a map of data. A typical use case might be to add data from configuration
* to an error message. This method, and this class, does not seek to replace
* full interpolation mechanisms, for example Velocity.</p>
*
* <p>This method calls {@link #interpolate(String, Map)} repeatedly until the
* returned string does not change. This has the effect of allowing the replace
* strings in <code>valuesMap</code> to contain variables that should also be
* interpolated.</p>
*
* <p>The expected format of <code>templateString</code> is:
* <code><pre>
* The ${animal} jumped over the ${target}.
* </pre></code>
* such that the key/value pairs found in <code>values</code> are substituted into the string at the
* <code>${key-name}</code> markers. In the above example, <code>valuesMap</code>
* could have been populated as:
* <code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "${critter}" );
* valuesMap.put( "target", "${pet}" );
* valuesMap.put( "pet", "${petCharacteristic} dog" );
* valuesMap.put( "petCharacteristic", "lazy" );
* valuesMap.put( "critter", "${critterSpeed} ${critterColor} ${critterType}" );
* valuesMap.put( "critterSpeed", "quick" );
* valuesMap.put( "critterColor", "brown" );
* valuesMap.put( "critterType", "fox" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap, true );
* </pre></code>
* yielding:
* <code><pre>
* The quick brown fox jumped over the lazy dog.
* </pre></code></p>
*
* <p>The value of <code>templateString</code> is returned in an unaltered
* if <code>templateString</code> is null, empty, or contains no marked variables
* that can be resolved by the key/value pairs found in <code>valuesMap</code>,
* or if <code>valuesMap</code> is null, empty or has no key/value pairs that can be
* applied to the marked variables within <code>templateString</code>.</p>
*
* <p>If a <code>valuesMap</code> value is null, it will be treated as "".</p>
*
* @param templateString String containing any mixture of variable and non-variable
* content, to be used as a template for the value substitution process
* @param valuesMap Map containing the key/value pairs to be used to resolve
* the values of the marked variables found within <code>templateString</code>
* @return the interpolated String
*/
public static String interpolateRepeatedly(String templateString, Map valuesMap) {
// pre-conditions
if (templateString == null || valuesMap == null ||
templateString.length() == 0 || valuesMap.isEmpty()) {
return templateString;
}
String currentResult = templateString;
String previousResult = null;
while (!StringUtils.equals(currentResult, previousResult)) {
previousResult = currentResult;
currentResult = Interpolation.interpolate(previousResult, valuesMap);
}
return currentResult;
}
} |
package org.apache.velocity.anakia;
import java.util.Iterator;
import java.util.Vector;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
/**
* This class allows you to walk a tree of JDOM Element objects.
* It first walks the tree itself starting at the Element passed
* into allElements() and stores each node of the tree
* in a Vector which allElements() returns as a result of its
* execution. You can then use a #foreach in Velocity to walk
* over the Vector and visit each Element node.
*
* @author <a href="jon@latchkey.com">Jon S. Stevens</a>
* @version $Id: TreeWalker.java,v 1.2 2000/12/20 07:19:00 jvanzyl Exp $
*/
public class TreeWalker
{
/** the cache of Element objects */
private Vector theElements = null;
/**
* Empty constructor
*/
public TreeWalker()
{
// Left blank
}
/**
* Creates a new Vector and walks the Element tree.
*
* @param Element the starting Element node
* @return Vector a vector of Element nodes
*/
public Vector allElements(Element e)
{
theElements = new Vector();
treeWalk (e);
return this.theElements;
}
/**
* A recursive method to walk the Element tree.
* @param Element the current Element
*/
private final void treeWalk(Element e)
{
for (Iterator i=e.getChildren().iterator(); i.hasNext(); )
{
Element child = (Element)i.next();
theElements.add(child);
treeWalk(child);
}
}
} |
package scal.io.liger;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.android.vending.expansion.zipfile.ZipResourceFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import scal.io.liger.model.ContentPackMetadata;
import scal.io.liger.model.ExpansionIndexItem;
import scal.io.liger.model.InstanceIndexItem;
import scal.io.liger.model.StoryPath;
import scal.io.liger.model.StoryPathLibrary;
public class IndexManager {
private static String availableIndexName = "available_index.json";
private static String installedIndexName = "installed_index.json";
private static String instanceIndexName = "instance_index.json";
private static String contentIndexName = "content_index.json";
private static String contentMetadataName = "content_metadata.json";
public static String noPatchFile = "NOPATCH";
public static String buildFileName(ExpansionIndexItem item, String mainOrPatch) {
if (Constants.MAIN.equals(mainOrPatch)) {
return item.getExpansionId() + "." + mainOrPatch + "." + item.getExpansionFileVersion() + ".obb";
} else if (Constants.PATCH.equals(mainOrPatch)) {
if (item.getPatchFileVersion() == null) {
// not really an error, removing message
// Log.d("INDEX", "CAN'T CONSTRUCT FILENAME FOR " + item.getExpansionId() + ", PATCH VERSION IS NULL");
return noPatchFile;
} else {
return item.getExpansionId() + "." + mainOrPatch + "." + item.getPatchFileVersion() + ".obb";
}
} else {
Log.d("INDEX", "CAN'T CONSTRUCT FILENAME FOR " + item.getExpansionId() + ", DON'T UNDERSTAND " + mainOrPatch);
// this is not the same as having no patch
// return noPatchFile;
return "FOO";
}
}
public static String buildFilePath(ExpansionIndexItem item) {
String checkPath = Environment.getExternalStorageDirectory().toString() + File.separator + item.getExpansionFilePath();
File checkDir = new File(checkPath);
if (checkDir.isDirectory() || checkDir.mkdirs()) {
return checkPath;
} else {
Log.d("INDEX", "CAN'T CONSTRUCT PATH FOR " + item.getExpansionId() + ", PATH " + item.getExpansionFilePath() + " DOES NOT EXIST AND COULD NOT BE CREATED");
return null;
}
}
public static void copyAvailableIndex(Context context) {
copyIndex(context, availableIndexName);
return;
}
public static void copyInstalledIndex(Context context) {
copyIndex(context, installedIndexName);
return;
}
// instance and content index shouldn't be part of assets
private static void copyIndex(Context context, String jsonFileName) {
AssetManager assetManager = context.getAssets();
String jsonFilePath = ZipHelper.getFileFolderName(context);
Log.d("INDEX", "COPYING JSON FILE " + jsonFileName + " FROM ASSETS TO " + jsonFilePath);
File jsonFile = new File(jsonFilePath + jsonFileName);
// do not replace installed index
if (jsonFileName.equals(availableIndexName) && jsonFile.exists()) {
Log.d("INDEX", "JSON FILE " + jsonFileName + " ALREADY EXISTS IN " + jsonFilePath + ", DELETING");
jsonFile.delete();
}
if (jsonFileName.equals(installedIndexName) && jsonFile.exists()) {
Log.d("INDEX", "JSON FILE " + jsonFileName + " ALREADY EXISTS IN " + jsonFilePath + ", NOT COPYING");
return;
}
InputStream assetIn = null;
OutputStream assetOut = null;
try {
assetIn = assetManager.open(jsonFileName);
assetOut = new FileOutputStream(jsonFile);
byte[] buffer = new byte[1024];
int read;
while ((read = assetIn.read(buffer)) != -1) {
assetOut.write(buffer, 0, read);
}
assetIn.close();
assetIn = null;
assetOut.flush();
assetOut.close();
assetOut = null;
} catch (IOException ioe) {
Log.e("INDEX", "COPYING JSON FILE " + jsonFileName + " FROM ASSETS TO " + jsonFilePath + " FAILED");
return;
}
// check for zero-byte files
if (jsonFile.exists() && (jsonFile.length() == 0)) {
Log.e("INDEX", "COPYING JSON FILE " + jsonFileName + " FROM ASSETS TO " + jsonFilePath + " FAILED (FILE WAS ZERO BYTES)");
jsonFile.delete();
}
return;
}
// need to move this elsewhere
public static File copyThumbnail(Context context, String thumbnailFileName) {
AssetManager assetManager = context.getAssets();
String thumbnailFilePath = ZipHelper.getFileFolderName(context);
Log.d("INDEX", "COPYING THUMBNAIL FILE " + thumbnailFileName + " FROM ASSETS TO " + thumbnailFilePath);
File thumbnailFile = new File(thumbnailFilePath + thumbnailFileName);
if (thumbnailFile.exists()) {
Log.d("INDEX", "THUMBNAIL FILE " + thumbnailFileName + " ALREADY EXISTS IN " + thumbnailFilePath + ", DELETING");
thumbnailFile.delete();
}
File thumbnailDirectory = new File(thumbnailFile.getParent());
if (!thumbnailDirectory.exists()) {
thumbnailDirectory.mkdirs();
}
InputStream assetIn = null;
OutputStream assetOut = null;
try {
assetIn = assetManager.open(thumbnailFileName);
assetOut = new FileOutputStream(thumbnailFile);
byte[] buffer = new byte[1024];
int read;
while ((read = assetIn.read(buffer)) != -1) {
assetOut.write(buffer, 0, read);
}
assetIn.close();
assetIn = null;
assetOut.flush();
assetOut.close();
assetOut = null;
} catch (IOException ioe) {
Log.e("INDEX", "COPYING THUMBNAIL FILE " + thumbnailFileName + " FROM ASSETS TO " + thumbnailFilePath + " FAILED: " + ioe.getLocalizedMessage());
return null;
}
// check for zero-byte files
if (thumbnailFile.exists() && (thumbnailFile.length() == 0)) {
Log.e("INDEX", "COPYING THUMBNAIL FILE " + thumbnailFileName + " FROM ASSETS TO " + thumbnailFilePath + " FAILED (FILE WAS ZERO BYTES)");
thumbnailFile.delete();
return null;
}
return thumbnailFile;
}
public static HashMap<String, ExpansionIndexItem> loadAvailableFileIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, availableIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
// construct name (index by main file names)
String fileName = buildFileName(item, Constants.MAIN);
indexMap.put(fileName, item);
}
return indexMap;
}
public static HashMap<String, ExpansionIndexItem> loadInstalledFileIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, installedIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
// construct name (index by main file names)
String fileName = buildFileName(item, Constants.MAIN);
indexMap.put(fileName, item);
}
return indexMap;
}
public static HashMap<String, ExpansionIndexItem> loadAvailableOrderIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, availableIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
indexMap.put(item.getPatchOrder(), item);
}
return indexMap;
}
public static HashMap<String, ExpansionIndexItem> loadInstalledOrderIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, installedIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
indexMap.put(item.getPatchOrder(), item);
}
return indexMap;
}
public static HashMap<String, ExpansionIndexItem> loadAvailableIdIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, availableIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
indexMap.put(item.getExpansionId(), item);
}
return indexMap;
}
public static HashMap<String, ExpansionIndexItem> loadInstalledIdIndex(Context context) {
ArrayList<ExpansionIndexItem> indexList = loadIndex(context, installedIndexName);
HashMap<String, ExpansionIndexItem> indexMap = new HashMap<String, ExpansionIndexItem>();
for (ExpansionIndexItem item : indexList) {
indexMap.put(item.getExpansionId(), item);
}
return indexMap;
}
// supressing messages for less text during polling
private static ArrayList<ExpansionIndexItem> loadIndex(Context context, String jsonFileName) {
String indexJson = null;
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
String jsonFilePath = ZipHelper.getFileFolderName(context);
// Log.d("INDEX", "READING JSON FILE " + jsonFilePath + jsonFileName + " FROM SD CARD");
File jsonFile = new File(jsonFilePath + jsonFileName);
if (!jsonFile.exists()) {
Log.e("INDEX", jsonFilePath + jsonFileName + " WAS NOT FOUND");
return indexList;
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(jsonFile);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonStream = null;
indexJson = new String(buffer);
} catch (IOException ioe) {
Log.e("INDEX", "READING JSON FILE " + jsonFilePath + jsonFileName + " FROM SD CARD FAILED");
return indexList;
}
} else {
Log.e("INDEX", "SD CARD WAS NOT FOUND");
return indexList;
}
if ((indexJson != null) && (indexJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
indexList = gson.fromJson(indexJson, new TypeToken<ArrayList<ExpansionIndexItem>>() {
}.getType());
}
return indexList;
}
// only one key option for instance index
public static HashMap<String, InstanceIndexItem> loadInstanceIndex(Context context) {
HashMap<String, InstanceIndexItem> indexMap = new HashMap<String, InstanceIndexItem>();
String indexJson = null;
ArrayList<InstanceIndexItem> indexList = new ArrayList<InstanceIndexItem>();
String jsonFilePath = ZipHelper.getFileFolderName(context);
Log.d("INDEX", "READING JSON FILE " + jsonFilePath + instanceIndexName + " FROM SD CARD");
File jsonFile = new File(jsonFilePath + instanceIndexName);
if (!jsonFile.exists()) {
Log.d("INDEX", jsonFilePath + instanceIndexName + " WAS NOT FOUND");
} else {
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(jsonFile);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonStream = null;
indexJson = new String(buffer);
} catch (IOException ioe) {
Log.e("INDEX", "READING JSON FILE " + jsonFilePath + instanceIndexName + " FROM SD CARD FAILED");
}
} else {
Log.e("INDEX", "SD CARD WAS NOT FOUND");
return indexMap; // if there's no card, there's nowhere to read instance files from, so just stop here
}
if ((indexJson != null) && (indexJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
indexList = gson.fromJson(indexJson, new TypeToken<ArrayList<InstanceIndexItem>>() {
}.getType());
}
for (InstanceIndexItem item : indexList) {
indexMap.put(item.getInstanceFilePath(), item);
}
}
return indexMap;
}
// only one key option for content index, file is loaded from a zipped content pack
// content index is read only, no register/update/save methods
// TODO this should leverage the loadContentIndexAsList to avoid dupliction
public static HashMap<String, InstanceIndexItem> loadContentIndex(Context context, String packageName, String expansionId, String language) {
String contentJson = null;
ArrayList<InstanceIndexItem> contentList = new ArrayList<InstanceIndexItem>();
HashMap<String, InstanceIndexItem> contentMap = new HashMap<String, InstanceIndexItem>();
String contentPath = packageName + File.separator + expansionId + File.separator + contentIndexName;
Log.d("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE");
try {
InputStream jsonStream = ZipHelper.getFileInputStream(contentPath, context, language);
if (jsonStream == null) {
Log.e("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE FAILED (STREAM WAS NULL)");
return contentMap;
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
contentJson = new String(buffer);
if ((contentJson != null) && (contentJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
contentList = gson.fromJson(contentJson, new TypeToken<ArrayList<InstanceIndexItem>>() {
}.getType());
}
for (InstanceIndexItem item : contentList) {
contentMap.put(item.getInstanceFilePath(), item);
}
} catch (IOException ioe) {
Log.e("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE FAILED: " + ioe.getMessage());
return contentMap;
}
return contentMap;
}
// only one key option for content index, file is loaded from a zipped content pack
// content index is read only, no register/update/save methods
public static ArrayList<InstanceIndexItem> loadContentIndexAsList(Context context, String packageName, String expansionId, String language) {
String contentJson = null;
ArrayList<InstanceIndexItem> contentList = new ArrayList<InstanceIndexItem>();
String contentPath = packageName + File.separator + expansionId + File.separator + contentIndexName;
Log.d("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE");
try {
InputStream jsonStream = ZipHelper.getFileInputStream(contentPath, context, language);
if (jsonStream == null) {
Log.e("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE FAILED (STREAM WAS NULL)");
return contentList;
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
contentJson = new String(buffer);
if ((contentJson != null) && (contentJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
contentList = gson.fromJson(contentJson, new TypeToken<ArrayList<InstanceIndexItem>>() {
}.getType());
}
} catch (IOException ioe) {
Log.e("INDEX", "READING JSON FILE " + contentPath + " FROM ZIP FILE FAILED: " + ioe.getMessage());
}
return contentList;
}
// not strictly an index, but including here because code is similar
public static ContentPackMetadata loadContentMetadata(Context context, String packageName, String expansionId, String language) {
String metadataJson = null;
ContentPackMetadata metadata = null;
String metadataPath = packageName + File.separator + expansionId + File.separator + contentMetadataName;
Log.d("INDEX", "READING JSON FILE " + metadataPath + " FROM ZIP FILE");
try {
InputStream jsonStream = ZipHelper.getFileInputStream(metadataPath, context, language);
if (jsonStream == null) {
Log.e("INDEX", "READING JSON FILE " + metadataPath + " FROM ZIP FILE FAILED (STREAM WAS NULL)");
return null;
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
metadataJson = new String(buffer);
if ((metadataJson != null) && (metadataJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
metadata = gson.fromJson(metadataJson, new TypeToken<ContentPackMetadata>() {
}.getType());
}
} catch (IOException ioe) {
Log.e("INDEX", "READING JSON FILE " + metadataPath + " FROM ZIP FILE FAILED: " + ioe.getMessage());
return null;
}
return metadata;
}
public static HashMap<String, String> loadTempateIndex (Context context) {
HashMap<String, String> templateMap = new HashMap<String, String>();
ZipResourceFile zrf = ZipHelper.getResourceFile(context);
ArrayList<ZipResourceFile.ZipEntryRO> zipEntries = new ArrayList<ZipResourceFile.ZipEntryRO>(Arrays.asList(zrf.getAllEntries()));
for (ZipResourceFile.ZipEntryRO zipEntry : zipEntries) {
// Log.d("INDEX", "GOT ITEM: " + zipEntry.mFileName);
templateMap.put(zipEntry.mFileName.substring(zipEntry.mFileName.lastIndexOf(File.separator) + 1), zipEntry.mFileName);
}
return templateMap;
}
public static HashMap<String, InstanceIndexItem> fillInstanceIndex(Context context, HashMap<String, InstanceIndexItem> indexList, String language) {
ArrayList<File> instanceFiles = JsonHelper.getLibraryInstanceFiles(context);
boolean forceSave = false; // need to resolve issue of unset language in existing record preventing update to index
int initialSize = indexList.size();
for (final File f : instanceFiles) {
if (indexList.containsKey(f.getAbsolutePath()) && language.equals(indexList.get(f.getAbsolutePath()).getLanguage())) {
Log.d("INDEX", "FOUND INDEX ITEM FOR INSTANCE FILE " + f.getAbsolutePath());
} else {
Log.d("INDEX", "ADDING INDEX ITEM FOR INSTANCE FILE " + f.getAbsolutePath());
forceSave = true;
String[] parts = FilenameUtils.removeExtension(f.getName()).split("-");
String datePart = parts[parts.length - 1]; // FIXME make more robust
Date date = new Date(Long.parseLong(datePart));
InstanceIndexItem newItem = new InstanceIndexItem(f.getAbsolutePath(), date.getTime());
String jsonString = JsonHelper.loadJSON(f, "en"); // FIXME don't hardcode "en"
ArrayList<String> referencedFiles = new ArrayList<String>(); // should not need to insert dependencies to check metadata
StoryPathLibrary spl = JsonHelper.deserializeStoryPathLibrary(jsonString, f.getAbsolutePath(), referencedFiles, context, language);
if (spl == null) {
return indexList;
}
// set language
newItem.setLanguage(language);
// first check local metadata fields
newItem.setTitle(spl.getMetaTitle());
newItem.setStoryType(spl.getMetaDescription()); // this seems more useful than medium
newItem.setThumbnailPath(spl.getMetaThumbnail());
// unsure where to put additional fields
// if anything is missing, open story path
if ((newItem.getTitle() == null) ||
(newItem.getStoryType() == null) ||
(newItem.getThumbnailPath() == null)) {
Log.d("INDEX", "MISSING METADATA, OPENING STORY PATH FOR INSTANCE FILE " + f.getAbsolutePath());
if (spl.getCurrentStoryPathFile() != null) {
spl.loadStoryPathTemplate("CURRENT", false);
}
StoryPath currentStoryPath = spl.getCurrentStoryPath();
if (currentStoryPath != null) {
// null values will be handled by the index card builder
if (newItem.getTitle() == null) {
newItem.setTitle(currentStoryPath.getTitle());
}
if (newItem.getStoryType() == null) {
newItem.setStoryType(currentStoryPath.getMedium());
}
if (newItem.getThumbnailPath() == null) {
newItem.setThumbnailPath(spl.getMetaThumbnail());
}
}
} else {
Log.d("INDEX", "METADATA COMPLETE FOR INSTANCE FILE " + f.getAbsolutePath());
}
indexList.put(newItem.getInstanceFilePath(), newItem);
}
}
// persist updated index (if necessary)
if ((indexList.size() == initialSize) && !forceSave) {
Log.d("INDEX", "NOTHING ADDED TO INSTANCE INDEX, NO SAVE");
} else {
Log.d("INDEX", (indexList.size() - initialSize) + " ITEMS ADDED TO INSTANCE INDEX, SAVING");
ArrayList<InstanceIndexItem> indexArray = new ArrayList<InstanceIndexItem>(indexList.values());
saveInstanceIndex(context, indexArray, instanceIndexName);
}
return indexList;
}
public static void registerAvailableIndexItem(Context context, ExpansionIndexItem indexItem) {
HashMap<String, ExpansionIndexItem> indexMap = loadAvailableIdIndex(context);
indexMap.put(indexItem.getExpansionId(), indexItem);
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, availableIndexName);
return;
}
public static void registerInstalledIndexItem(Context context, ExpansionIndexItem indexItem) {
HashMap<String, ExpansionIndexItem> indexMap = loadInstalledIdIndex(context);
indexMap.put(indexItem.getExpansionId(), indexItem);
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, installedIndexName);
return;
}
public static void unregisterAvailableIndexItem(Context context, ExpansionIndexItem indexItem) {
HashMap<String, ExpansionIndexItem> indexMap = loadAvailableIdIndex(context);
indexMap.remove(indexItem.getExpansionId());
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, availableIndexName);
return;
}
public static void unregisterInstalledIndexItem(Context context, ExpansionIndexItem indexItem) {
HashMap<String, ExpansionIndexItem> indexMap = loadInstalledIdIndex(context);
indexMap.remove(indexItem.getExpansionId());
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, installedIndexName);
return;
}
public static void unregisterAvailableIndexItem(Context context, String fileName) {
HashMap<String, ExpansionIndexItem> indexMap = loadAvailableFileIndex(context);
indexMap.remove(fileName);
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, availableIndexName);
return;
}
public static void unregisterInstalledIndexItem(Context context, String fileName) {
HashMap<String, ExpansionIndexItem> indexMap = loadInstalledFileIndex(context);
indexMap.remove(fileName);
ArrayList<ExpansionIndexItem> indexList = new ArrayList<ExpansionIndexItem>();
for (ExpansionIndexItem eii : indexMap.values()) {
indexList.add(eii);
}
saveIndex(context, indexList, installedIndexName);
return;
}
public static void saveAvailableIndex(Context context, HashMap<String, ExpansionIndexItem> indexMap) {
saveIndex(context, new ArrayList(indexMap.values()), availableIndexName);
return;
}
public static void saveInstalledIndex(Context context, HashMap<String, ExpansionIndexItem> indexMap) {
saveIndex(context, new ArrayList(indexMap.values()), installedIndexName);
return;
}
private static void saveIndex(Context context, ArrayList<ExpansionIndexItem> indexList, String jsonFileName) {
String indexJson = "";
String jsonFilePath = ZipHelper.getFileFolderName(context);
Log.d("INDEX", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD");
File jsonFile = new File(jsonFilePath + jsonFileName + ".tmp"); // write to temp and rename
if (jsonFile.exists()) {
jsonFile.delete();
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
jsonFile.createNewFile();
FileOutputStream jsonStream = new FileOutputStream(jsonFile);
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
indexJson = gson.toJson(indexList);
byte[] buffer = indexJson.getBytes();
jsonStream.write(buffer);
jsonStream.flush();
jsonStream.close();
jsonStream = null;
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + jsonFileName + ".tmp " + jsonFilePath + jsonFileName);
} catch (IOException ioe) {
Log.e("INDEX", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD FAILED");
return;
}
} else {
Log.e("INDEX", "SD CARD WAS NOT FOUND");
return;
}
}
public static void updateInstanceIndex(Context context, InstanceIndexItem newItem, HashMap<String, InstanceIndexItem> indexList) {
indexList.put(newItem.getInstanceFilePath(), newItem);
ArrayList<InstanceIndexItem> indexArray = new ArrayList<InstanceIndexItem>(indexList.values());
saveInstanceIndex(context, indexArray, instanceIndexName);
}
public static void saveInstanceIndex(Context context, ArrayList<InstanceIndexItem> indexList, String jsonFileName) {
String indexJson = "";
String jsonFilePath = ZipHelper.getFileFolderName(context);
Log.d("INDEX", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD");
File jsonFile = new File(jsonFilePath + jsonFileName + ".tmp"); // write to temp and rename
if (jsonFile.exists()) {
jsonFile.delete();
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
jsonFile.createNewFile();
FileOutputStream jsonStream = new FileOutputStream(jsonFile);
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
indexJson = gson.toJson(indexList);
byte[] buffer = indexJson.getBytes();
jsonStream.write(buffer);
jsonStream.flush();
jsonStream.close();
jsonStream = null;
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + jsonFileName + ".tmp " + jsonFilePath + jsonFileName);
} catch (IOException ioe) {
Log.e("INDEX", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD FAILED");
return;
}
} else {
Log.e("INDEX", "SD CARD WAS NOT FOUND");
return;
}
}
} |
package com.izforge.izpack.panels;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import net.n3.nanoxml.XMLElement;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.ProcessPanelWorker;
import com.izforge.izpack.util.AbstractUIProcessHandler;
/**
* The process panel class.
*
* This class allows external processes to be executed during installation.
*
* Parts of the code have been taken from CompilePanel.java and
* modified a lot.
*
* @author Tino Schwarze
* @author Julien Ponge
*/
public class ProcessPanel extends IzPanel implements AbstractUIProcessHandler
{
/** The operation label . */
protected JLabel processLabel;
/** The overall progress bar. */
protected JProgressBar overallProgressBar;
/** True if the compilation has been done. */
private boolean validated = false;
/** The processing worker. Does all the work. */
private ProcessPanelWorker worker;
/** Number of jobs to process. Used for progress indication. */
private int noOfJobs;
private int currentJob;
/** Where the output is displayed */
private JTextArea outputPane;
private JScrollPane outputScrollPane;
/**
* The constructor.
*
* @param parent The parent window.
* @param idata The installation data.
*/
public ProcessPanel(InstallerFrame parent, InstallData idata)
throws IOException
{
super(parent, idata);
this.worker = new ProcessPanelWorker(idata, this);
JLabel heading = new JLabel();
Font font = heading.getFont();
font = font.deriveFont(Font.BOLD, font.getSize() * 2.0f);
heading.setFont(font);
heading.setHorizontalAlignment(SwingConstants.CENTER);
heading.setText(parent.langpack.getString("ProcessPanel.heading"));
heading.setVerticalAlignment(SwingConstants.TOP);
setLayout(new BorderLayout());
add(heading, BorderLayout.NORTH);
// put everything but the heading into it's own panel
// (to center it vertically)
JPanel subpanel = new JPanel();
subpanel.setAlignmentX(0.5f);
subpanel.setLayout(new BoxLayout(subpanel, BoxLayout.Y_AXIS));
this.processLabel = new JLabel();
this.processLabel.setAlignmentX(0.5f);
this.processLabel.setText(" ");
subpanel.add(this.processLabel);
this.overallProgressBar = new JProgressBar();
this.overallProgressBar.setAlignmentX(0.5f);
this.overallProgressBar.setStringPainted(true);
subpanel.add(this.overallProgressBar);
this.outputPane = new JTextArea();
this.outputPane.setEditable(false);
this.outputScrollPane = new JScrollPane(this.outputPane);
subpanel.add(this.outputScrollPane);
add(subpanel, BorderLayout.CENTER);
}
/**
* Indicates wether the panel has been validated or not.
*
* @return The validation state.
*/
public boolean isValidated()
{
return validated;
}
/** The compiler starts. */
public void startProcessing(int no_of_jobs)
{
this.noOfJobs = no_of_jobs;
overallProgressBar.setMaximum(noOfJobs);
parent.lockPrevButton();
}
/** The compiler stops. */
public void finishProcessing()
{
overallProgressBar.setValue(this.noOfJobs);
String no_of_jobs = Integer.toString(this.noOfJobs);
overallProgressBar.setString(no_of_jobs + " / " + no_of_jobs);
overallProgressBar.setEnabled(false);
processLabel.setText(" ");
processLabel.setEnabled(false);
validated = true;
idata.installSuccess = true;
if (idata.panels.indexOf(this) != (idata.panels.size() - 1))
parent.unlockNextButton();
}
/**
* Log a message.
*
* @param message The message.
* @param stderr Whether the message came from stderr or stdout.
*/
public void logOutput(String message, boolean stderr)
{
// TODO: make it colored
this.outputPane.append(message + '\n');
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
outputPane.setCaretPosition(outputPane.getText().length());
}
}
);
}
/**
* Next job starts.
*
* @param jobName The job name.
*/
public void startProcess(String jobName)
{
processLabel.setText(jobName);
this.currentJob++;
overallProgressBar.setValue(this.currentJob);
overallProgressBar.setString(
Integer.toString(this.currentJob)
+ " / "
+ Integer.toString(this.noOfJobs));
}
public void finishProcess()
{
}
/** Called when the panel becomes active. */
public void panelActivate()
{
// We clip the panel
Dimension dim = parent.getPanelsContainerSize();
dim.width = dim.width - (dim.width / 4);
dim.height = 150;
setMinimumSize(dim);
setMaximumSize(dim);
setPreferredSize(dim);
parent.lockNextButton();
this.worker.startThread();
}
/** Create XML data for automated installation. */
public void makeXMLData(XMLElement panelRoot)
{
// does nothing (no state to save)
}
} |
package com.faveset.khttp;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
class RequestStartHandler implements StateHandler {
/**
* @param conn is not used currently.
* @param state will be reset for the header parsing stage on success.
*
* @throws InvalidRequestException on bad request.
* @return true if enough data existed in the buffer to parse a request
* line.
*/
public boolean handleState(NonBlockingConnection conn, ByteBuffer buf, HandlerState state) throws InvalidRequestException {
HttpRequest req = state.getRequest();
// The spec allows for leading CRLFs.
Strings.skipCrlf(buf);
// Now, look for the Request-Line.
ByteBuffer lineBuf;
try {
lineBuf = Strings.parseLine(buf);
} catch (BufferOverflowException e) {
throw new InvalidRequestException("Request-Line exceeded buffer", HttpStatus.RequestURITooLong);
}
if (lineBuf == null) {
// Signal that more data is needed.
return false;
}
try {
HttpRequest.Method method = Strings.parseMethod(lineBuf);
req.setMethod(method);
} catch (ParseException e) {
throw new InvalidRequestException("Unknown request method", HttpStatus.NotImplemented);
}
String reqUri = Strings.parseWord(lineBuf);
if (reqUri.length() == 0) {
throw new InvalidRequestException("Request is missing URI", HttpStatus.BadRequest);
}
req.setUri(reqUri);
try {
int version = Strings.parseHttpVersion(lineBuf);
if (version > 1) {
// We only support HTTP/1.0 and HTTP/1.1.
throw new InvalidRequestException("Unsupported HTTP version in request", HttpStatus.NotImplemented);
}
} catch (ParseException e) {
throw new InvalidRequestException("Could not parse HTTP version", HttpStatus.BadRequest);
}
state.reset();
return true;
}
} |
package com.socks.library;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.socks.library.klog.BaseLog;
import com.socks.library.klog.FileLog;
import com.socks.library.klog.JsonLog;
import com.socks.library.klog.XmlLog;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
public final class KLog {
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String NULL_TIPS = "Log with null object";
private static final String DEFAULT_MESSAGE = "execute";
private static final String PARAM = "Param";
private static final String NULL = "null";
private static final String TAG_DEFAULT = "KLog";
private static final String SUFFIX = ".java";
public static final int JSON_INDENT = 4;
public static final int V = 0x1;
public static final int D = 0x2;
public static final int I = 0x3;
public static final int W = 0x4;
public static final int E = 0x5;
public static final int A = 0x6;
private static final int JSON = 0x7;
private static final int XML = 0x8;
private static final int STACK_TRACE_INDEX_5 = 5;
private static final int STACK_TRACE_INDEX_4 = 4;
private static String mGlobalTag;
private static boolean mIsGlobalTagEmpty = true;
private static boolean IS_SHOW_LOG = true;
public static void init(boolean isShowLog) {
IS_SHOW_LOG = isShowLog;
}
public static void init(boolean isShowLog, @Nullable String tag) {
IS_SHOW_LOG = isShowLog;
mGlobalTag = tag;
mIsGlobalTagEmpty = TextUtils.isEmpty(mGlobalTag);
}
public static void v() {
printLog(V, null, DEFAULT_MESSAGE);
}
public static void v(Object msg) {
printLog(V, null, msg);
}
public static void v(String tag, Object... objects) {
printLog(V, tag, objects);
}
public static void d() {
printLog(D, null, DEFAULT_MESSAGE);
}
public static void d(Object msg) {
printLog(D, null, msg);
}
public static void d(String tag, Object... objects) {
printLog(D, tag, objects);
}
public static void i() {
printLog(I, null, DEFAULT_MESSAGE);
}
public static void i(Object msg) {
printLog(I, null, msg);
}
public static void i(String tag, Object... objects) {
printLog(I, tag, objects);
}
public static void w() {
printLog(W, null, DEFAULT_MESSAGE);
}
public static void w(Object msg) {
printLog(W, null, msg);
}
public static void w(String tag, Object... objects) {
printLog(W, tag, objects);
}
public static void e() {
printLog(E, null, DEFAULT_MESSAGE);
}
public static void e(Object msg) {
printLog(E, null, msg);
}
public static void e(String tag, Object... objects) {
printLog(E, tag, objects);
}
public static void a() {
printLog(A, null, DEFAULT_MESSAGE);
}
public static void a(Object msg) {
printLog(A, null, msg);
}
public static void a(String tag, Object... objects) {
printLog(A, tag, objects);
}
public static void json(String jsonFormat) {
printLog(JSON, null, jsonFormat);
}
public static void json(String tag, String jsonFormat) {
printLog(JSON, tag, jsonFormat);
}
public static void xml(String xml) {
printLog(XML, null, xml);
}
public static void xml(String tag, String xml) {
printLog(XML, tag, xml);
}
public static void file(File targetDirectory, Object msg) {
printFile(null, targetDirectory, null, msg);
}
public static void file(String tag, File targetDirectory, Object msg) {
printFile(tag, targetDirectory, null, msg);
}
public static void file(String tag, File targetDirectory, String fileName, Object msg) {
printFile(tag, targetDirectory, fileName, msg);
}
public static void debug() {
printDebug(null, DEFAULT_MESSAGE);
}
public static void debug(Object msg) {
printDebug(null, msg);
}
public static void debug(String tag, Object... objects) {
printDebug(tag, objects);
}
public static void trace() {
printStackTrace();
}
private static void printStackTrace() {
if (!IS_SHOW_LOG) {
return;
}
Throwable tr = new Throwable();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
tr.printStackTrace(pw);
pw.flush();
String message = sw.toString();
String traceString[] = message.split("\\n\\t");
StringBuilder sb = new StringBuilder();
sb.append("\n");
for (String trace : traceString) {
if (trace.contains("at com.socks.library.KLog")) {
continue;
}
sb.append(trace).append("\n");
}
String[] contents = wrapperContent(STACK_TRACE_INDEX_4, null, sb.toString());
String tag = contents[0];
String msg = contents[1];
String headString = contents[2];
BaseLog.printDefault(D, tag, headString + msg);
}
private static void printLog(int type, String tagStr, Object... objects) {
if (!IS_SHOW_LOG) {
return;
}
String[] contents = wrapperContent(STACK_TRACE_INDEX_5, tagStr, objects);
String tag = contents[0];
String msg = contents[1];
String headString = contents[2];
switch (type) {
case V:
case D:
case I:
case W:
case E:
case A:
BaseLog.printDefault(type, tag, headString + msg);
break;
case JSON:
JsonLog.printJson(tag, msg, headString);
break;
case XML:
XmlLog.printXml(tag, msg, headString);
break;
}
}
private static void printDebug(String tagStr, Object... objects) {
String[] contents = wrapperContent(STACK_TRACE_INDEX_5, tagStr, objects);
String tag = contents[0];
String msg = contents[1];
String headString = contents[2];
BaseLog.printDefault(D, tag, headString + msg);
}
private static void printFile(String tagStr, File targetDirectory, String fileName, Object objectMsg) {
if (!IS_SHOW_LOG) {
return;
}
String[] contents = wrapperContent(STACK_TRACE_INDEX_5, tagStr, objectMsg);
String tag = contents[0];
String msg = contents[1];
String headString = contents[2];
FileLog.printFile(tag, targetDirectory, fileName, headString, msg);
}
private static String[] wrapperContent(int stackTraceIndex, String tagStr, Object... objects) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement targetElement = stackTrace[stackTraceIndex];
String className = targetElement.getClassName();
String[] classNameInfo = className.split("\\.");
if (classNameInfo.length > 0) {
className = classNameInfo[classNameInfo.length - 1] + SUFFIX;
}
if (className.contains("$")) {
className = className.split("\\$")[0] + SUFFIX;
}
String methodName = targetElement.getMethodName();
int lineNumber = targetElement.getLineNumber();
if (lineNumber < 0) {
lineNumber = 0;
}
String tag = (tagStr == null ? className : tagStr);
if (mIsGlobalTagEmpty && TextUtils.isEmpty(tag)) {
tag = TAG_DEFAULT;
} else if (!mIsGlobalTagEmpty) {
tag = mGlobalTag;
}
String msg = (objects == null) ? NULL_TIPS : getObjectsString(objects);
String headString = "[ (" + className + ":" + lineNumber + ")#" + methodName + " ] ";
return new String[]{tag, msg, headString};
}
private static String getObjectsString(Object... objects) {
if (objects.length > 1) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n");
for (int i = 0; i < objects.length; i++) {
Object object = objects[i];
if (object == null) {
stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(NULL).append("\n");
} else {
stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n");
}
}
return stringBuilder.toString();
} else if (objects.length == 1){
Object object = objects[0];
return object == null ? NULL : object.toString();
} else {
return NULL;
}
}
} |
package ameba.core;
import org.glassfish.jersey.server.ResourceConfig;
import java.util.Map;
import java.util.Set;
/**
* @author icode
*/
class ExcludeResourceConfig extends ResourceConfig {
private Set<String> excludes;
public ExcludeResourceConfig(Set<String> excludes) {
this.excludes = excludes;
}
private boolean isExclude(Class cls) {
if (excludes == null) return false;
if (cls == null) return true;
String className = cls.getName();
for (String e : excludes) {
if (e.endsWith(".**")) {
if (className.startsWith(e.substring(0, e.length() - 3))) {
return true;
}
} else if (e.endsWith(".*")) {
int index = e.length() - 2;
if (className.startsWith(e.substring(0, index)) && className.indexOf(".", index + 1) == -1) {
return true;
}
} else if (className.equals(e)) {
return true;
}
}
return false;
}
@Override
public ResourceConfig register(Object component, Map<Class<?>, Integer> contracts) {
if (component == null || isExclude(component.getClass())) return this;
return super.register(component, contracts);
}
@Override
public ResourceConfig register(Class<?> componentClass) {
if (componentClass == null || isExclude(componentClass)) return this;
return super.register(componentClass);
}
@Override
public ResourceConfig register(Class<?> componentClass, int bindingPriority) {
if (componentClass == null || isExclude(componentClass)) return this;
return super.register(componentClass, bindingPriority);
}
@Override
public ResourceConfig register(Class<?> componentClass, Class<?>... contracts) {
if (componentClass == null || isExclude(componentClass)) return this;
return super.register(componentClass, contracts);
}
@Override
public ResourceConfig register(Class<?> componentClass, Map<Class<?>, Integer> contracts) {
if (componentClass == null || isExclude(componentClass)) return this;
return super.register(componentClass, contracts);
}
@Override
public ResourceConfig register(Object component) {
if (component == null || isExclude(component.getClass())) return this;
return super.register(component);
}
@Override
public ResourceConfig register(Object component, int bindingPriority) {
if (component == null || isExclude(component.getClass())) return this;
return super.register(component, bindingPriority);
}
@Override
public ResourceConfig register(Object component, Class<?>... contracts) {
if (component == null || isExclude(component.getClass())) return this;
return super.register(component, contracts);
}
} |
package org.holoeverywhere.widget;
import org.holoeverywhere.R;
import org.holoeverywhere.text.AllCapsTransformationMethod;
import org.holoeverywhere.text.TransformationMethod;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.v4.view.MotionEventCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.CompoundButton;
public class Switch extends CompoundButton {
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked
};
private static final int MONOSPACE = 3;
private static final int SANS = 1;
private static final int SERIF = 2;
private static final int TOUCH_MODE_DOWN = 1;
private static final int TOUCH_MODE_DRAGGING = 2;
private static final int TOUCH_MODE_IDLE = 0;
private int mMinFlingVelocity;
private Layout mOffLayout;
private Layout mOnLayout;
private int mSwitchBottom;
private int mSwitchHeight;
private int mSwitchLeft;
private int mSwitchMinWidth;
private int mSwitchPadding;
private int mSwitchRight;
private int mSwitchTop;
private TransformationMethod mSwitchTransformationMethod;
private int mSwitchWidth;
private final Rect mTempRect = new Rect();
private ColorStateList mTextColors;
private CharSequence mTextOff;
private CharSequence mTextOn;
private TextPaint mTextPaint;
private Drawable mThumbDrawable;
private float mThumbPosition;
private int mThumbTextPadding;
private int mThumbWidth;
private boolean mToggleWhenClick;
private int mTouchMode;
private int mTouchSlop;
private float mTouchX;
private float mTouchY;
private Drawable mTrackDrawable;
private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
public Switch(Context context) {
this(context, null);
}
public Switch(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.switchStyle);
}
public Switch(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
Resources res = getResources();
mTextPaint.density = res.getDisplayMetrics().density;
// TODO
// mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.Switch, defStyle, 0);
mThumbDrawable = a.getDrawable(R.styleable.Switch_thumb);
mTrackDrawable = a.getDrawable(R.styleable.Switch_track);
mTextOn = a.getText(R.styleable.Switch_textOn);
mTextOff = a.getText(R.styleable.Switch_textOff);
mThumbTextPadding = a.getDimensionPixelSize(
R.styleable.Switch_thumbTextPadding, 0);
mSwitchMinWidth = a.getDimensionPixelSize(
R.styleable.Switch_switchMinWidth, 0);
mSwitchPadding = a.getDimensionPixelSize(
R.styleable.Switch_switchPadding, 0);
mToggleWhenClick = a.getBoolean(R.styleable.Switch_toggleWhenClick, true);
int appearance = a.getResourceId(R.styleable.Switch_switchTextAppearance, 0);
if (appearance != 0) {
setSwitchTextAppearance(context, appearance);
}
a.recycle();
ViewConfiguration config = ViewConfiguration.get(context);
mTouchSlop = config.getScaledTouchSlop();
mMinFlingVelocity = config.getScaledMinimumFlingVelocity();
refreshDrawableState();
setChecked(isChecked());
}
private void animateThumbToCheckedState(boolean newCheckedState) {
// TODO animate!
// float targetPos = newCheckedState ? 0 : getThumbScrollRange();
// mThumbPosition = targetPos;
setChecked(newCheckedState);
}
private void cancelSuperTouch(MotionEvent ev) {
MotionEvent cancel = MotionEvent.obtain(ev);
cancel.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(cancel);
cancel.recycle();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
int[] myDrawableState = getDrawableState();
if (mThumbDrawable != null) {
mThumbDrawable.setState(myDrawableState);
}
if (mTrackDrawable != null) {
mTrackDrawable.setState(myDrawableState);
}
invalidate();
}
@Override
public int getCompoundPaddingRight() {
int padding = super.getCompoundPaddingRight() + mSwitchWidth;
if (!TextUtils.isEmpty(getText())) {
padding += mSwitchPadding;
}
return padding;
}
public int getSwitchMinWidth() {
return mSwitchMinWidth;
}
public int getSwitchPadding() {
return mSwitchPadding;
}
private boolean getTargetCheckedState() {
return mThumbPosition >= getThumbScrollRange() / 2;
}
public CharSequence getTextOff() {
return mTextOff;
}
public CharSequence getTextOn() {
return mTextOn;
}
public Drawable getThumbDrawable() {
return mThumbDrawable;
}
private int getThumbScrollRange() {
if (mTrackDrawable == null) {
return 0;
}
mTrackDrawable.getPadding(mTempRect);
return mSwitchWidth - mThumbWidth - mTempRect.left - mTempRect.right;
}
public int getThumbTextPadding() {
return mThumbTextPadding;
}
public Drawable getTrackDrawable() {
return mTrackDrawable;
}
private boolean hitThumb(float x, float y) {
mThumbDrawable.getPadding(mTempRect);
final int thumbTop = mSwitchTop - mTouchSlop;
final int thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop;
final int thumbRight = thumbLeft + mThumbWidth +
mTempRect.left + mTempRect.right + mTouchSlop;
final int thumbBottom = mSwitchBottom + mTouchSlop;
return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom;
}
public boolean isToggleWhenClick() {
return mToggleWhenClick;
}
@Override
public void jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState();
mThumbDrawable.jumpToCurrentState();
mTrackDrawable.jumpToCurrentState();
}
private Layout makeLayout(CharSequence text) {
final CharSequence transformed = mSwitchTransformationMethod != null
? mSwitchTransformationMethod.getTransformation(text, this)
: text;
return new StaticLayout(transformed, mTextPaint,
(int) Math.ceil(Layout.getDesiredWidth(transformed, mTextPaint)),
Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int switchLeft = mSwitchLeft;
int switchTop = mSwitchTop;
int switchRight = mSwitchRight;
int switchBottom = mSwitchBottom;
mTrackDrawable.setBounds(switchLeft, switchTop, switchRight, switchBottom);
mTrackDrawable.draw(canvas);
final int saveState = canvas.save();
mTrackDrawable.getPadding(mTempRect);
int switchInnerLeft = switchLeft + mTempRect.left;
int switchInnerTop = switchTop + mTempRect.top;
int switchInnerRight = switchRight - mTempRect.right;
int switchInnerBottom = switchBottom - mTempRect.bottom;
canvas.clipRect(switchInnerLeft, switchTop, switchInnerRight, switchBottom);
mThumbDrawable.getPadding(mTempRect);
final int thumbPos = (int) (mThumbPosition + 0.5f);
int thumbLeft = switchInnerLeft - mTempRect.left + thumbPos;
int thumbRight = switchInnerLeft + thumbPos + mThumbWidth + mTempRect.right;
mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
mThumbDrawable.draw(canvas);
if (mTextColors != null) {
mTextPaint.setColor(mTextColors.getColorForState(getDrawableState(),
mTextColors.getDefaultColor()));
}
mTextPaint.drawableState = getDrawableState();
Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
canvas.translate((thumbLeft + thumbRight) / 2 - switchText.getWidth() / 2,
(switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2);
switchText.draw(canvas);
canvas.restoreToCount(saveState);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(Switch.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(Switch.class.getName());
CharSequence switchText = isChecked() ? mTextOn : mTextOff;
if (!TextUtils.isEmpty(switchText)) {
CharSequence oldText = info.getText();
if (TextUtils.isEmpty(oldText)) {
info.setText(switchText);
} else {
StringBuilder newText = new StringBuilder();
newText.append(oldText).append(' ').append(switchText);
info.setText(newText);
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mThumbPosition = isChecked() ? getThumbScrollRange() : 0;
int switchRight = getWidth() - getPaddingRight();
int switchLeft = switchRight - mSwitchWidth;
int switchTop = 0;
int switchBottom = 0;
switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) {
default:
case Gravity.TOP:
switchTop = getPaddingTop();
switchBottom = switchTop + mSwitchHeight;
break;
case Gravity.CENTER_VERTICAL:
switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 -
mSwitchHeight / 2;
switchBottom = switchTop + mSwitchHeight;
break;
case Gravity.BOTTOM:
switchBottom = getHeight() - getPaddingBottom();
switchTop = switchBottom - mSwitchHeight;
break;
}
mSwitchLeft = switchLeft;
mSwitchTop = switchTop;
mSwitchBottom = switchBottom;
mSwitchRight = switchRight;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (mOnLayout == null) {
mOnLayout = makeLayout(mTextOn);
}
if (mOffLayout == null) {
mOffLayout = makeLayout(mTextOff);
}
mTrackDrawable.getPadding(mTempRect);
final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
final int switchWidth = Math.max(mSwitchMinWidth,
maxTextWidth * 2 + mThumbTextPadding * 4 + mTempRect.left + mTempRect.right);
final int switchHeight = mTrackDrawable.getIntrinsicHeight();
mThumbWidth = maxTextWidth + mThumbTextPadding * 2;
switch (widthMode) {
case MeasureSpec.AT_MOST:
widthSize = Math.min(widthSize, switchWidth);
break;
case MeasureSpec.UNSPECIFIED:
widthSize = switchWidth;
break;
case MeasureSpec.EXACTLY:
break;
}
switch (heightMode) {
case MeasureSpec.AT_MOST:
heightSize = Math.min(heightSize, switchHeight);
break;
case MeasureSpec.UNSPECIFIED:
heightSize = switchHeight;
break;
case MeasureSpec.EXACTLY:
break;
}
mSwitchWidth = switchWidth;
mSwitchHeight = switchHeight;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int measuredHeight = getMeasuredHeight();
if (measuredHeight < switchHeight) {
setMeasuredDimension(getMeasuredWidth(), switchHeight);
}
}
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
super.onPopulateAccessibilityEvent(event);
CharSequence text = isChecked() ? mOnLayout.getText() : mOffLayout.getText();
if (!TextUtils.isEmpty(text)) {
event.getText().add(text);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mVelocityTracker.addMovement(ev);
switch (MotionEventCompat.getActionMasked(ev)) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
if (isEnabled() && hitThumb(x, y)) {
mTouchMode = TOUCH_MODE_DOWN;
mTouchX = x;
mTouchY = y;
}
return true;
}
case MotionEvent.ACTION_MOVE: {
switch (mTouchMode) {
case TOUCH_MODE_IDLE:
break;
case TOUCH_MODE_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
if (Math.abs(x - mTouchX) > mTouchSlop ||
Math.abs(y - mTouchY) > mTouchSlop) {
mTouchMode = TOUCH_MODE_DRAGGING;
getParent().requestDisallowInterceptTouchEvent(true);
mTouchX = x;
mTouchY = y;
return true;
}
break;
}
case TOUCH_MODE_DRAGGING: {
final float x = ev.getX();
final float dx = x - mTouchX;
float newPos = Math.max(0,
Math.min(mThumbPosition + dx, getThumbScrollRange()));
if (newPos != mThumbPosition) {
mThumbPosition = newPos;
mTouchX = x;
invalidate();
}
return true;
}
}
break;
}
case MotionEvent.ACTION_UP:
if (mTouchMode == TOUCH_MODE_DOWN && mToggleWhenClick) {
toggle();
cancelSuperTouch(ev);
mTouchMode = TOUCH_MODE_IDLE;
mVelocityTracker.clear();
return true;
}
case MotionEvent.ACTION_CANCEL: {
if (mTouchMode == TOUCH_MODE_DRAGGING) {
stopDrag(ev);
return true;
}
mTouchMode = TOUCH_MODE_IDLE;
mVelocityTracker.clear();
break;
}
}
return super.onTouchEvent(ev);
}
@Override
public void setChecked(boolean checked) {
mThumbPosition = checked ? getThumbScrollRange() : 0;
super.setChecked(checked);
invalidate();
}
public void setSwitchMinWidth(int pixels) {
mSwitchMinWidth = pixels;
requestLayout();
}
public void setSwitchPadding(int pixels) {
mSwitchPadding = pixels;
requestLayout();
}
public void setSwitchTextAppearance(Context context, int resid) {
TypedArray appearance =
context.obtainStyledAttributes(resid,
R.styleable.TextAppearance);
ColorStateList colors;
int ts;
colors = appearance.getColorStateList(R.styleable.
TextAppearance_android_textColor);
if (colors != null) {
mTextColors = colors;
} else {
mTextColors = getTextColors();
}
ts = appearance.getDimensionPixelSize(R.styleable.
TextAppearance_android_textSize, 0);
if (ts != 0) {
if (ts != mTextPaint.getTextSize()) {
mTextPaint.setTextSize(ts);
requestLayout();
}
}
int typefaceIndex, styleIndex;
typefaceIndex = appearance.getInt(R.styleable.
TextAppearance_android_typeface, -1);
styleIndex = appearance.getInt(R.styleable.
TextAppearance_android_textStyle, -1);
setSwitchTypefaceByIndex(typefaceIndex, styleIndex);
boolean allCaps = appearance.getBoolean(R.styleable.
TextAppearance_android_textAllCaps, false);
if (allCaps) {
mSwitchTransformationMethod = new AllCapsTransformationMethod(getContext());
mSwitchTransformationMethod.setLengthChangesAllowed(true);
} else {
mSwitchTransformationMethod = null;
}
appearance.recycle();
}
public void setSwitchTypeface(Typeface tf) {
if (mTextPaint.getTypeface() != tf) {
mTextPaint.setTypeface(tf);
requestLayout();
invalidate();
}
}
public void setSwitchTypeface(Typeface tf, int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style);
} else {
tf = Typeface.create(tf, style);
}
setSwitchTypeface(tf);
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
setSwitchTypeface(tf);
}
}
private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) {
Typeface tf = null;
switch (typefaceIndex) {
case SANS:
tf = Typeface.SANS_SERIF;
break;
case SERIF:
tf = Typeface.SERIF;
break;
case MONOSPACE:
tf = Typeface.MONOSPACE;
break;
}
setSwitchTypeface(tf, styleIndex);
}
public void setTextOff(CharSequence textOff) {
mTextOff = textOff;
requestLayout();
}
public void setTextOn(CharSequence textOn) {
mTextOn = textOn;
requestLayout();
}
public void setThumbDrawable(Drawable thumb) {
mThumbDrawable = thumb;
requestLayout();
}
public void setThumbResource(int resId) {
setThumbDrawable(getContext().getResources().getDrawable(resId));
}
public void setThumbTextPadding(int pixels) {
mThumbTextPadding = pixels;
requestLayout();
}
public void setToggleWhenClick(boolean mToggleWhenClick) {
this.mToggleWhenClick = mToggleWhenClick;
}
public void setTrackDrawable(Drawable track) {
mTrackDrawable = track;
requestLayout();
}
public void setTrackResource(int resId) {
setTrackDrawable(getContext().getResources().getDrawable(resId));
}
private void stopDrag(MotionEvent ev) {
mTouchMode = TOUCH_MODE_IDLE;
boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
cancelSuperTouch(ev);
if (commitChange) {
boolean newState;
mVelocityTracker.computeCurrentVelocity(1000);
float xvel = mVelocityTracker.getXVelocity();
if (Math.abs(xvel) > mMinFlingVelocity) {
newState = xvel > 0;
} else {
newState = getTargetCheckedState();
}
animateThumbToCheckedState(newState);
} else {
animateThumbToCheckedState(isChecked());
}
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable;
}
} |
package betterwithaddons.util;
import net.minecraft.block.BlockBanner;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemBanner;
import net.minecraft.item.ItemShield;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class BannerUtil {
public static ItemStack getBannerItemFromBlock(World world, BlockPos pos)
{
IBlockState blockstate = world.getBlockState(pos);
if (blockstate.getBlock() instanceof BlockBanner) {
BlockBanner bannerblock = (BlockBanner) blockstate.getBlock();
return bannerblock.getItem(world, pos, blockstate);
}
return ItemStack.EMPTY;
}
public static boolean isSameBanner(ItemStack bannerA, ItemStack bannerB)
{
if(isAnyBanner(bannerA) && isAnyBanner(bannerB)) {
boolean baseequal = ItemBanner.getBaseColor(bannerA) == ItemBanner.getBaseColor(bannerB);
NBTTagList patternsA = null;
NBTTagList patternsB = null;
if(bannerA.hasTagCompound() && bannerA.getTagCompound().hasKey("BlockEntityTag", 10)) {
NBTTagCompound compound = bannerA.getTagCompound().getCompoundTag("BlockEntityTag");
if (compound.hasKey("Patterns")) {
patternsA = compound.getTagList("Patterns", 10);
}
}
if(bannerB.hasTagCompound() && bannerB.getTagCompound().hasKey("BlockEntityTag", 10)) {
NBTTagCompound compound = bannerB.getTagCompound().getCompoundTag("BlockEntityTag");
if (compound.hasKey("Patterns")) {
patternsB = compound.getTagList("Patterns", 10);
}
}
//this is shitty.
boolean bothnull = (patternsA == null || patternsA.tagCount() == 0) && (patternsB == null || patternsB.tagCount() == 0);
return baseequal && (bothnull || patternsA.equals(patternsB));
}
return false;
}
public static boolean isSameBanner(ItemStack banner, Entity bannerHolder)
{
boolean match = false;
if(bannerHolder instanceof EntityLivingBase) {
ItemStack helmet = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.HEAD);
ItemStack mainhand = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.MAINHAND);
ItemStack offhand = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.OFFHAND);
if(isAnyBanner(helmet))
match |= isSameBanner(banner,helmet);
if(isAnyBanner(mainhand))
match |= isSameBanner(banner,mainhand);
if(isAnyBanner(offhand))
match |= isSameBanner(banner,offhand);
}
return match;
}
public static boolean isAnyBanner(ItemStack stack)
{
return stack.getItem() instanceof ItemBanner || stack.getItem() instanceof ItemShield;
}
} |
package br.com.imobiliaria.dao;
import br.com.imobiliaria.model.Imagem;
import br.com.imobiliaria.model.Imovel;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
@Stateless
public class ImovelDAO {
@PersistenceContext(unitName = "imobiliariaPU")
private EntityManager em;
public void insere(Imovel imovel) {
em.persist(imovel);
}
public void excluir(Long id) {
em.remove(em.getReference(Imovel.class, id));
}
public Imovel buscar(Long id) {
return em.find(Imovel.class, id);
}
public Imovel atualizar(Imovel imovel) {
Imagem imagem = new Imagem();
imagem.setImovel(imovel);
FileInputStream fileInputStream=null;
File file = new File("C:\\download.jpg");
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
}catch(Exception e){
e.printStackTrace();
}
imagem.setImagem(bFile);
List<Imagem> imagens = new ArrayList<>();
imagens.add(imagem);
imovel.setImagens(imagens);
return em.merge(imovel);
}
public List<Imovel> lista() {
TypedQuery<Imovel> q = em.createQuery("SELECT i "
+ "FROM Imovel i ORDER BY i.id", Imovel.class);
return q.getResultList();
}
} |
package com.attask.jenkins;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.BatchFile;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tasks.Shell;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.*;
@ExportedBean
public class ScriptBuilder extends Builder {
private final String scriptName; //will be an absolute path
private final List<Parameter> parameters;
private final boolean abortOnFailure;
private final ErrorMode errorMode;
private final String errorRange;
private final ErrorMode unstableMode;
private final String unstableRange;
private final String injectProperties;
private final boolean runOnMaster;
@DataBoundConstructor
public ScriptBuilder(String scriptName, List<Parameter> parameters, boolean abortOnFailure, ErrorMode errorMode, String errorRange, ErrorMode unstableMode, String unstableRange, String injectProperties, boolean runOnMaster) {
this.scriptName = scriptName;
if(parameters == null) {
this.parameters = Collections.emptyList();
} else {
this.parameters = Collections.unmodifiableList(new ArrayList<Parameter>(parameters));
}
this.abortOnFailure = abortOnFailure;
this.errorMode = errorMode;
this.errorRange = errorRange;
this.unstableMode = unstableMode;
this.unstableRange = unstableRange;
this.injectProperties = injectProperties;
this.runOnMaster = runOnMaster;
}
@Exported
public String getScriptName() {
return scriptName;
}
@Exported
public List<Parameter> getParameters() {
return parameters;
}
@Exported
public boolean getAbortOnFailure() {
return abortOnFailure;
}
@Exported
public ErrorMode getErrorMode() {
return errorMode;
}
@Exported
public String getErrorRange() {
return errorRange;
}
@Exported
public ErrorMode getUnstableMode() {
return unstableMode;
}
@Exported
public String getUnstableRange() {
return unstableRange;
}
@Exported
public String getInjectProperties() {
return injectProperties;
}
/**
* If true the script runs on the master node in a temporary directory rather than on the machine the build is running on.
*/
@Exported
public boolean getRunOnMaster() {
return runOnMaster;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public Map<String, Script> findRunnableScripts() throws IOException, InterruptedException {
FilePath rootPath = Jenkins.getInstance().getRootPath();
FilePath userContent = new FilePath(rootPath, "userContent");
DescriptorImpl descriptor = getDescriptor();
return descriptor.findRunnableScripts(userContent);
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException {
boolean result;
final Map<String, Script> runnableScripts = findRunnableScripts();
Script script = runnableScripts.get(scriptName);
if(script != null) {
Map<String, String> varsToInject = injectParameters(parameters);
build.addAction(new InjectPropertiesAction(varsToInject));
//If we want to run it on master, do so. But if the job is already running on master, just run it as if the run on master flag isn't set.
if(this.runOnMaster && !(launcher instanceof Launcher.LocalLauncher)) {
FilePath workspace = Jenkins.getInstance().getRootPath().createTempDir("Workspace", "Temp");
try {
Launcher masterLauncher = new Launcher.RemoteLauncher(listener, workspace.getChannel(), true);
result = execute(build, masterLauncher, listener, script);
} finally {
workspace.deleteRecursive();
}
} else {
result = execute(build, launcher, listener, script);
}
} else {
listener.error("'" + scriptName + "' doesn't exist anymore. Failing.");
result = false;
}
injectProperties(build, listener);
return result;
}
private void injectProperties(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
if(getInjectProperties() != null && !getInjectProperties().isEmpty()) {
PrintStream logger = listener.getLogger();
logger.println("injecting properties from " + getInjectProperties());
FilePath filePath = new FilePath(build.getWorkspace(), getInjectProperties());
Properties injectedProperties = new Properties();
InputStream read = filePath.read();
try {
injectedProperties.load(read);
} finally {
read.close();
}
Map<String, String> injectedMap = new HashMap<String, String>(injectedProperties.size());
for (Map.Entry<Object, Object> entry : injectedProperties.entrySet()) {
logger.println("\t" + entry.getKey() + " => " + entry.getValue());
injectedMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
build.addAction(new InjectPropertiesAction(injectedMap));
}
}
private Map<String, String> injectParameters(List<Parameter> parameters) {
Map<String, String> result = new HashMap<String, String>();
for (Parameter parameter : parameters) {
String key = parameter.getParameterKey();
String value = parameter.getParameterValue();
result.put(key, value);
}
return result;
}
private boolean execute(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, Script script) throws IOException, InterruptedException {
String scriptContents = script.findScriptContents();
if(launcher.isUnix()) {
Shell shell = new Shell(scriptContents);
return shell.perform(build, launcher, listener);
} else {
BatchFile batchFile = new BatchFile(scriptContents);
return batchFile.perform(build, launcher, listener);
}
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public String fileTypes;
@Override
public boolean configure(StaplerRequest request, JSONObject formData) throws FormException {
fileTypes = formData.getString("fileTypes");
save();
return super.configure(request, formData);
}
public String getFileTypes() {
load();
if(fileTypes == null || fileTypes.isEmpty()) {
return ".*";
}
return fileTypes;
}
@Exported
public ListBoxModel doFillScriptNameItems() {
FilePath rootPath = Jenkins.getInstance().getRootPath();
FilePath userContent = new FilePath(rootPath, "userContent");
ListBoxModel items = new ListBoxModel();
for (Script script : findRunnableScripts(userContent).values()) {
//Pretty up the name
String path = script.getFile().getRemote();
path = path.substring(userContent.getRemote().length()+1);
items.add(path, script.getFile().getRemote());
}
return items;
}
public String getGuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
private Map<String, Script> findRunnableScripts(FilePath userContent) {
final List<String> fileTypes = Arrays.asList(this.getFileTypes().split("\\s+"));
try {
return userContent.act(new FindScriptsOnMaster(userContent, fileTypes));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public ListBoxModel doFillErrorModeItems() {
ListBoxModel items = new ListBoxModel();
for (ErrorMode errorMode : ErrorMode.values()) {
items.add(errorMode.getHumanReadable(), errorMode.toString());
}
return items;
}
@Exported
public ListBoxModel doFillUnstableModeItems() {
return doFillErrorModeItems();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getDisplayName() {
return "Execute UserContent Script";
}
}
} |
package com.bdh.automation;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* Commands for creating, generating, and cleaning Allure reports.
*
* @author Jimmy Zeisweiss.
*
*/
public enum AllureCommand {
/**
* Generate an Allure report using existing Allure result data files.
*/
GENERATE("generate"),
/**
* Open an existing Allure report.
*/
OPEN("report open"),
/**
* Remove an existing Allure report.
*/
REMOVE_OLD_REPORT("report clean");
private static final String CONSOLE_HORIZONTAL_LINE = "
private static final String REPORT_DATA_PATH = "target/allure-results";
private static final String ALLURE_HOME = SystemUtils.USER_DIR + "/allure-tools/1.4.22";
private static final String TOOL_PATH = ALLURE_HOME + "/bin/allure" + (SystemUtils.IS_OS_WINDOWS ? ".bat" : "");
private String command;
AllureCommand(String command) {
this.command = command;
}
/**
* Execute a command line command without an appended value.
*/
private void executeCommand() {
executeCommand("");
}
/**
* Execute a command line command with an appended value.
*
* @param appendValue
* to add to the command
*/
private void executeCommand(final String appendValue) {
this.command = CommandLine.parse(TOOL_PATH).getExecutable() + " " + this.command + " " + appendValue;
System.out.println(CONSOLE_HORIZONTAL_LINE);
System.out.println("Running Command: $ " + command);
ExecutorService service = Executors.newSingleThreadExecutor();
Future<String> future = service.submit(new Callable<String>() {
@Override
public String call() {
try {
Process process = Runtime.getRuntime().exec(command);
InputStreamReader stream = new InputStreamReader(process.getInputStream());
BufferedReader output = new BufferedReader(stream);
while (process.isAlive()) {
String line = output.readLine();
if (line != null) {
System.out.println("OUTPUT: " + line);
}
}
} catch (IOException | SecurityException e) {
e.printStackTrace();
}
return "Success";
}
});
try {
future.get(30, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException | ExecutionException e) {
System.out.println("Timeout reached");
}
service.shutdownNow();
System.out.println(CONSOLE_HORIZONTAL_LINE);
}
/**
* Run the current command.
*/
public void run() {
switch (this) {
case GENERATE:
executeCommand(REPORT_DATA_PATH);
break;
case OPEN:
executeCommand();
break;
case REMOVE_OLD_REPORT:
executeCommand();
FileUtils.deleteQuietly(new File(REPORT_DATA_PATH));
try {
FileUtils.forceMkdir(new File(REPORT_DATA_PATH));
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} |
package com.codahale.shore;
import static com.google.common.base.Preconditions.*;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.logging.Logger;
import net.jcip.annotations.Immutable;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.FilterHolder;
import org.mortbay.jetty.servlet.ServletHolder;
import com.codahale.shore.modules.HibernateModule;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.wideplay.warp.persist.SessionFilter;
/**
* Starts a new Jetty server and runs a Shore application.
*
* @author coda
*
*/
@Immutable
public class ServerCommand implements Runnable {
private static final int GRACEFUL_SHUTDOWN_PERIOD = 5000;
private static final Logger LOGGER = Logger.getLogger(ServerCommand.class.getCanonicalName());
private final AbstractConfiguration configuration;
private final int port;
private final Properties properties;
/**
* Creates a new {@link ServerCommand}.
*
* @param configuration
* the application's configuration
* @param port
* the port to listen on
* @param properties
* the connection properties
*/
public ServerCommand(AbstractConfiguration configuration, int port, Properties properties) {
this.configuration = checkNotNull(configuration);
this.port = port;
this.properties = checkNotNull(properties);
}
public AbstractConfiguration getConfiguration() {
return configuration;
}
public int getPort() {
return port;
}
public Properties getProperties() {
return properties;
}
@Override
public void run() {
final Server server = new Server();
configuration.configure();
server.addConnector(buildConnector());
server.addHandler(buildContext(buildServletHolder()));
server.setSendServerVersion(false);
server.setGracefulShutdown(GRACEFUL_SHUTDOWN_PERIOD);
server.setStopAtShutdown(true);
configuration.configureServer(server);
try {
server.start();
server.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Connector buildConnector() {
final Connector connector = configuration.getConnector();
connector.setPort(port);
return connector;
}
private Context buildContext(ServletHolder servletHolder) {
final Context root = new Context();
root.setContextPath("/"); |
package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.ui.Model;
import java.util.List;
import java.util.ArrayList;
import twitter4j.*;
import twitter4j.conf.*;
import oauth.signpost.*;
import oauth.signpost.basic.*;
import oauth.signpost.http.HttpParameters;
import com.model.Auth;
import com.model.TwitterForm;
import com.model.Tweet;
import com.model.TwitterConfig;
@Controller
public class TwitterController {
@Autowired
Auth auth;
@Autowired
TwitterConfig twitterConfig;
@ModelAttribute
TwitterForm setUpForm() {
TwitterForm form = new TwitterForm();
form.setMessage("off");
form.setFavoriteCount(Integer.parseInt(twitterConfig.getDefaultFavoriteCount()));
return form;
}
@RequestMapping("/")
String index(@ModelAttribute TwitterForm form, Model model) {
auth.setConsumer(new DefaultOAuthConsumer(twitterConfig.getConsumerKey(), twitterConfig.getConsumerSecret()));
auth.setProvider(new DefaultOAuthProvider(twitterConfig.getRequestTokenUri(), twitterConfig.getAccessTokenUri(), twitterConfig.getAuthorizeUri()));
try {
form.setAuthUri(auth.getProvider().retrieveRequestToken(auth.getConsumer(), twitterConfig.getCallbackUri()));
} catch (Exception e) {
form.setMessage(e.getMessage());
}
model.addAttribute("form", form);
model.addAttribute("auth", auth);
return "twitter/favbom";
}
@RequestMapping("/auth")
String auth(
@RequestParam("oauth_token") String oauth_token
, @RequestParam("oauth_verifier") String oauth_verifier
, @ModelAttribute TwitterForm form, Model model) {
try {
auth.getProvider().retrieveAccessToken(auth.getConsumer(), oauth_verifier);
HttpParameters hp = auth.getProvider().getResponseParameters();
auth.setUserId(hp.get("user_id").first());
auth.setUserName(hp.get("screen_name").first());
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(twitterConfig.getConsumerKey())
.setOAuthConsumerSecret(twitterConfig.getConsumerSecret())
.setOAuthAccessToken(auth.getConsumer().getToken())
.setOAuthAccessTokenSecret(auth.getConsumer().getTokenSecret());
auth.setTwitter(new TwitterFactory(cb.build()).getInstance());
} catch (Exception e) {
form.setMessage(e.getMessage());
}
model.addAttribute("form", form);
model.addAttribute("auth", auth);
return "twitter/favbom";
}
@RequestMapping("/fav")
String fav(@ModelAttribute TwitterForm form, Model model) {
try{
List<Tweet> tweets = new ArrayList<Tweet>();
int pageCounter = 1;
int favCounter = 0;
while(favCounter < form.getFavoriteCount()) {
ResponseList<Status> statuses = auth.getTwitter().getUserTimeline(form.getToUserName(), new Paging(pageCounter ++, Integer.parseInt(twitterConfig.getPagingCount())));
if (statuses.size() == 0) {
break;
}
for(Status status : statuses){
if(favCounter >= form.getFavoriteCount()) {
break;
}
if(!status.isFavorited() && status.getInReplyToStatusId() == -1) {
Tweet tweet = new Tweet();
tweet.setId(status.getId());
tweet.setFavorited(status.isFavorited());
tweet.setText(status.getText());
tweets.add(tweet);
auth.getTwitter().createFavorite(tweet.getId());
favCounter ++;
}
}
}
form.setTweets(tweets);
} catch (Exception e) {
form.setMessage(e.getMessage());
}
model.addAttribute("form", form);
model.addAttribute("auth", auth);
return "twitter/favbom";
}
/*
@RequestMapping("/watch")
String watch(ModelMap modelMap) {
//
String accessToken = (String) session.getAttribute(SK_ACCESS_TOKEN);
String tokenSecret = (String) session.getAttribute(SK_TOKEN_SECRET);
String user_id = (String) session.getAttribute(SK_USER_ID);
String screen_name = (String) session.getAttribute(SK_SCREEN_NAME);
//
modelMap.addAttribute(RK_USER_ID, user_id);
modelMap.addAttribute(RK_SCREEN_NAME, screen_name);
return "twitter/watch";
}
@RequestMapping("/gettweets")
String gettweets(@RequestParam(RK_F_NAME) String fname, @RequestParam(RK_FAV_COUNT) String favCount, ModelMap modelMap) {
//
String accessToken = (String) session.getAttribute(SK_ACCESS_TOKEN);
String tokenSecret = (String) session.getAttribute(SK_TOKEN_SECRET);
String user_id = (String) session.getAttribute(SK_USER_ID);
String screen_name = (String) session.getAttribute(SK_SCREEN_NAME);
// twitter4j
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(CONCUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(tokenSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
int _favCount = Integer.parseInt(favCount);
List<Map> tweets = new ArrayList<Map>();
int pageCounter = 1;
int favCounter = 0;
while(favCounter < _favCount) {
//
ResponseList<Status> statuses = twitter.getUserTimeline(fname, new Paging(pageCounter ++, TW_PAGING_COUNT));
if (statuses.size() == 0) {
break;
}
for(Status status : statuses){
if(favCounter >= _favCount) {
break;
}
HashMap<String,String> map = new HashMap<String,String>();
map.put("id", String.valueOf(status.getId()));
map.put("tweet", status.getText());
if(status.isFavorited()) {
map.put("faved", "on");
} else {
map.put("faved", "off");
}
tweets.add(map);
favCounter ++;
}
}
//
modelMap.addAttribute(RK_TWEETS, tweets);
modelMap.addAttribute(RK_F_NAME, fname);
modelMap.addAttribute(RK_FAV_COUNT, favCount);
modelMap.addAttribute(RK_USER_ID, user_id);
modelMap.addAttribute(RK_SCREEN_NAME, screen_name);
modelMap.addAttribute(RK_AUTH_URI, "#");
} catch (Exception e) {
modelMap.addAttribute(RK_IS_ERROR, true);
modelMap.addAttribute(RK_MESSAGE, e.getMessage());
}
return "twitter/watch";
}
@RequestMapping("/fav2")
String fav2(@RequestParam("statusId") String statusId, @RequestParam(RK_F_NAME) String fname, @RequestParam(RK_FAV_COUNT) String favCount, ModelMap modelMap) {
try {
//
String accessToken = (String) session.getAttribute(SK_ACCESS_TOKEN);
String tokenSecret = (String) session.getAttribute(SK_TOKEN_SECRET);
String user_id = (String) session.getAttribute(SK_USER_ID);
String screen_name = (String) session.getAttribute(SK_SCREEN_NAME);
// twitter4j
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(CONCUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(tokenSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
twitter.createFavorite(Long.parseLong(statusId));
int _favCount = Integer.parseInt(favCount);
List<Map> tweets = new ArrayList<Map>();
int pageCounter = 1;
int favCounter = 0;
while(favCounter < _favCount) {
//
ResponseList<Status> statuses = twitter.getUserTimeline(fname, new Paging(pageCounter ++, TW_PAGING_COUNT));
if (statuses.size() == 0) {
break;
}
for(Status status : statuses){
if(favCounter >= _favCount) {
break;
}
HashMap<String,String> map = new HashMap<String,String>();
map.put("id", String.valueOf(status.getId()));
map.put("tweet", status.getText());
if(status.isFavorited()) {
map.put("faved", "on");
} else {
map.put("faved", "off");
}
tweets.add(map);
favCounter ++;
}
}
//
modelMap.addAttribute(RK_TWEETS, tweets);
modelMap.addAttribute(RK_F_NAME, fname);
modelMap.addAttribute(RK_FAV_COUNT, favCount);
modelMap.addAttribute(RK_USER_ID, user_id);
modelMap.addAttribute(RK_SCREEN_NAME, screen_name);
modelMap.addAttribute(RK_AUTH_URI, "#");
} catch (Exception e) {
modelMap.addAttribute(RK_IS_ERROR, true);
modelMap.addAttribute(RK_MESSAGE, e.getMessage());
}
return "twitter/watch";
}
*/
} |
package com.es.lib.common.model;
import com.es.lib.common.collection.CollectionUtil;
import com.es.lib.common.text.FioChopper;
import com.es.lib.common.text.TextUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
/**
* @author Zuzoev Dmitry - zuzoev.d@ext-system.com
* @since 23.09.16
*/
public class FullName {
private String surname;
private String name;
private String patronymic;
private List<String> others;
public FullName(String fullName) {
if (StringUtils.isBlank(fullName)) {
return;
}
final String[] parts = TextUtil.splitAsArray(fullName);
if (parts.length >= 1) {
surname = parts[0];
}
if (parts.length >= 2) {
name = parts[1];
}
if (parts.length >= 3) {
patronymic = parts[2];
}
if (parts.length >= 4) {
others = Arrays.asList(Arrays.copyOfRange(parts, 3, parts.length));
}
}
public FullName(String surname, String name, String patronymic) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
}
public String getSurname() {
return surname;
}
public String getName() {
return name;
}
public String getPatronymic() {
return patronymic;
}
public String getPatronymicFull() {
String result = StringUtils.defaultString(getPatronymic(), "");
if (CollectionUtil.isNotEmpty(others)) {
result += (" " + String.join(" ", others));
}
return result.trim();
}
public String getNotSurname() {
String result = (StringUtils.isNotBlank(name) ? name : "")
+ (StringUtils.isNotBlank(patronymic) ? " " + patronymic : "");
if (CollectionUtil.isNotEmpty(others)) {
result += (" " + String.join(" ", others));
}
return result.trim();
}
public List<String> getOthers() {
return others;
}
public List<String> toList() {
return Arrays.asList(toArray());
}
public String[] toArray() {
if (surname != null) {
if (name != null) {
if (patronymic != null) {
return new String[]{surname, name, patronymic};
}
return new String[]{surname, name};
}
return new String[]{surname};
}
return new String[0];
}
public String getFull() {
String result = (StringUtils.isNotBlank(surname) ? surname + " " : "")
+ (StringUtils.isNotBlank(name) ? name : "")
+ (StringUtils.isNotBlank(patronymic) ? " " + patronymic : "");
if (CollectionUtil.isNotEmpty(others)) {
result += (" " + String.join(" ", others));
}
return result.trim();
}
public String getChoppedLeft() {
return FioChopper.leftFullName(this);
}
public String getChoppedRight() {
return FioChopper.rightFullName(this);
}
public boolean isAllBlank() {
return StringUtils.isBlank(surname)
&& StringUtils.isBlank(name)
&& StringUtils.isBlank(patronymic);
}
public boolean isAllEmpty() {
return StringUtils.isEmpty(surname)
&& StringUtils.isEmpty(name)
&& StringUtils.isEmpty(patronymic);
}
@Override
public String toString() {
return "FullName{" +
"surname='" + surname + '\'' +
", name='" + name + '\'' +
", patronymic='" + patronymic + '\'' +
", others=" + others +
'}';
}
} |
package com.gadawski.day;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.time.DayOfWeek;
import java.util.List;
import java.util.Map;
public class DayStatsFactory {
private Map<DayOfWeek, List<DayData>> data;
private DayStatsFactory(Map<DayOfWeek, List<DayData>> data) {
this.data = data;
}
public static DayStatsFactory fromData(List<DayData> dayData) {
Map<DayOfWeek, List<DayData>> map = Maps.newHashMap();
for (DayData day : dayData) {
List<DayData> list = map.get(day.getDayOfWeek());
if (map.get(day.getDayOfWeek()) == null) {
list = Lists.newArrayList();
}
list.add(day);
map.put(day.getDayOfWeek(), list);
}
return new DayStatsFactory(map);
}
public List<DayStats> getStats() {
List<DayStats> result = Lists.newArrayList();
for (DayOfWeek day : DayOfWeek.values()) {
List<DayData> dayData = data.get(day);
if (dayData != null) {
result.add(new DayStats(dayData));
}
}
return result;
}
} |
package com.github.fjdbc.sql;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.github.fjdbc.ConnectionProvider;
import com.github.fjdbc.IntSequence;
import com.github.fjdbc.RuntimeSQLException;
import com.github.fjdbc.PreparedStatementBinder;
import com.github.fjdbc.internal.PreparedStatementEx;
import com.github.fjdbc.op.StatementOperation;
import com.github.fjdbc.query.Query;
import com.github.fjdbc.query.ResultSetExtractor;
public class StandardSql {
/**
* Debug statements by printing the value of prepared values in a comment next to the '?' placeholder.
*/
private final boolean debug;
private final ConnectionProvider cnxProvider;
/**
* @param cnxProvider
* The database connection provider.
*/
public StandardSql(ConnectionProvider cnxProvider) {
this(cnxProvider, false);
}
/**
* @param cnxProvider
* The database connection provider.
* @param debug
* Debug statements by printing the value of prepared values in a comment next to the '?' placeholder.
*/
public StandardSql(ConnectionProvider cnxProvider, boolean debug) {
this.cnxProvider = cnxProvider;
this.debug = debug;
}
/**
* Build a {@code SELECT} statement.
*/
public SqlSelectBuilder select() {
final SqlSelectBuilder res = new SqlSelectBuilder();
return res;
}
/**
* Build a {@code SELECT} statement.
*/
public SqlSelectBuilder select(String... _selects) {
final SqlSelectBuilder res = new SqlSelectBuilder();
res.select(_selects);
return res;
}
/**
* Convenience method to build a {@code SELECT DISTINCT} statement.
*/
public SqlSelectBuilder selectDistinct(String... _selects) {
final SqlSelectBuilder res = new SqlSelectBuilder().distinct();
res.select(_selects);
return res;
}
/**
* Build a {@code SELECT} statement that starts with a {@code WITH} clause.
*/
public WithClauseBuilder with(String pseudoTableName) {
return new SqlSelectBuilder().with(pseudoTableName);
}
/**
* Build an {@code UPDATE} statement.
*/
public SqlUpdateBuilder update(String tableName) {
return new SqlUpdateBuilder(tableName);
}
/**
* Build a {@code DELETE} statement.
*/
public SqlDeleteBuilder deleteFrom(String fromClause) {
return new SqlDeleteBuilder(fromClause);
}
/**
* Build an {@code INSERT} statement.
*/
public SqlInsertBuilder insertInto(String tableName) {
return new SqlInsertBuilder(tableName);
}
/**
* Build a {@code MERGE} statement.
*/
public SqlMergeBuilder mergeInto(String tableName) {
return new SqlMergeBuilder(tableName);
}
/**
* Build an SQL condition, to use in {@code WHERE} clauses for instance.
* @param lhs
* The left-hand side of the condition.
*/
public ConditionBuilder<Condition> condition(String lhs) {
final ConditionBuilder<Condition> res = new ConditionBuilder<>(lhs, null);
res.setParent(res);
return res;
}
/**
* Convert an arbitrary string to an SQL fragment.
* <p>
* The SQL fragment may then be used in any of the {@code raw} methods, or as an SQL {@code Condition}.
*/
public SqlRaw raw(String sql) {
return new SqlRaw(sql);
}
/**
* Convert an arbitrary string and a prepared statement binder to an SQL fragment.
* <p>
* The SQL fragment may then be used in any of the {@code raw} methods, or as an SQL {@code Condition}.
*/
public SqlRaw raw(String sql, PreparedStatementBinder binder) {
return new SqlRaw(sql, binder);
}
public SqlRaw raw(String sql, Object value1) {
final PreparedStatementBinder binder = PreparedStatementBinder.create(value1);
return new SqlRaw(sql, binder);
}
/**
* Build an {@code AND} condition.
* @param conditions
* The conditions to be joined with the {@code AND} operator.
*/
public CompositeConditionBuilder and(Condition... conditions) {
return new CompositeConditionBuilder(Arrays.asList(conditions), LogicalOperator.AND);
}
/**
* Build an {@code OR} condition.
* @param conditions
* The conditions to be joined with the {@code OR} operator.
*/
public CompositeConditionBuilder or(Condition... conditions) {
return new CompositeConditionBuilder(Arrays.asList(conditions), LogicalOperator.OR);
}
public Condition not(Condition condition) {
return new NotCondition(condition);
}
public Condition exists(SqlSelectStatement subquery) {
return new ExistsCondition(subquery);
}
/**
* Build a {@code SELECT} statement that is the {@code UNION} of all specified {@code SELECT} statements.
* @param selects
* The {@code SELECT} statements to join.
*/
public SqlSelectStatement union(SqlSelectBuilder... selects) {
return new CompositeSqlSelectStatement(Arrays.asList(selects), "union\n");
}
/**
* Build a {@code SELECT} statement that is the {@code UNION ALL} of all specified {@code SELECT} statements.
* @param selects
* The {@code SELECT} statements to join.
*/
public SqlSelectStatement unionAll(SqlSelectBuilder... selects) {
return new CompositeSqlSelectStatement(Arrays.asList(selects), "union all\n");
}
/**
* Build a {@code SELECT} statement that is the intersection of all specified {@code SELECT} statements.
* @param selects
* The {@code SELECT} statements to join with the {@code INTERSECT} operator.
*/
public SqlSelectStatement intersect(SqlSelectBuilder... selects) {
return new CompositeSqlSelectStatement(Arrays.asList(selects), "intersect\n");
}
/**
* Build a {@code SELECT} statement that represents {@code a MINUS b}.
* <p>
* Oracle-specific; use {@link #except} for standard SQL.
*/
public SqlSelectStatement minus(SqlSelectBuilder a, SqlSelectBuilder b) {
return new CompositeSqlSelectStatement(Arrays.asList(a, b), "minus\n");
}
/**
* Build a {@code SELECT} statement that represents {@code a EXCEPT b}.
*/
public SqlSelectStatement except(SqlSelectBuilder a, SqlSelectBuilder b) {
return new CompositeSqlSelectStatement(Arrays.asList(a, b), "except\n");
}
/**
* Build a batch statement. The batch statement is initially empty; statements must be added with the
* {@link BatchStatementBuilder#addStatement} method.
*/
public BatchStatementBuilder batchStatement() {
return new BatchStatementBuilder();
}
/**
* Build a batch statement using the specified statements.
*/
public StatementOperation batchStatement(Collection<? extends SqlStatement> statements) {
return new BatchStatementBuilder(statements).toStatement();
}
/**
* Build a batch statement from an SQL string and a stream of prepared statement binders.
*/
public <T extends PreparedStatementBinder> SqlStatement batchStatement(String sql, Stream<T> statements) {
return new StreamBackedBatchStatement<>(sql, statements, -1, -1);
}
/**
* Build a batch statement from an SQL string and a stream of prepared statement binders.
*/
public <T extends PreparedStatementBinder> StreamBackedBatchStatement<T> batchStatement(String sql,
Stream<T> statements, long executeEveryNRow, long commitEveryNRow) {
return new StreamBackedBatchStatement<>(sql, statements, executeEveryNRow, commitEveryNRow);
}
public enum RelationalOperator implements SqlFragment {
EQ("="),
NOT_EQ("<>"),
GT(">"),
GTE(">="),
LT("<"),
LTE("<="),
LIKE("like"),
IS("is"),
IS_NOT("is not"),
IN("in");
private final String value;
RelationalOperator(String value) {
this.value = value;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(value);
}
}
public static class InConditionBuilder implements Condition {
private final String sql;
private final PreparedStatementBinder binder;
public <T> InConditionBuilder(SqlFragment lhs, Collection<? extends T> values, Class<T> type) {
if (values == null) throw new IllegalArgumentException();
if (values.isEmpty()) {
sql = "1=0";
binder = null;
} else {
final int maxItemsForInClause = 1000; // Oracle limit
final ArrayList<String> sqlClauses = new ArrayList<>(values.size() / maxItemsForInClause + 1);
final List<List<String>> subCollections = SqlUtils.partition(Collections.nCopies(values.size(), "?"),
maxItemsForInClause);
for (final List<String> subCollection : subCollections) {
sqlClauses.add(
lhs.getSql() + " in (" + subCollection.stream().collect(Collectors.joining(", ")) + ")");
}
sql = sqlClauses.size() == 1 ? sqlClauses.get(0)
: ("(" + sqlClauses.stream().collect(Collectors.joining(" or ")) + ")");
binder = (ps, index) -> {
for (final T value : values) {
setAnyObject(ps, index.next(), value, type);
}
};
}
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
if (binder != null) binder.bind(ps, index);
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
}
public static class SqlRaw implements SqlFragment, Condition {
private final String sql;
/**
* May be null.
*/
private final PreparedStatementBinder binder;
public SqlRaw(String sql) {
this(sql, null);
}
public SqlRaw(String sql, PreparedStatementBinder binder) {
assert sql != null;
this.sql = sql;
this.binder = binder;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
@Override
public void bind(PreparedStatement st, IntSequence index) throws SQLException {
if (binder != null) binder.bind(st, index);
}
}
public static class SqlStringBuilder {
private final StringBuilder sb = new StringBuilder();
private int indentLevel = 0;
private boolean startLine = true;
public SqlStringBuilder append(String sql) {
if (startLine)
sb.append(Collections.nCopies(indentLevel * 4, " ").stream().collect(Collectors.joining()));
startLine = false;
sb.append(sql);
return this;
}
/**
* Convenience method
*/
public SqlStringBuilder appendln(SqlFragment sqlFragment) {
sqlFragment.appendTo(this);
appendln();
return this;
}
/**
* Convenience method
*/
public SqlStringBuilder append(SqlFragment sqlFragment) {
sqlFragment.appendTo(this);
return this;
}
/**
* Convenience method
*/
public SqlStringBuilder appendln(String sql) {
append(sql);
appendln();
return this;
}
public SqlStringBuilder appendln() {
sb.append("\n");
startLine = true;
return this;
}
public void increaseIndent() {
indentLevel++;
}
public void decreaseIndent() {
indentLevel
}
public String getSql() {
return sb.toString();
}
@Override
public String toString() {
return sb.toString();
}
}
/**
* Represents a PreparedStatement parameter.
* @param <T>
* The type of the PreparedStatement parameter.
*/
public class SqlParameter<T> implements SqlFragment {
private final T value;
private final Class<T> type;
private final String sql;
public SqlParameter(T value, Class<T> type) {
this("?", value, type);
}
public SqlParameter(String rawSql, T value, Class<T> type) {
this.sql = rawSql;
assert rawSql != null && rawSql.contains("?");
this.value = value;
this.type = type;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
if (isDebug()) {
w.append(" /* ");
w.append(value == null ? "null" : SqlUtils.escapeComment(value.toString()));
w.append(" */");
}
}
@Override
public void bind(PreparedStatement st, IntSequence index) throws SQLException {
setAnyObject(st, index.next(), value, type);
}
}
public static class ExistsCondition extends CompositeSqlFragment implements Condition {
public ExistsCondition(SqlSelectStatement wrapped) {
super(new SqlRaw("exists ("), SqlFragment.newlineIndent, wrapped, SqlFragment.dedent, new SqlRaw(")"));
}
}
public static class CompositeSqlFragment implements SqlFragment {
private final Collection<SqlFragment> fragments;
public CompositeSqlFragment(SqlFragment... fragments) {
this.fragments = Arrays.asList(fragments);
}
@Override
public void appendTo(SqlStringBuilder w) {
for (final SqlFragment fragment : fragments) {
w.append(fragment);
}
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
for (final SqlFragment fragment : fragments) {
fragment.bind(ps, index);
}
}
}
/**
* @param <P>
* the parent type
*/
public class ExpressionBuilder<P> implements SqlFragment {
private SqlFragment wrapped;
private final P parent;
public ExpressionBuilder(P parent) {
this.parent = parent;
}
@SuppressWarnings("unchecked")
public <T> P value(Object value, Class<T> _class) {
if (value == null) {
wrapped = new SqlParameter<>((T) value, null);
} else {
if (!value.getClass().equals(_class))
throw new IllegalArgumentException("Object must be of type: " + _class);
if (!PreparedStatementEx.jdbcTypes.contains(_class))
throw new IllegalArgumentException(String.format("Invalid JDBC type: %s. Allowed types are: %s",
_class, PreparedStatementEx.jdbcTypes));
wrapped = new SqlParameter<>((T) value, _class);
}
return parent;
}
// @formatter:off
public P value(String value) { wrapped = new SqlParameter<>(value, String.class); return parent; }
public P value(BigDecimal value) { wrapped = new SqlParameter<>(value, BigDecimal.class); return parent; }
public P value(Boolean value) { wrapped = new SqlParameter<>(value, Boolean.class); return parent; }
public P value(Integer value) { wrapped = new SqlParameter<>(value, Integer.class); return parent; }
public P value(Long value) { wrapped = new SqlParameter<>(value, Long.class); return parent; }
public P value(Float value) { wrapped = new SqlParameter<>(value, Float.class); return parent; }
public P value(Double value) { wrapped = new SqlParameter<>(value, Double.class); return parent; }
public P value(byte[] value) { wrapped = new SqlParameter<>(value, byte[].class); return parent; }
public P value(java.sql.Date value) { wrapped = new SqlParameter<>(value, java.sql.Date.class); return parent; }
public P value(Time value) { wrapped = new SqlParameter<>(value, Time.class); return parent; }
public P value(Timestamp value) { wrapped = new SqlParameter<>(value, Timestamp.class); return parent; }
public P value(Clob value) { wrapped = new SqlParameter<>(value, Clob.class); return parent; }
public P value(Blob value) { wrapped = new SqlParameter<>(value, Blob.class); return parent; }
public P value(Array value) { wrapped = new SqlParameter<>(value, Array.class); return parent; }
public P value(Ref value) { wrapped = new SqlParameter<>(value, Ref.class); return parent; }
public P value(URL value) { wrapped = new SqlParameter<>(value, URL.class); return parent; }
public P raw(String sql, String value) { wrapped = new SqlParameter<>(sql, value, String.class); return parent; }
public P raw(String sql, BigDecimal value) { wrapped = new SqlParameter<>(sql, value, BigDecimal.class); return parent; }
public P raw(String sql, Boolean value) { wrapped = new SqlParameter<>(sql, value, Boolean.class); return parent; }
public P raw(String sql, Integer value) { wrapped = new SqlParameter<>(sql, value, Integer.class); return parent; }
public P raw(String sql, Long value) { wrapped = new SqlParameter<>(sql, value, Long.class); return parent; }
public P raw(String sql, Float value) { wrapped = new SqlParameter<>(sql, value, Float.class); return parent; }
public P raw(String sql, Double value) { wrapped = new SqlParameter<>(sql, value, Double.class); return parent; }
public P raw(String sql, byte[] value) { wrapped = new SqlParameter<>(sql, value, byte[].class); return parent; }
public P raw(String sql, java.sql.Date value) { wrapped = new SqlParameter<>(sql, value, java.sql.Date.class); return parent; }
public P raw(String sql, Time value) { wrapped = new SqlParameter<>(sql, value, Time.class); return parent; }
public P raw(String sql, Timestamp value) { wrapped = new SqlParameter<>(sql, value, Timestamp.class); return parent; }
public P raw(String sql, Clob value) { wrapped = new SqlParameter<>(sql, value, Clob.class); return parent; }
public P raw(String sql, Blob value) { wrapped = new SqlParameter<>(sql, value, Blob.class); return parent; }
public P raw(String sql, Array value) { wrapped = new SqlParameter<>(sql, value, Array.class); return parent; }
public P raw(String sql, Ref value) { wrapped = new SqlParameter<>(sql, value, Ref.class); return parent; }
public P raw(String sql, URL value) { wrapped = new SqlParameter<>(sql, value, URL.class); return parent; }
// @formatter:on
public P raw(String _sql) {
wrapped = new SqlRaw(_sql);
return parent;
}
public P raw(String _sql, PreparedStatementBinder binder) {
wrapped = new SqlRaw(_sql, binder);
return parent;
}
/**
* @param subquery
* A subquery that returns a single row.
*/
public P subquery(SqlSelectBuilder subquery) {
wrapped = SqlFragment.wrapInParentheses(subquery, true);
return parent;
}
public P all(SqlSelectBuilder subquery) {
wrapped = new CompositeSqlFragment(new SqlRaw("all ("), SqlFragment.newlineIndent, subquery,
SqlFragment.dedent, new SqlRaw(")"));
return parent;
}
public P any(SqlSelectBuilder subquery) {
wrapped = new CompositeSqlFragment(new SqlRaw("any ("), SqlFragment.newlineIndent, subquery,
SqlFragment.dedent, new SqlRaw(")"));
return parent;
}
@Override
public void appendTo(SqlStringBuilder w) {
wrapped.appendTo(w);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
wrapped.bind(ps, index);
}
}
static <T> void setAnyObject(PreparedStatement ps, int columnIndex, T o, Class<T> type) throws SQLException {
if (o == null) {
// java.sql.Types.OTHER does not work with Oracle driver.
ps.setNull(columnIndex, java.sql.Types.INTEGER);
} else if (type.equals(String.class)) {
ps.setString(columnIndex, (String) o);
} else if (type.equals(BigDecimal.class)) {
ps.setBigDecimal(columnIndex, (BigDecimal) o);
} else if (type.equals(Boolean.class)) {
ps.setBoolean(columnIndex, (Boolean) o);
} else if (type.equals(Integer.class)) {
ps.setInt(columnIndex, (Integer) o);
} else if (type.equals(Long.class)) {
ps.setLong(columnIndex, (Long) o);
} else if (type.equals(Float.class)) {
ps.setFloat(columnIndex, (Float) o);
} else if (type.equals(Double.class)) {
ps.setDouble(columnIndex, (Double) o);
} else if (type.equals(byte[].class)) {
ps.setBytes(columnIndex, (byte[]) o);
} else if (type.equals(java.sql.Date.class)) {
ps.setDate(columnIndex, (java.sql.Date) o);
} else if (type.equals(Time.class)) {
ps.setTime(columnIndex, (Time) o);
} else if (type.equals(Timestamp.class)) {
ps.setTimestamp(columnIndex, (Timestamp) o);
} else if (type.equals(Clob.class)) {
ps.setClob(columnIndex, (Clob) o);
} else if (type.equals(Blob.class)) {
ps.setBlob(columnIndex, (Blob) o);
} else if (type.equals(Array.class)) {
ps.setArray(columnIndex, (Array) o);
} else if (type.equals(Ref.class)) {
ps.setRef(columnIndex, (Ref) o);
} else if (type.equals(URL.class)) {
ps.setURL(columnIndex, (URL) o);
}
}
public interface SqlFragment extends PreparedStatementBinder {
void appendTo(SqlStringBuilder w);
@Override
default void bind(PreparedStatement ps, IntSequence index) throws SQLException {
// do nothing
}
default String getSql() {
final SqlStringBuilder builder = new SqlStringBuilder();
appendTo(builder);
return builder.getSql();
}
public static final SqlFragment indent = w -> {
w.increaseIndent();
};
public static final SqlFragment newlineIndent = w -> {
w.appendln();
w.increaseIndent();
};
public static final SqlFragment dedent = w -> {
w.decreaseIndent();
};
public static final SqlFragment newlineDedent = w -> {
w.appendln();
w.decreaseIndent();
};
public static final SqlFragment nullLiteral = w -> w.append("NULL");
public static SqlFragment wrapInParentheses(SqlFragment fragment, boolean newlineAndIndent) {
return newlineAndIndent
? new CompositeSqlFragment(new SqlRaw("("), SqlFragment.newlineIndent, fragment,
SqlFragment.dedent, new SqlRaw(")"))
: new CompositeSqlFragment(new SqlRaw("("), fragment, new SqlRaw(")"));
}
}
public static class InSubqueryConditionBuilder implements Condition {
private final SqlFragment rhs;
private final SqlFragment lhs;
public InSubqueryConditionBuilder(SqlFragment lhs, SqlFragment rhs) {
this.lhs = lhs;
this.rhs = rhs;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(lhs);
w.appendln(" in (");
w.increaseIndent();
w.append(rhs);
w.decreaseIndent();
w.append(")");
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
lhs.bind(ps, index);
rhs.bind(ps, index);
}
}
public static class SimpleConditionBuilder implements Condition {
private final SqlFragment rhs;
private final RelationalOperator operator;
private final SqlFragment lhs;
public SimpleConditionBuilder(SqlFragment lhs, RelationalOperator operator, SqlFragment rhs) {
this.lhs = lhs;
this.rhs = rhs;
this.operator = operator;
}
@Override
public void appendTo(SqlStringBuilder w) {
lhs.appendTo(w);
w.append(" ");
operator.appendTo(w);
w.append(" ");
rhs.appendTo(w);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
lhs.bind(ps, index);
rhs.bind(ps, index);
}
}
public enum LogicalOperator implements SqlFragment {
AND("and"), OR("or");
private final String sql;
private LogicalOperator(String sql) {
this.sql = sql;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
}
public static class CompositeConditionBuilder implements Condition {
private final Collection<Condition> conditions;
private final LogicalOperator operator;
public CompositeConditionBuilder(Collection<Condition> conditions, LogicalOperator operator) {
this.conditions = new ArrayList<>(conditions);
this.operator = operator;
}
public void add(Condition condition) {
conditions.add(condition);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
for (final Condition c : conditions) {
c.bind(ps, index);
}
}
@Override
public void appendTo(SqlStringBuilder w) {
if (conditions.size() == 0) {
w.append("1=1");
} else {
if (conditions.size() > 1) w.append("(");
forEach_endAware(conditions, (c, first, last) -> {
w.append(c);
if (!last) w.append(" ").append(operator).append(" ");
});
if (conditions.size() > 1) w.append(")");
}
}
}
public static class NotCondition implements Condition {
private final Condition wrapped;
public NotCondition(Condition condition) {
assert condition != null;
this.wrapped = condition;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
wrapped.bind(ps, index);
}
@Override
public void appendTo(SqlStringBuilder w) {
w.appendln("not (");
w.increaseIndent();
w.appendln(wrapped);
w.decreaseIndent();
w.append(")");
}
}
public class ConditionBuilder<P> implements Condition {
private Condition currentCondition;
private final SqlFragment lhs;
private P parent;
public ConditionBuilder(String _lhs, P parent) {
this.lhs = new SqlRaw(_lhs);
this.parent = parent;
}
public void setParent(P parent) {
this.parent = parent;
}
public ExpressionBuilder<P> is(RelationalOperator _operator) {
final ExpressionBuilder<P> rhs = new ExpressionBuilder<>(parent);
currentCondition = new SimpleConditionBuilder(lhs, _operator, rhs);
return rhs;
}
// @formatter:off
/**
* Build an '=' expression.
*/
public ExpressionBuilder<P> eq() { return is(RelationalOperator.EQ); }
/**
* Build a '<>' expression.
*/
public ExpressionBuilder<P> notEq() { return is(RelationalOperator.NOT_EQ); }
/**
* Build a '>' expression.
*/
public ExpressionBuilder<P> gt() { return is(RelationalOperator.GT); }
/**
* Build a '<' expression.
*/
public ExpressionBuilder<P> lt() { return is(RelationalOperator.LT); }
/**
* Build a '>=' expression.
*/
public ExpressionBuilder<P> gte() { return is(RelationalOperator.GTE); }
/**
* Build a '<=' expression.
*/
public ExpressionBuilder<P> lte() { return is(RelationalOperator.LTE); }
// @formatter:on
private <U> ConditionBuilder<P> _in(Collection<? extends U> values, Class<U> type) {
final InConditionBuilder res = new InConditionBuilder(lhs, values, type);
currentCondition = res;
return this;
}
// Because of type erasure of generics we cannot have polymorphism here
// @formatter:off
public P in_String(Collection<? extends String> values) { _in(values, String.class); return parent; }
public P in_BigDecimal(Collection<? extends BigDecimal> values) { _in(values, BigDecimal.class); return parent; }
public P in_Boolean(Collection<? extends Boolean> values) { _in(values, Boolean.class); return parent; }
public P in_Integer(Collection<? extends Integer> values) { _in(values, Integer.class); return parent; }
public P in_Long(Collection<? extends Long> values) { _in(values, Long.class); return parent; }
public P in_Float(Collection<? extends Float> values) { _in(values, Float.class); return parent; }
public P in_Double(Collection<? extends Double> values) { _in(values, Double.class); return parent; }
public P in_bytes(Collection<? extends byte[]> values) { _in(values, byte[].class); return parent; }
public P in_Date(Collection<? extends java.sql.Date> values) { _in(values, java.sql.Date.class); return parent; }
public P in_Time(Collection<? extends Time> values) { _in(values, Time.class); return parent; }
public P in_Timestamp(Collection<? extends Timestamp> values) { _in(values, Timestamp.class); return parent; }
public P in_Clob(Collection<? extends Clob> values) { _in(values, Clob.class); return parent; }
public P in_Blob(Collection<? extends Blob> values) { _in(values, Blob.class); return parent; }
public P in_Array(Collection<? extends Array> values) { _in(values, Array.class); return parent; }
public P in_Ref(Collection<? extends Ref> values) { _in(values, Ref.class); return parent; }
public P in_URL(Collection<? extends URL> values) { _in(values, URL.class); return parent; }
// @formatter:on
public P in(SqlSelectBuilder subquery) {
currentCondition = new InSubqueryConditionBuilder(lhs, subquery);
return parent;
}
public P isNull() {
currentCondition = new SimpleConditionBuilder(lhs, RelationalOperator.IS, new SqlRaw("null"));
return parent;
}
public P isNotNull() {
currentCondition = new SimpleConditionBuilder(lhs, RelationalOperator.IS_NOT, new SqlRaw("null"));
return parent;
}
public P like(String text, char escapeChar) {
// TODO use placeholder instead
currentCondition = new SimpleConditionBuilder(lhs, RelationalOperator.LIKE,
new SqlRaw(SqlUtils.escapeLikeString(text, escapeChar) + "'"));
return parent;
}
public P like(String text) {
// TODO use placeholder instead
currentCondition = new SimpleConditionBuilder(lhs, RelationalOperator.LIKE,
new SqlRaw(SqlUtils.toLiteralString(text)));
return parent;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(currentCondition);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
currentCondition.bind(ps, index);
}
}
public enum JoinType implements SqlFragment {
INNER("inner join"), LEFT("left join"), RIGHT("right join"), FULL("full join"), CROSS("cross join");
private final String sql;
JoinType(String sql) {
this.sql = sql;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
}
public interface Condition extends SqlFragment {
// tag interface
}
public abstract class SqlStatement implements SqlFragment {
public final StatementOperation toStatement() {
return new StatementOperation(cnxProvider, getSql(), this);
}
}
public class SqlDeleteBuilder extends SqlStatement {
private final String fromClause;
private final Collection<SqlFragment> whereClauses = new ArrayList<>();
public SqlDeleteBuilder(String fromClause) {
this.fromClause = fromClause;
}
public ConditionBuilder<SqlDeleteBuilder> where(String lhs) {
if (lhs == null) throw new IllegalArgumentException();
final ConditionBuilder<SqlDeleteBuilder> res = new ConditionBuilder<>(lhs, this);
whereClauses.add(res);
return res;
}
public SqlDeleteBuilder where(Condition condition) {
if (condition == null) throw new IllegalArgumentException();
whereClauses.add(condition);
return this;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append("delete ").append("from ").appendln(fromClause);
if (!whereClauses.isEmpty()) {
w.appendln("where");
w.increaseIndent();
forEach_endAware(whereClauses, (clause, first, last) -> {
w.appendln(clause);
if (!last) w.append("and ");
});
w.decreaseIndent();
}
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
final CompositeIterator<SqlFragment> fragmentsIterator = new CompositeIterator<>(
Arrays.asList(whereClauses.iterator()));
while (fragmentsIterator.hasNext()) {
fragmentsIterator.next().bind(ps, index);
}
}
@Override
public String toString() {
return getSql();
}
}
public static class WithClauseBuilder implements SqlFragment {
private final String pseudoTableName;
private SqlSelectBuilder subquery;
private final SqlSelectBuilder parent;
public WithClauseBuilder(String pseudoTableName, SqlSelectBuilder parent) {
this.pseudoTableName = pseudoTableName;
this.parent = parent;
}
public SqlSelectBuilder as(SqlSelectBuilder _subquery) {
this.subquery = _subquery;
return parent;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
subquery.bind(ps, index);
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(pseudoTableName).appendln(" as (");
w.increaseIndent();
w.append(subquery);
w.decreaseIndent();
w.append(")");
}
}
public abstract class SqlSelectStatement implements SqlFragment {
public <T> Query<T> toQuery(ResultSetExtractor<T> extractor) {
return new Query<>(cnxProvider, getSql(), this, extractor);
}
}
public enum Placement {
BEFORE_KEYWORD, AFTER_KEYWORD, AFTER_EXPRESSION
}
public enum SqlSelectClause implements SqlFragment {
WITH("with"),
SELECT("select"),
FROM("from"),
WHERE("where"),
GROUP_BY("group by"),
HAVING("having"),
ORDER_BY("order by"),
OFFSET("offset"),
FETCH_FIRST("fetch first");
private final String sql;
SqlSelectClause(String sql) {
this.sql = sql;
}
@Override
public String getSql() {
return sql;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
}
/**
* Store additional raw clauses used in SELECT statements.
*/
private static class SqlRawMap {
private final List<List<SqlRaw>> rawClauses;
private static final int totalLocationCount = SqlSelectClause.values().length;
public SqlRawMap() {
final int keyCount = Placement.values().length * SqlSelectClause.values().length;
rawClauses = new ArrayList<>(keyCount);
for (int i = 0; i < keyCount; i++) {
rawClauses.add(null);
}
}
private int getIndex(Placement placement, SqlSelectClause location) {
return placement.ordinal() * totalLocationCount + location.ordinal();
}
public List<SqlRaw> get(Placement placement, SqlSelectClause location) {
final int index = getIndex(placement, location);
final List<SqlRaw> clauses = rawClauses.get(index);
return clauses == null ? Collections.emptyList() : clauses;
}
public void add(Placement placement, SqlSelectClause location, SqlRaw clause) {
final int index = getIndex(placement, location);
List<SqlRaw> clauses = rawClauses.get(index);
if (clauses == null) {
clauses = new ArrayList<>(1);
rawClauses.set(index, clauses);
}
clauses.add(clause);
}
}
public class SqlSelectBuilder extends SqlSelectStatement {
private final Collection<SqlFragment> withClauses = new ArrayList<>();
private final Collection<SqlFragment> selectClauses = new ArrayList<>();
private SqlFragment fromClause;
private final Collection<String> joinClauses = new ArrayList<>();
private final Collection<SqlFragment> whereClauses = new ArrayList<>();
private final Collection<SqlFragment> havingClauses = new ArrayList<>();
private final Collection<SqlFragment> groupByClauses = new ArrayList<>();
private final Collection<SqlFragment> orderByClauses = new ArrayList<>();
private SqlFragment offsetClause;
private SqlFragment fetchFirstClause;
private final SqlRawMap additionalClauses = new SqlRawMap();
public SqlSelectBuilder distinct() {
additionalClauses.add(Placement.AFTER_KEYWORD, SqlSelectClause.SELECT, new SqlRaw("distinct"));
return this;
}
public WithClauseBuilder with(String pseudoTableName) {
final WithClauseBuilder res = new WithClauseBuilder(pseudoTableName, this);
withClauses.add(res);
return res;
}
/**
* Add a SELECT clause having the following form:
* <p>
* {@code SELECT 'literal' as columnAlias}
*/
public SqlSelectBuilder selectLiteral(String literal, String columnAlias) {
final StringBuilder clause_str = new StringBuilder(SqlUtils.toLiteralString(literal));
if (columnAlias != null) clause_str.append(" AS " + columnAlias);
selectClauses.add(new SqlRaw(clause_str.toString()));
return this;
}
public SqlSelectBuilder select(String _selectClause) {
selectClauses.add(new SqlRaw(_selectClause));
return this;
}
public SqlSelectBuilder select(String... _selects) {
return select(Arrays.asList(_selects));
}
public SqlSelectBuilder select(Collection<String> _selects) {
this.selectClauses.addAll(_selects.stream().map(SqlRaw::new).collect(Collectors.toList()));
return this;
}
public SqlSelectBuilder from(String _fromClause) {
if (fromClause != null) throw new IllegalStateException();
this.fromClause = new SqlRaw(_fromClause);
return this;
}
public SqlSelectBuilder from(SqlSelectBuilder _fromClause) {
if (fromClause != null) throw new IllegalStateException("from clause has already been set");
this.fromClause = SqlFragment.wrapInParentheses(_fromClause, true);
return this;
}
private SqlSelectBuilder join(JoinType joinType, String joinClause) {
if (joinClause == null) throw new IllegalArgumentException();
joinClauses.add(joinType.getSql() + " " + joinClause);
return this;
}
public SqlSelectBuilder innerJoin(String joinClause) {
return join(JoinType.INNER, joinClause);
}
public SqlSelectBuilder leftJoin(String joinClause) {
return join(JoinType.LEFT, joinClause);
}
public SqlSelectBuilder rightJoin(String joinClause) {
return join(JoinType.RIGHT, joinClause);
}
public SqlSelectBuilder fullJoin(String joinClause) {
return join(JoinType.FULL, joinClause);
}
public SqlSelectBuilder crossJoin(String joinClause) {
return join(JoinType.CROSS, joinClause);
}
public ConditionBuilder<SqlSelectBuilder> where(String lhs) {
if (lhs == null) throw new IllegalArgumentException();
final ConditionBuilder<SqlSelectBuilder> res = new ConditionBuilder<>(lhs, this);
whereClauses.add(res);
return res;
}
public SqlSelectBuilder where(Condition condition) {
if (condition == null) throw new IllegalArgumentException();
whereClauses.add(condition);
return this;
}
public ConditionBuilder<SqlSelectBuilder> having(String lhs) {
if (lhs == null) throw new IllegalArgumentException();
final ConditionBuilder<SqlSelectBuilder> res = new ConditionBuilder<>(lhs, this);
havingClauses.add(res);
return res;
}
public SqlSelectBuilder having(Condition condition) {
havingClauses.add(condition);
return this;
}
public SqlSelectBuilder groupBy(String... _groupByClauses) {
for (final String f : _groupByClauses) {
groupByClauses.add(new SqlRaw(f));
}
return this;
}
public SqlSelectBuilder orderBy(String... _orderByClauses) {
for (final String f : _orderByClauses) {
orderByClauses.add(new SqlRaw(f));
}
return this;
}
/**
* Row offset. {@code 0} means no offset.<br>
* Introduced in the SQL:2008 standard.
*/
public SqlSelectBuilder offset(int offset) {
if (offsetClause != null) throw new IllegalStateException("offset clause has already been set");
offsetClause = new SqlRaw("? rows", (ps, index) -> ps.setInt(index.next(), offset));
return this;
}
public SqlSelectBuilder fetchFirst(int rowCount) {
if (fetchFirstClause != null) throw new IllegalStateException("fetch first clause has already been set");
fetchFirstClause = new SqlRaw("? rows only", (ps, index) -> ps.setInt(index.next(), rowCount));
return this;
}
public SqlSelectBuilder raw(Placement placement, SqlSelectClause location, String _sql,
PreparedStatementBinder binder) {
final SqlRaw clause = new SqlRaw(_sql, binder);
additionalClauses.add(placement, location, clause);
return this;
}
public SqlSelectBuilder raw(Placement placement, SqlSelectClause location, String _sql) {
return raw(placement, location, _sql, null);
}
/**
* @param w
* @param clause The type of SELECT clause.
* @param fragments The SQL fragments making the SQL clause.
* @param newline If
* {@code true, separate fragments with newline and increment indentation of fragments (except when there is only one fragment).
* @param joinString The join string between fragments.
*/
private void writeClause(SqlStringBuilder w, SqlSelectClause clause,
Collection<? extends SqlFragment> fragments, boolean newline, String joinString) {
additionalClauses.get(Placement.BEFORE_KEYWORD, clause).forEach(w::appendln);
if (!fragments.isEmpty()) {
w.append(clause);
additionalClauses.get(Placement.AFTER_KEYWORD, clause).forEach(i -> w.append(" ").append(i));
if (newline && fragments.size() > 1) {
w.appendln();
w.increaseIndent();
} else {
w.append(" ");
}
forEach_endAware(fragments, (fragment, first, last) -> {
if (newline)
w.appendln(fragment);
else w.append(fragment);
if (!last) w.append(joinString);
});
if (newline) {
if (fragments.size() > 1) w.decreaseIndent();
} else {
w.appendln();
}
} else {
additionalClauses.get(Placement.AFTER_KEYWORD, clause).forEach(w::appendln);
}
additionalClauses.get(Placement.AFTER_EXPRESSION, clause).forEach(w::appendln);
}
@Override
public void appendTo(SqlStringBuilder w) {
writeClause(w, SqlSelectClause.WITH, withClauses, true, ",");
writeClause(w, SqlSelectClause.SELECT, selectClauses, false, ", ");
// begin - special case for "from" clause
additionalClauses.get(Placement.BEFORE_KEYWORD, SqlSelectClause.FROM).forEach(w::appendln);
w.append(SqlSelectClause.FROM).append(" ");
additionalClauses.get(Placement.AFTER_KEYWORD, SqlSelectClause.FROM)
.forEach(i -> w.append(i).append(" "));
w.appendln(fromClause);
joinClauses.forEach(w::appendln);
additionalClauses.get(Placement.AFTER_EXPRESSION, SqlSelectClause.FROM).forEach(w::appendln);
// end - special case for "from" clause
writeClause(w, SqlSelectClause.WHERE, whereClauses, true, "and ");
writeClause(w, SqlSelectClause.GROUP_BY, groupByClauses, false, ", ");
writeClause(w, SqlSelectClause.HAVING, havingClauses, true, "and ");
writeClause(w, SqlSelectClause.ORDER_BY, orderByClauses, false, ", ");
writeClause(w, SqlSelectClause.OFFSET, getOffsetClauses(), false, "");
writeClause(w, SqlSelectClause.FETCH_FIRST, getFetchFirstClauses(), false, "");
}
public Collection<SqlFragment> getOffsetClauses() {
return offsetClause == null ? Collections.emptyList() : Collections.singleton(offsetClause);
}
public Collection<SqlFragment> getFetchFirstClauses() {
return fetchFirstClause == null ? Collections.emptyList() : Collections.singleton(fetchFirstClause);
}
public Collection<SqlFragment> getFromClauses() {
return Collections.singleton(fromClause);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
// @formatter:off
final CompositeIterator<SqlFragment> fragmentsIterator = new CompositeIterator<>(Arrays.asList(
withClauses.iterator(),
selectClauses.iterator(),
getFromClauses().iterator(),
whereClauses.iterator(),
groupByClauses.iterator(),
havingClauses.iterator(),
orderByClauses.iterator(),
getOffsetClauses().iterator(),
getFetchFirstClauses().iterator()
));
// @formatter:on
while (fragmentsIterator.hasNext()) {
fragmentsIterator.next().bind(ps, index);
}
}
@Override
public String toString() {
return getSql();
}
}
public static class SetValueClause implements SqlFragment {
private final String columnName;
private final ExpressionBuilder<InsertValuesBuilder> value;
public SetValueClause(String columnName, ExpressionBuilder<InsertValuesBuilder> value) {
this.columnName = columnName;
this.value = value;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(columnName).append(" = ").append(value);
}
public String getColumnName() {
return columnName;
}
public ExpressionBuilder<InsertValuesBuilder> getValue() {
return value;
}
@Override
public void bind(PreparedStatement st, IntSequence index) throws SQLException {
value.bind(st, index);
}
}
public static class UpdateSetClause implements SqlFragment {
private final String columnName;
private final ExpressionBuilder<SqlUpdateBuilder> value;
public UpdateSetClause(String columnName, ExpressionBuilder<SqlUpdateBuilder> value) {
this.columnName = columnName;
this.value = value;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(columnName).append(" = ").append(value);
}
public String getColumnName() {
return columnName;
}
public ExpressionBuilder<SqlUpdateBuilder> getValue() {
return value;
}
@Override
public void bind(PreparedStatement st, IntSequence index) throws SQLException {
value.bind(st, index);
}
}
public class InsertValuesBuilder implements SqlFragment {
private final Collection<SetValueClause> setClauses = new ArrayList<>();
public InsertValuesBuilder() {
this(Collections.emptyList());
}
public InsertValuesBuilder(Collection<? extends SetValueClause> _setClauses) {
setClauses.addAll(_setClauses);
}
public ExpressionBuilder<InsertValuesBuilder> set(String columnName) {
final ExpressionBuilder<InsertValuesBuilder> res = new ExpressionBuilder<>(this);
setClauses.add(new SetValueClause(columnName, res));
return res;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
for (final SetValueClause clause : setClauses) {
clause.bind(ps, index);
}
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append("(");
w.append(setClauses.stream().map(SetValueClause::getColumnName).collect(Collectors.joining(", ")));
w.append(")");
w.appendln();
w.append("values (");
w.append(setClauses.stream().map(SetValueClause::getValue).map(SqlFragment::getSql).collect(
Collectors.joining(", ")));
w.append(")");
}
}
public class SqlInsertBuilder extends SqlStatement {
private final String tableName;
private SqlFragment body;
private Collection<String> columns;
public SqlInsertBuilder(String tableName) {
this.tableName = tableName;
}
public SqlSelectBuilder subquery(String... _columns) {
if (body != null) throw new IllegalArgumentException();
this.columns = Arrays.asList(_columns);
final SqlSelectBuilder res = new SqlSelectBuilder();
body = res;
return res;
}
public InsertValuesBuilder values() {
if (body instanceof InsertValuesBuilder) return (InsertValuesBuilder) body;
if (body != null) throw new IllegalArgumentException();
final InsertValuesBuilder res = new InsertValuesBuilder();
body = res;
return res;
}
/**
* Convience method. Equivalent to: {@code values().set(columnName)}.
*/
public ExpressionBuilder<InsertValuesBuilder> set(String columnName) {
return values().set(columnName);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
body.bind(ps, index);
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append("insert into ").append(tableName);
if (columns != null) {
w.append(" (");
w.append(columns.stream().collect(Collectors.joining(", ")));
w.appendln(")");
}
w.append(body);
}
}
public class SqlUpdateBuilder extends SqlStatement {
private final Collection<SqlFragment> whereClauses = new ArrayList<>();
private final Collection<UpdateSetClause> setClauses = new ArrayList<>();
private final String tableName;
public SqlUpdateBuilder(String tableName) {
this.tableName = tableName;
}
public ExpressionBuilder<SqlUpdateBuilder> set(String columnName) {
final ExpressionBuilder<SqlUpdateBuilder> res = new ExpressionBuilder<>(this);
setClauses.add(new UpdateSetClause(columnName, res));
return res;
}
public ConditionBuilder<SqlUpdateBuilder> where(String lhs) {
if (lhs == null) throw new IllegalArgumentException();
final ConditionBuilder<SqlUpdateBuilder> res = new ConditionBuilder<>(lhs, this);
whereClauses.add(res);
return res;
}
public SqlUpdateBuilder where(Condition condition) {
if (condition == null) throw new IllegalArgumentException();
whereClauses.add(condition);
return this;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append("update ").append(tableName).appendln(" set");
w.increaseIndent();
forEach_endAware(setClauses, (clause, first, last) -> {
w.append(clause);
w.appendln(last ? "" : ",");
});
w.decreaseIndent();
if (!whereClauses.isEmpty()) {
w.appendln("where");
w.increaseIndent();
forEach_endAware(whereClauses, (clause, first, last) -> {
w.appendln(clause);
if (!last) w.append("and ");
});
w.decreaseIndent();
}
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
final CompositeIterator<SqlFragment> fragmentsIterator = new CompositeIterator<>(
Arrays.asList(setClauses.iterator(), whereClauses.iterator()));
while (fragmentsIterator.hasNext()) {
fragmentsIterator.next().bind(ps, index);
}
}
}
public enum SqlMergeClauseFlag {
ON_CLAUSE, UPDATE_CLAUSE, INSERT_CLAUSE
}
public static class SqlMergeClause implements SqlFragment {
private final EnumSet<SqlMergeClauseFlag> flags;
private final String columnName;
private final ExpressionBuilder<SqlMergeBuilder> value;
public SqlMergeClause(EnumSet<SqlMergeClauseFlag> flags, String columnName,
ExpressionBuilder<SqlMergeBuilder> value) {
this.flags = flags;
this.columnName = columnName;
this.value = value;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
value.bind(ps, index);
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(columnName).append(" = ").append(value);
}
public EnumSet<SqlMergeClauseFlag> getFlags() {
return flags;
}
public String getColumnName() {
return columnName;
}
public ExpressionBuilder<SqlMergeBuilder> getValue() {
return value;
}
}
public class SqlMergeBuilder extends SqlStatement {
private final String tableName;
private final Collection<SqlMergeClause> setClauses = new ArrayList<>();
public SqlMergeBuilder(String tableName) {
this.tableName = tableName;
}
public ExpressionBuilder<SqlMergeBuilder> on(String columnName) {
final ExpressionBuilder<SqlMergeBuilder> res = new ExpressionBuilder<>(this);
setClauses.add(new SqlMergeClause(
EnumSet.of(SqlMergeClauseFlag.ON_CLAUSE, SqlMergeClauseFlag.INSERT_CLAUSE), columnName, res));
return res;
}
public ExpressionBuilder<SqlMergeBuilder> insertOrUpdate(String columnName) {
final ExpressionBuilder<SqlMergeBuilder> res = new ExpressionBuilder<>(this);
setClauses.add(new SqlMergeClause(
EnumSet.of(SqlMergeClauseFlag.UPDATE_CLAUSE, SqlMergeClauseFlag.INSERT_CLAUSE), columnName, res));
return res;
}
public ExpressionBuilder<SqlMergeBuilder> insert(String columnName) {
final ExpressionBuilder<SqlMergeBuilder> res = new ExpressionBuilder<>(this);
setClauses.add(new SqlMergeClause(EnumSet.of(SqlMergeClauseFlag.INSERT_CLAUSE), columnName, res));
return res;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
final List<SqlMergeClause> onClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.ON_CLAUSE))
.collect(Collectors.toList());
final List<SqlMergeClause> updateClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.UPDATE_CLAUSE))
.collect(Collectors.toList());
final List<SqlMergeClause> insertClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.INSERT_CLAUSE))
.collect(Collectors.toList());
final CompositeIterator<SqlMergeClause> it = new CompositeIterator<>(
Arrays.asList(onClauses.iterator(), updateClauses.iterator(), insertClauses.iterator()));
while (it.hasNext()) {
it.next().bind(ps, index);
}
}
@Override
public void appendTo(SqlStringBuilder w) {
final List<SqlMergeClause> onClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.ON_CLAUSE))
.collect(Collectors.toList());
final List<SqlMergeClause> updateClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.UPDATE_CLAUSE))
.collect(Collectors.toList());
final List<SqlMergeClause> insertClauses = setClauses.stream()
.filter(c -> c.getFlags().contains(SqlMergeClauseFlag.INSERT_CLAUSE))
.collect(Collectors.toList());
w.append("merge into ").append(tableName).appendln(" using dual on (");
w.increaseIndent();
forEach_endAware(onClauses, (clause, first, last) -> {
if (!first) w.append("and ");
w.appendln(clause);
});
w.decreaseIndent();
w.appendln(")");
if (!updateClauses.isEmpty()) {
w.appendln("when matched then update set");
w.increaseIndent();
forEach_endAware(updateClauses, (clause, first, last) -> {
w.append(clause);
w.appendln(last ? "" : ",");
});
w.decreaseIndent();
}
w.append("when not matched then insert (");
w.append(insertClauses.stream().map(SqlMergeClause::getColumnName).collect(Collectors.joining(", ")));
w.append(") values (");
w.append(insertClauses.stream().map(SqlMergeClause::getValue).map(SqlFragment::getSql).collect(
Collectors.joining(", ")));
w.append(")");
}
}
@FunctionalInterface
private interface EndAwareConsumer<T> {
void accept(T value, boolean first, boolean last);
}
static <T> void forEach_endAware(Collection<? extends T> collection, EndAwareConsumer<T> consumer) {
final int count = collection.size();
int i = 0;
for (final T t : collection) {
consumer.accept(t, i == 0, i == count - 1);
i++;
}
}
public class CompositeSqlSelectStatement extends SqlSelectStatement {
private final Collection<SqlSelectStatement> fragments;
private final String joinClause;
public CompositeSqlSelectStatement(Collection<SqlSelectStatement> fragments, String joinClause) {
this.fragments = fragments;
this.joinClause = joinClause;
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
for (final SqlFragment fragment : fragments) {
fragment.bind(ps, index);
}
}
@Override
public void appendTo(SqlStringBuilder w) {
forEach_endAware(fragments, (fragment, first, last) -> {
w.append(fragment);
if (!last) w.append(joinClause);
});
}
}
/**
* Represent a batch statement. Unlike in JDBC where a batch statement is represented by a single
* {@link java.sql.Statement} object, here the BatchStatement holds a collection of {@link SqlStatement} items.
* <p>
* Warning: each {@link SqlStatement} item must represent the same SQL statement. Only the first statement will be
* converted to SQL.
* <p>
* At the moment, there is no check to actually make sure the SQL is the same. This may change in the future.
*/
public class BatchStatementBuilder extends SqlStatement {
private final Collection<SqlStatement> statements;
private long executeEveryNRow = -1;
private long commitEveryNRow = -1;
public BatchStatementBuilder() {
this.statements = new ArrayList<>();
}
public BatchStatementBuilder executeEveryNRow(int _executeEveryNRow) {
this.executeEveryNRow = _executeEveryNRow;
return this;
}
public BatchStatementBuilder commitEveryNRow(int _commitEveryNRow) {
this.commitEveryNRow = _commitEveryNRow;
return this;
}
public BatchStatementBuilder(Collection<? extends SqlStatement> statements) {
this.statements = new ArrayList<>(statements);
}
public void addStatement(SqlStatement statement) {
statements.add(statement);
}
@Override
public void appendTo(SqlStringBuilder w) {
if (statements.isEmpty()) return;
statements.iterator().next().appendTo(w);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
final String sql = statements.iterator().next().getSql();
final StreamBackedBatchStatement<SqlStatement> wrapped = new StreamBackedBatchStatement<>(sql,
statements.stream(), executeEveryNRow, commitEveryNRow);
wrapped.bind(ps, index);
}
}
/**
* Create a batch statement from an SQL string and a stream of prepared statement binders.
*/
public class StreamBackedBatchStatement<T extends PreparedStatementBinder> extends SqlStatement {
private final Stream<T> statements;
private final String sql;
private final long executeEveryNRow;
private final long commitEveryNRow;
private BiConsumer<SQLException, T> errorHandler = (e, statement) -> {
throw new RuntimeSQLException(e);
};
private AtomicBoolean cancelRequested = new AtomicBoolean();
public StreamBackedBatchStatement(String sql, Stream<T> statements, final long executeEveryNRow,
final long commitEveryNRow) {
this.sql = sql;
this.statements = statements;
this.executeEveryNRow = executeEveryNRow;
this.commitEveryNRow = commitEveryNRow;
}
public StreamBackedBatchStatement<T> setErrorHandler(BiConsumer<SQLException, T> errorHandler) {
this.errorHandler = errorHandler;
return this;
}
@Override
public void appendTo(SqlStringBuilder w) {
w.append(sql);
}
/**
* {@code cancelRequested} is an {@code AtomicBoolean} instance that allows to cancel the execution from a
* different thread.<br>
* If not set, an instance is provided by default.
*/
public void setCancelRequestAtomicBoolean(AtomicBoolean cancelRequested) {
this.cancelRequested = cancelRequested;
}
/**
* Request the cancellation of this statement.
* This method is thread-safe.
*/
public void cancel() {
cancelRequested.set(true);
}
@Override
public void bind(PreparedStatement ps, IntSequence index) throws SQLException {
final IntSequence count = new IntSequence(0);
try {
statements.forEachOrdered(s -> {
try {
s.bind(ps, index);
ps.addBatch();
count.next();
if (cancelRequested.get()) {
cnxProvider.rollback(ps.getConnection());
throw new CancellationException();
}
if (executeEveryNRow > 0 && (count.get() % executeEveryNRow) == 0) {
ps.executeBatch();
}
if (commitEveryNRow > 0 && (count.get() % commitEveryNRow) == 0) {
cnxProvider.commit(ps.getConnection());
}
} catch (final SQLException e) {
errorHandler.accept(e, s);
} finally {
index.reset();
}
});
} catch (final Exception e) {
if (!(e instanceof CancellationException)) {
throw e;
}
}
}
}
/**
* Debug statements by printing the value of prepared values in a comment next to the '?' placeholder.
*/
public boolean isDebug() {
return debug;
}
} |
package com.github.lstephen.ootp.ai;
import com.github.lstephen.ootp.ai.config.Config;
import com.github.lstephen.ootp.ai.data.Id;
import com.github.lstephen.ootp.ai.draft.DraftReport;
import com.github.lstephen.ootp.ai.io.Printables;
import com.github.lstephen.ootp.ai.ootp5.report.SpringTraining;
import com.github.lstephen.ootp.ai.player.Player;
import com.github.lstephen.ootp.ai.player.ratings.PlayerRatings;
import com.github.lstephen.ootp.ai.regression.BattingRegression;
import com.github.lstephen.ootp.ai.regression.PitchingRegression;
import com.github.lstephen.ootp.ai.regression.Predictor;
import com.github.lstephen.ootp.ai.report.FreeAgents;
import com.github.lstephen.ootp.ai.report.GenericValueReport;
import com.github.lstephen.ootp.ai.report.HittingSelectionReport;
import com.github.lstephen.ootp.ai.report.LeagueBattingReport;
import com.github.lstephen.ootp.ai.report.PitchingStrategyReport;
import com.github.lstephen.ootp.ai.report.SalaryReport;
import com.github.lstephen.ootp.ai.report.TeamPositionReport;
import com.github.lstephen.ootp.ai.report.TeamReport;
import com.github.lstephen.ootp.ai.roster.Changes;
import com.github.lstephen.ootp.ai.roster.Changes.ChangeType;
import com.github.lstephen.ootp.ai.roster.FourtyManRoster;
import com.github.lstephen.ootp.ai.roster.Moves;
import com.github.lstephen.ootp.ai.roster.Roster;
import com.github.lstephen.ootp.ai.roster.Roster.Status;
import com.github.lstephen.ootp.ai.roster.RosterSelection;
import com.github.lstephen.ootp.ai.roster.Team;
import com.github.lstephen.ootp.ai.selection.BestStartersSelection;
import com.github.lstephen.ootp.ai.selection.Mode;
import com.github.lstephen.ootp.ai.selection.Selections;
import com.github.lstephen.ootp.ai.selection.bench.Bench;
import com.github.lstephen.ootp.ai.selection.depthchart.AllDepthCharts;
import com.github.lstephen.ootp.ai.selection.depthchart.DepthChartSelection;
import com.github.lstephen.ootp.ai.selection.lineup.AllLineups;
import com.github.lstephen.ootp.ai.selection.lineup.LineupSelection;
import com.github.lstephen.ootp.ai.selection.rotation.Rotation;
import com.github.lstephen.ootp.ai.selection.rotation.RotationSelection;
import com.github.lstephen.ootp.ai.site.SingleTeam;
import com.github.lstephen.ootp.ai.site.Site;
import com.github.lstephen.ootp.ai.site.SiteDefinition;
import com.github.lstephen.ootp.ai.site.SiteHolder;
import com.github.lstephen.ootp.ai.site.impl.SiteDefinitionFactory;
import com.github.lstephen.ootp.ai.stats.SplitPercentages;
import com.github.lstephen.ootp.ai.stats.SplitPercentagesHolder;
import com.github.lstephen.ootp.ai.stats.SplitStats;
import com.github.lstephen.ootp.ai.value.JavaAdapter;
import com.github.lstephen.ootp.ai.value.PlayerValue;
import com.github.lstephen.ootp.ai.value.ReplacementLevels$;
import com.github.lstephen.ootp.extract.html.Page;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Stopwatch;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.joda.time.DateTimeConstants;
/** @author lstephen */
public class Main {
private static final Logger LOG = Logger.getLogger(Main.class.getName());
private static final SiteDefinition TWML =
SiteDefinitionFactory.ootp6(
"TWML",
"http:
Id.<Team>valueOf(15),
"Splendid Splinter",
16);
private static final SiteDefinition CBL =
SiteDefinitionFactory.ootp5(
"CBL", "http:
private static final SiteDefinition HFTC =
SiteDefinitionFactory.ootp5(
"HFTC", "http:
private static final SiteDefinition OLD_BTH_CHC =
SiteDefinitionFactory.ootp6(
"BTH",
"http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/",
Id.<Team>valueOf(20),
"National",
30);
private static final SiteDefinition OLD_BTH_NYY =
SiteDefinitionFactory.ootp6(
"OLD_BTH_NYY",
"http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/",
Id.<Team>valueOf(3),
"American",
30);
private static final SiteDefinition BTHUSTLE =
SiteDefinitionFactory.ootp6(
"BTHUSTLE",
"http://bthbaseball.allsimbaseball10.com/game/lgreports/",
Id.<Team>valueOf(14),
"National",
16);
private static final SiteDefinition SAVOY =
SiteDefinitionFactory.ootp5(
"SAVOY", "http:
private static final SiteDefinition LBB =
SiteDefinitionFactory.ootp5(
"LBB", "http://bbs56.net/LBB/Site/Leaguesite/", Id.<Team>valueOf(3), "AL", 20);
private static final SiteDefinition GABL =
SiteDefinitionFactory.ootp5(
"GABL",
"http:
Id.<Team>valueOf(22),
"National",
30);
private static final SiteDefinition TFMS =
SiteDefinitionFactory.ootp5("TFMS", "tfms5-2004/", Id.<Team>valueOf(3), "League 2", 16);
private static final ImmutableMap<String, SiteDefinition> SITES =
ImmutableMap.<String, SiteDefinition>builder()
.put("TWML", TWML)
.put("CBL", CBL)
.put("HFTC", HFTC)
.put("OLD_BTH_CHC", OLD_BTH_CHC)
.put("OLD_BTH_NYY", OLD_BTH_NYY)
.put("BTHUSTLE", BTHUSTLE)
.put("LBB", LBB)
.put("SAVOY", SAVOY)
.put("GABL", GABL)
.build();
private static ImmutableSet<SiteDefinition> LOOK_TO_NEXT_SEASON = ImmutableSet.of();
private static ImmutableSet<SiteDefinition> INAUGURAL_DRAFT = ImmutableSet.of();
public static void main(String[] args) throws IOException {
new Main().run();
}
public void run() throws IOException {
String site = System.getenv("OOTPAI_SITE");
if (site == null) {
throw new IllegalStateException("OOTPAI_SITE is required");
}
run(SITES.get(site));
}
private void run(SiteDefinition def) throws IOException {
Preconditions.checkNotNull(def, "SiteDefinition not found");
File outputDirectory = new File(Config.createDefault().getValue("output.dir").or("c:/ootp"));
try (FileOutputStream out =
new FileOutputStream(new File(outputDirectory, def.getName() + ".txt"), false)) {
run(def, out);
}
}
private void run(SiteDefinition def, OutputStream out) throws IOException {
LOG.log(Level.INFO, "Running for {0}...", def.getName());
String clearCache = System.getenv("OOTPAI_CLEAR_CACHE");
if ("true".equals(clearCache)) {
LOG.log(Level.INFO, "Clearing cache...");
def.getSite().clearCache();
}
Boolean isLookToNextSeason = Boolean.FALSE;
Boolean isPlayoffs = "true".equals(System.getenv("OOTPAI_PLAYOFFS"));
if (LOOK_TO_NEXT_SEASON.contains(def)) {
isLookToNextSeason = Boolean.TRUE;
}
final Site site = def.getSite();
SiteHolder.set(site);
LOG.log(Level.INFO, "Warming team cache...");
site.getTeamIds()
.parallelStream()
.flatMap(
id ->
Stream.of("team%s.html", "team%spr.html", "team%ssa.html")
.map(s -> String.format(s, id.get())))
.map(site::getPage)
.forEach(Page::load);
LOG.log(Level.INFO, "Warming player cache...");
site.getPage("pagents.html").load();
Iterable<Player> allPlayers = site.getAllPlayers();
Printables.print(LeagueBattingReport.create(site)).to(out);
LOG.log(Level.INFO, "Extracting current roster and team...");
Roster oldRoster = site.extractRoster();
Context$.MODULE$.oldRoster_$eq(oldRoster);
Team team = site.extractTeam();
LOG.log(Level.INFO, "Running regressions...");
SplitPercentages pcts = SplitPercentages.create(site);
SplitPercentagesHolder.set(pcts);
final BattingRegression battingRegression = BattingRegression.run(site);
Printables.print(battingRegression.correlationReport()).to(out);
final PitchingRegression pitchingRegression = PitchingRegression.run(site);
Printables.print(pitchingRegression.correlationReport()).to(out);
LOG.info("Setting up Predictions...");
final Predictor predictor = new Predictor(allPlayers, battingRegression, pitchingRegression);
pcts.print(out);
SplitStats.setPercentages(pcts);
PlayerRatings.setPercentages(pcts);
BestStartersSelection.setPercentages(pcts);
Bench.setPercentages(pcts);
LOG.info("Loading manual changes...");
Changes changes = Changes.load(site);
team.processManualChanges(changes);
boolean isExpandedRosters = site.getDate().getMonthOfYear() == DateTimeConstants.SEPTEMBER;
int month = site.getDate().getMonthOfYear();
Mode mode = Mode.REGULAR_SEASON;
if (month < DateTimeConstants.APRIL) {
mode = Mode.PRESEASON;
} else if (isExpandedRosters) {
mode = Mode.EXPANDED;
}
LOG.info("Loading FAS...");
FreeAgents fas = FreeAgents.create(site, changes, predictor);
RosterSelection selection = new RosterSelection(team, predictor);
selection.setPrevious(oldRoster);
LOG.log(Level.INFO, "Selecting ideal roster...");
Context$.MODULE$.idealRoster_$eq(selection.select(Mode.IDEAL));
LOG.info("Calculating top FA targets...");
Iterable<Player> topFaTargets = fas.getTopTargets(mode);
Integer minRosterSize = 70;
Integer maxRosterSize = 75;
ImmutableSet<Player> futureFas = ImmutableSet.of();
if (isLookToNextSeason) {
futureFas = ImmutableSet.copyOf(Iterables.filter(team, site.isFutureFreeAgent()));
System.out.print("Removing (FA):");
for (Player p : Player.byShortName().immutableSortedCopy(futureFas)) {
System.out.print(p.getShortName() + "/");
}
System.out.println();
team.remove(futureFas);
}
LOG.log(Level.INFO, "Selecting new rosters...");
Stopwatch sw = Stopwatch.createStarted();
Mode selectionMode = mode;
if (isPlayoffs) {
selectionMode = Mode.PLAYOFFS;
}
Roster newRoster = selection.select(selectionMode, changes);
newRoster.setTargetMinimum(minRosterSize);
newRoster.setTargetMaximum(maxRosterSize);
Context$.MODULE$.newRoster_$eq(newRoster);
sw.stop();
LOG.log(Level.INFO, "Roster selection time: " + sw);
Printables.print(new HittingSelectionReport(newRoster, predictor, site.getTeamBatting()))
.to(out);
selection.printPitchingSelectionTable(out, newRoster, site.getTeamPitching());
Printables.print(newRoster).to(out);
LOG.info("Calculating roster changes...");
Printables.print(newRoster.getChangesFrom(oldRoster)).to(out);
LOG.log(Level.INFO, "Choosing rotation...");
Rotation rotation =
RotationSelection.forMode(selectionMode, predictor)
.selectRotation(
ImmutableSet.<Player>of(),
Selections.onlyPitchers(newRoster.getPlayers(Status.ML)));
Printables.print(rotation).to(out);
Printables.print(new PitchingStrategyReport(rotation, predictor)).to(out);
LOG.log(Level.INFO, "Choosing lineups...");
AllLineups lineups =
new LineupSelection(predictor)
.select(Selections.onlyHitters(newRoster.getPlayers(Status.ML)));
LOG.log(Level.INFO, "Choosing Depth Charts...");
AllDepthCharts depthCharts =
new DepthChartSelection(predictor)
.select(lineups, Selections.onlyHitters(newRoster.getPlayers(Status.ML)));
Printables.print(depthCharts).to(out);
Printables.print(lineups).to(out);
LOG.info("Salary report...");
SalaryReport salary = new SalaryReport(team, site.getSalary(), site.getFinancials(), predictor);
final GenericValueReport generic = new GenericValueReport(team, predictor, salary);
generic.setReverse(false);
LOG.log(Level.INFO, "Strategy...");
generic.setTitle("Bunt for Hit");
generic.setPlayers(
newRoster
.getPlayers(Status.ML)
.stream()
.filter(p -> p.getBuntForHitRating().normalize().get() > 80)
.collect(Collectors.toSet()));
generic.print(out);
double stealingBreakEven = 0.590 + 3.33 * lineups.getHomeRunsPerPlateAppearance(predictor);
generic.setTitle("Stealing @ " + String.format("%.1f", stealingBreakEven * 100.0));
generic.setPlayers(
newRoster
.getPlayers(Status.ML)
.stream()
.filter(p -> p.getStealingRating().normalize().get() > stealingBreakEven * 100.0)
.collect(Collectors.toSet()));
generic.print(out);
//Break Even Rate = 0.590 + 3.33 x (HR/PA)
if (site.getDate().getMonthOfYear() == DateTimeConstants.MARCH) {
LOG.log(Level.INFO, "Spring training...");
Printables.print(SpringTraining.create(site.getType(), newRoster.getAllPlayers())).to(out);
}
Printables.print(ReplacementLevels$.MODULE$.getForIdeal(predictor)).to(out);
LOG.info("Draft...");
ImmutableSet<Player> drafted = ImmutableSet.copyOf(changes.get(Changes.ChangeType.PICKED));
Iterable<Player> remaining =
Sets.difference(
ImmutableSet.copyOf(FluentIterable.from(site.getDraft()).filter(Predicates.notNull())),
drafted);
if (!Iterables.isEmpty(remaining)) {
generic.setTitle("Drafted");
generic.setPlayers(drafted);
generic.print(out);
generic.setTitle("Remaining");
generic.setPlayers(remaining);
generic.print(out);
}
DraftReport.create(site, predictor).print(out);
Printables.print(salary).to(out);
LOG.info("Extensions report...");
generic.setTitle("Extensions");
generic.setPlayers(
Iterables.concat(
Iterables.filter(newRoster.getAllPlayers(), site.isFutureFreeAgent()), futureFas));
generic.print(out);
LOG.info("Arbitration report...");
generic.setTitle("Arbitration");
generic.setPlayers(
Iterables.filter(
newRoster.getAllPlayers(),
new Predicate<Player>() {
public boolean apply(Player p) {
return p.getSalary().endsWith("a");
}
}));
generic.print(out);
if (def.getName().equals("BTHUSTLE")) {
LOG.info("40 man roster reports...");
FourtyManRoster fourtyMan = new FourtyManRoster(team, newRoster, predictor);
Printables.print(fourtyMan).to(out);
generic.setTitle("+40");
generic.setPlayers(
ImmutableSet.<Player>builder()
.addAll(fourtyMan.getPlayersToAdd())
.addAll(
FluentIterable.from(changes.get(ChangeType.FOURTY_MAN))
.filter(Predicates.in(newRoster.getAllPlayers())))
.build());
generic.print(out);
generic.setTitle("-40");
generic.setPlayers(fourtyMan.getPlayersToRemove());
generic.print(out);
generic.setTitle("Waive");
generic.setPlayers(isExpandedRosters ? ImmutableSet.of() : fourtyMan.getPlayersToWaive());
generic.print(out);
}
if (def.getName().equals("BTHUSTLE")) {
LOG.info("Waviers report...");
generic.setTitle("Waivers");
generic.setPlayers(site.getWaiverWire());
generic.print(out);
if (site.getDate().getMonthOfYear() < DateTimeConstants.APRIL) {
LOG.info("Rule 5...");
generic.setTitle("Rule 5");
generic.setPlayers(
Iterables.filter(
site.getRuleFiveDraft(),
new Predicate<Player>() {
public boolean apply(Player p) {
return JavaAdapter.nowValue(p, predictor).vsReplacement().get().toLong() >= 0;
}
}));
generic.print(out);
}
}
Moves moves = new Moves(newRoster, changes, predictor);
generic.setTitle("Release");
generic.setPlayers(moves.getRelease());
generic.print(out);
generic.setTitle("Sign");
generic.setPlayers(moves.getSign());
generic.print(out);
LOG.info("FA report...");
generic.setTitle("Top Targets");
generic.setPlayers(topFaTargets);
generic.print(out);
generic.setTitle("Free Agents");
generic.setPlayers(site.getFreeAgents());
generic.setLimit(50);
generic.print(out);
Printables.print(new TeamPositionReport(newRoster, predictor)).to(out);
generic.setTitle("Trade Values");
generic.setPlayers(Iterables.concat(newRoster.getAllPlayers(), futureFas));
generic.setLimit(200);
generic.print(out);
Set<Player> all = Sets.newHashSet();
Set<Player> minorLeaguers = Sets.newHashSet();
LOG.log(Level.INFO, "Team reports...");
generic.setLimit(50);
int n = Iterables.size(site.getTeamIds());
int count = 1;
for (Id<Team> id : site.getTeamIds()) {
SingleTeam t = site.getSingleTeam(id);
LOG.log(Level.INFO, "{0} ({1}/{2})...", new Object[] {t.getName(), count, n});
generic.setTitle(t.getName());
Roster r = t.getRoster();
Iterables.addAll(all, r.getAllPlayers());
Iterables.addAll(minorLeaguers, r.getPlayers(Status.AAA));
Iterables.addAll(minorLeaguers, r.getPlayers(Status.AA));
Iterables.addAll(minorLeaguers, r.getPlayers(Status.A));
generic.setPlayers(r.getAllPlayers());
generic.print(out);
count++;
}
TeamReport now =
TeamReport.create("Now", predictor, site, new PlayerValue(predictor).getNowValue());
LOG.info("Team Now Report...");
now.sortByEndOfSeason();
Printables.print(now).to(out);
generic.useDefaultValueFunction();
LOG.log(Level.INFO, "Non Top 10 prospects...");
ImmutableSet<Player> nonTopTens =
ImmutableSet.copyOf(
Iterables.filter(
all,
new Predicate<Player>() {
public boolean apply(Player p) {
return !p.getTeamTopProspectPosition().isPresent()
&& p.getAge() <= 25
&& site.getCurrentSalary(p) == 0;
}
}));
generic.setTitle("Non Top prospects");
generic.setLimit(50);
generic.setPlayers(nonTopTens);
generic.print(out);
LOG.log(Level.INFO, "Minor league non-prospects...");
ImmutableSet<Player> mlNonProspects =
ImmutableSet.copyOf(
Iterables.filter(
minorLeaguers,
new Predicate<Player>() {
public boolean apply(Player p) {
return p.getAge() > 25;
}
}));
generic.setTitle("ML non-prospects");
generic.setPlayers(mlNonProspects);
generic.print(out);
LOG.log(Level.INFO, "Done.");
}
} |
package com.hearthsim.card.minion;
import com.hearthsim.card.Card;
import com.hearthsim.card.Deck;
import com.hearthsim.card.ImplementedCardList;
import com.hearthsim.event.attack.AttackAction;
import com.hearthsim.event.deathrattle.DeathrattleAction;
import com.hearthsim.exception.HSException;
import com.hearthsim.exception.HSInvalidPlayerIndexException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.HearthAction;
import com.hearthsim.util.HearthAction.Verb;
import com.hearthsim.util.factory.BoardStateFactoryBase;
import com.hearthsim.util.tree.HearthTreeNode;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumSet;
public class Minion extends Card {
public enum BattlecryTargetType {
NO_BATTLECRY,
NO_TARGET,
FRIENDLY_HERO,
ENEMY_HERO,
FRIENDLY_MINIONS,
ENEMY_MINIONS,
FRIENDLY_BEASTS,
ENEMY_BEASTS,
FRIENDLY_MURLOCS,
ENEMY_MURLOCS
}
protected boolean taunt_;
protected boolean divineShield_;
protected boolean windFury_;
protected boolean charge_;
protected boolean hasAttacked_;
protected boolean hasWindFuryAttacked_;
protected boolean frozen_;
protected boolean silenced_;
protected boolean stealthed_;
protected boolean heroTargetable_;
protected byte health_;
protected byte maxHealth_;
protected byte baseHealth_;
protected byte auraHealth_;
protected byte attack_;
protected byte baseAttack_;
protected byte extraAttackUntilTurnEnd_;
protected byte auraAttack_;
protected boolean summoned_;
protected boolean transformed_;
protected boolean destroyOnTurnStart_;
protected boolean destroyOnTurnEnd_;
protected byte spellDamage_;
protected DeathrattleAction deathrattleAction_;
protected AttackAction attackAction_;
// This is a flag to tell the BoardState that it can't cheat on the placement of this minion
protected boolean placementImportant_ = false;
public Minion() {
super();
ImplementedCardList cardList = ImplementedCardList.getInstance();
ImplementedCardList.ImplementedCard implementedCard = cardList.getCardForClass(this.getClass());
if(implementedCard != null) {
// only 'Minion' class is not implemented
baseManaCost = (byte) implementedCard.mana_;
name_ = implementedCard.name_;
attack_ = (byte)implementedCard.attack_;
baseAttack_ = attack_;
health_ = (byte)implementedCard.health_;
maxHealth_ = health_;
baseHealth_ = health_;
taunt_ = implementedCard.taunt_;
divineShield_ = implementedCard.divineShield_;
windFury_ = implementedCard.windfury_;
charge_ = implementedCard.charge_;
stealthed_ = implementedCard.stealth_;
isInHand_ = true;
// TODO: spellpower could be deduced from text quite easily
}
}
/**
* Simplified constructor
*
* @param name
* @param mana
* @param attack
* @param health
* @param baseAttack
* @param baseHealth
* @param maxHealth
*/
public Minion(String name, byte mana, byte attack, byte health, byte baseAttack, byte baseHealth, byte maxHealth) {
this(name, mana, attack, health, baseAttack, (byte)0, (byte)0, baseHealth, maxHealth, (byte)0, (byte)0, false,
false, false, false, false, false, false, false, false, true, false, false, false, false, null, null,
true, false);
}
public Minion(String name, byte mana, byte attack, byte health, byte baseAttack, byte extraAttackUntilTurnEnd,
byte auraAttack, byte baseHealth, byte maxHealth, byte auraHealth, byte spellDamage, boolean taunt,
boolean divineShield, boolean windFury, boolean charge, boolean hasAttacked, boolean hasWindFuryAttacked,
boolean frozen, boolean silenced, boolean stealthed, boolean heroTargetable, boolean summoned,
boolean transformed, boolean destroyOnTurnStart, boolean destroyOnTurnEnd,
DeathrattleAction deathrattleAction, AttackAction attackAction, boolean isInHand, boolean hasBeenUsed) {
super(name, mana, hasBeenUsed, isInHand);
attack_ = attack;
health_ = health;
taunt_ = taunt;
divineShield_ = divineShield;
windFury_ = windFury;
charge_ = charge;
hasAttacked_ = hasAttacked;
baseAttack_ = baseAttack;
extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd;
hasWindFuryAttacked_ = hasWindFuryAttacked;
frozen_ = frozen;
silenced_ = silenced;
baseHealth_ = baseHealth;
maxHealth_ = maxHealth;
summoned_ = summoned;
transformed_ = transformed;
destroyOnTurnStart_ = destroyOnTurnStart;
destroyOnTurnEnd_ = destroyOnTurnEnd;
deathrattleAction_ = deathrattleAction;
attackAction_ = attackAction;
auraAttack_ = auraAttack;
auraHealth_ = auraHealth;
spellDamage_ = spellDamage;
stealthed_ = stealthed;
heroTargetable_ = heroTargetable;
}
public boolean getTaunt() {
return taunt_;
}
public void setTaunt(boolean taunt) {
taunt_ = taunt;
}
public byte getHealth() {
return health_;
}
public void setHealth(byte health) {
health_ = health;
}
public void addHealth(byte value) {
health_ += value;
}
public byte getMaxHealth() {
return maxHealth_;
}
public void setMaxHealth(byte health) {
maxHealth_ = health;
}
public void addMaxHealth(byte value) {
maxHealth_ += value;
}
public byte getBaseHealth() {
return baseHealth_;
}
public void setBaseHealth(byte health) {
baseHealth_ = health;
}
public byte getAttack() {
return attack_;
}
public void setAttack(byte attack) {
attack_ = attack;
}
public void addAttack(byte value) {
attack_ += value;
}
public boolean getDivineShield() {
return divineShield_;
}
public void setDivineShield(boolean divineShield) {
divineShield_ = divineShield;
}
public boolean canAttack() {
return !this.hasAttacked_ && (this.attack_ + this.extraAttackUntilTurnEnd_) > 0 && !this.frozen_;
}
@Deprecated
public boolean hasAttacked() {
return hasAttacked_;
}
public void hasAttacked(boolean hasAttacked) {
hasAttacked_ = hasAttacked;
}
public boolean hasWindFuryAttacked() {
return hasWindFuryAttacked_;
}
public void hasWindFuryAttacked(boolean hasAttacked) {
hasWindFuryAttacked_ = hasAttacked;
}
public boolean getCharge() {
return charge_;
}
public void setCharge(boolean value) {
charge_ = value;
}
public boolean getFrozen() {
return frozen_;
}
public void setFrozen(boolean value) {
frozen_ = value;
}
public boolean getWindfury() {
return windFury_;
}
public void setWindfury(boolean value) {
windFury_ = value;
if (hasAttacked_) {
hasAttacked_ = false;
hasWindFuryAttacked_ = true;
}
}
public boolean getSummoned() {
return summoned_;
}
public void setSummoned(boolean value) {
summoned_ = value;
}
public boolean getTransformed() {
return transformed_;
}
public void setTransformed(boolean value) {
transformed_ = value;
}
public void addExtraAttackUntilTurnEnd(byte value) {
extraAttackUntilTurnEnd_ += value;
}
public byte getExtraAttackUntilTurnEnd() {
return extraAttackUntilTurnEnd_;
}
public void setExtraAttackUntilTurnEnd(byte value) {
extraAttackUntilTurnEnd_ = value;
}
public boolean getDestroyOnTurnStart() {
return destroyOnTurnStart_;
}
public void setDestroyOnTurnStart(boolean value) {
destroyOnTurnStart_ = value;
}
public boolean getDestroyOnTurnEnd() {
return destroyOnTurnEnd_;
}
public void setDestroyOnTurnEnd(boolean value) {
destroyOnTurnEnd_ = value;
}
public boolean isSilenced() {
return silenced_;
}
public boolean hasDeathrattle() {
return deathrattleAction_ != null;
}
public void setDeathrattle(DeathrattleAction action) {
deathrattleAction_ = action;
}
public byte getAuraAttack() {
return auraAttack_;
}
public void setAuraAttack(byte value) {
auraAttack_ = value;
}
public byte getAuraHealth() {
return auraHealth_;
}
public void setAuraHealth(byte value) {
auraHealth_ = value;
}
public byte getTotalAttack() {
return (byte)(attack_ + auraAttack_ + extraAttackUntilTurnEnd_);
}
public byte getTotalHealth() {
return (byte)(health_ + auraHealth_);
}
public byte getTotalMaxHealth() {
return (byte)(maxHealth_ + auraHealth_);
}
public void addAuraHealth(byte value) {
auraHealth_ += value;
}
public void removeAuraHealth(byte value) {
health_ += value;
if(health_ > maxHealth_)
health_ = maxHealth_;
auraHealth_ -= value;
}
public boolean getStealthed() {
return stealthed_;
}
public void setStealthed(boolean value) {
stealthed_ = value;
}
public boolean getPlacementImportant() {
return placementImportant_;
}
public void setPlacementImportant(boolean value) {
placementImportant_ = value;
}
public boolean isHeroTargetable() {
return heroTargetable_;
}
public void setHeroTargetable(boolean value) {
heroTargetable_ = value;
}
public byte getSpellDamage() {
return spellDamage_;
}
public void setSpellDamage(byte value) {
spellDamage_ = value;
}
public void addSpellDamage(byte value) {
spellDamage_ += value;
}
public void subtractSpellDamage(byte value) {
spellDamage_ -= value;
}
/**
* Called at the start of the turn
*
* This function is called at the start of the turn. Any derived class must override it to implement whatever "start of the turn" effect the card has.
*/
@Override
public HearthTreeNode startTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
HearthTreeNode toRet = boardModel;
if(destroyOnTurnStart_) {
// toRet = this.destroyed(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1);
this.setHealth((byte)-99);
}
return toRet;
}
/**
* End the turn and resets the card state
*
* This function is called at the end of the turn. Any derived class must override it and remove any temporary buffs that it has.
*
* This is not the most efficient implementation... luckily, endTurn only happens once per turn
*/
@Override
public HearthTreeNode endTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
extraAttackUntilTurnEnd_ = 0;
HearthTreeNode toRet = boardModel;
if(destroyOnTurnEnd_) {
// toRet = this.destroyed(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1);
this.setHealth((byte)-99);
}
return toRet;
}
/**
* Called when this minion takes damage
*
* Always use this function to take damage... it properly notifies all others of its damage and possibly of its death
*
* @param damage The amount of damage to take
* @param attackPlayerSide The player index of the attacker. This is needed to do things like +spell damage.
* @param thisPlayerSide
* @param boardState
* @param deckPlayer0 The deck of player0
* @param isSpellDamage True if this is a spell damage
* @param handleMinionDeath Set this to True if you want the death event to trigger when (if) the minion dies from this damage. Setting this flag to True will also trigger deathrattle immediately.
* @throws HSInvalidPlayerIndexException
*/
public HearthTreeNode takeDamage(byte damage, PlayerSide attackPlayerSide, PlayerSide thisPlayerSide,
HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean isSpellDamage,
boolean handleMinionDeath) throws HSException {
if(!divineShield_) {
byte totalDamage = isSpellDamage ? (byte)(damage + boardState.data_.getSpellDamage(attackPlayerSide))
: damage;
health_ = (byte)(health_ - totalDamage);
// Notify all that the minion is damaged
HearthTreeNode toRet = boardState;
toRet = toRet.data_.getCurrentPlayerHero().minionDamagedEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide,
this, toRet, deckPlayer0, deckPlayer1);
for(int j = 0; j < PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getNumMinions(); ++j) {
if(!PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions().get(j).silenced_)
toRet = PlayerSide.CURRENT_PLAYER
.getPlayer(toRet)
.getMinions()
.get(j)
.minionDamagedEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide, this, toRet, deckPlayer0,
deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionDamagedEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide,
this, toRet, deckPlayer0, deckPlayer1);
for(int j = 0; j < PlayerSide.WAITING_PLAYER.getPlayer(toRet).getNumMinions(); ++j) {
if(!PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions().get(j).silenced_)
toRet = PlayerSide.WAITING_PLAYER
.getPlayer(toRet)
.getMinions()
.get(j)
.minionDamagedEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide, this, toRet, deckPlayer0,
deckPlayer1);
}
return toRet;
} else {
if(damage > 0)
divineShield_ = false;
return boardState;
}
}
/**
* Called when this minion dies (destroyed)
*
* Always use this function to "kill" minions
*
*
*
* @param thisPlayerSide
* @param boardState
* @param deckPlayer0
* @param deckPlayer1
*
* @throws HSInvalidPlayerIndexException
*/
public HearthTreeNode destroyed(PlayerSide thisPlayerSide, HearthTreeNode boardState, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
health_ = 0;
HearthTreeNode toRet = boardState;
// perform the deathrattle action if there is one
if(deathrattleAction_ != null) {
toRet = deathrattleAction_.performAction(this, thisPlayerSide, toRet, deckPlayer0, deckPlayer1);
}
// Notify all that it is dead
toRet = toRet.data_.getCurrentPlayerHero().minionDeadEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide, this,
toRet, deckPlayer0, deckPlayer1);
for(int j = 0; j < PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getNumMinions(); ++j) {
if(!PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions().get(j).silenced_)
toRet = PlayerSide.CURRENT_PLAYER
.getPlayer(toRet)
.getMinions()
.get(j)
.minionDeadEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide, this, toRet, deckPlayer0,
deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionDeadEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide, this,
toRet, deckPlayer0, deckPlayer1);
for(int j = 0; j < PlayerSide.WAITING_PLAYER.getPlayer(toRet).getNumMinions(); ++j) {
if(!PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions().get(j).silenced_)
toRet = PlayerSide.WAITING_PLAYER
.getPlayer(toRet)
.getMinions()
.get(j)
.minionDeadEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide, this, toRet, deckPlayer0,
deckPlayer1);
}
return toRet;
}
// Use for bounce (e.g., Brewmaster) or recreate (e.g., Reincarnate)
public Minion createResetCopy() {
try {
Constructor<? extends Minion> ctor = this.getClass().getConstructor();
Minion object = ctor.newInstance();
return object;
} catch(NoSuchMethodException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void silenced(PlayerSide thisPlayerSide, HearthTreeNode boardState) throws HSInvalidPlayerIndexException {
this.silenced(thisPlayerSide, boardState.data_);
}
/**
* Called when this minion is silenced
*
* Always use this function to "silence" minions
*
* @param thisPlayerSide
* @param boardState
* @throws HSInvalidPlayerIndexException
*/
public void silenced(PlayerSide thisPlayerSide, BoardModel boardState) throws HSInvalidPlayerIndexException {
spellDamage_ = 0;
divineShield_ = false;
taunt_ = false;
charge_ = false;
frozen_ = false;
windFury_ = false;
silenced_ = true;
deathrattleAction_ = null;
stealthed_ = false;
heroTargetable_ = true;
// Reset the attack and health to base
this.attack_ = this.baseAttack_;
if(this.maxHealth_ > this.baseHealth_) {
this.maxHealth_ = this.baseHealth_;
if(this.health_ > this.maxHealth_)
this.health_ = this.maxHealth_;
}
}
/**
* Called when this minion is healed
*
* Always use this function to heal minions
*
* @param healAmount The amount of healing to take
* @param thisPlayerSide
* @param boardState
* @param deckPlayer0 The deck of player0 @throws HSInvalidPlayerIndexException
* */
public HearthTreeNode takeHeal(byte healAmount, PlayerSide thisPlayerSide, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1) throws HSInvalidPlayerIndexException {
if(health_ < maxHealth_) {
if(health_ + healAmount > maxHealth_)
health_ = maxHealth_;
else
health_ = (byte)(health_ + healAmount);
// Notify all that it the minion is healed
HearthTreeNode toRet = boardState;
toRet = toRet.data_.getCurrentPlayerHero().minionHealedEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide,
this, toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionHealedEvent(PlayerSide.CURRENT_PLAYER, thisPlayerSide, this, toRet,
deckPlayer0, deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionHealedEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide,
this, toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionHealedEvent(PlayerSide.WAITING_PLAYER, thisPlayerSide, this, toRet,
deckPlayer0, deckPlayer1);
}
return toRet;
}
return boardState;
}
@Override
public boolean canBeUsedOn(PlayerSide playerSide, Minion minion, BoardModel boardModel) {
return playerSide != PlayerSide.WAITING_PLAYER && !hasBeenUsed;
}
/**
* Use a targetable battlecry.
*
* @param side
* @param targetMinion
* @param boardState
* @param deckPlayer0
* @param deckPlayer1
* @return
* @throws HSException
*/
public HearthTreeNode useTargetableBattlecry(PlayerSide side, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1) throws HSException {
HearthTreeNode node = new HearthTreeNode(boardState.data_.deepCopy());
int targetMinionIndex = side.getPlayer(boardState).getMinions().indexOf(targetMinion);
if(targetMinionIndex >= 0) {
node = this.useTargetableBattlecry_core(side, side.getPlayer(node).getMinions().get(targetMinionIndex),
node, deckPlayer0, deckPlayer1);
} else if(targetMinion instanceof Hero) {
node = this.useTargetableBattlecry_core(side, side.getPlayer(node).getHero(), node, deckPlayer0,
deckPlayer1);
} else {
node = null;
}
if(node != null) {
// Check for dead minions
node = BoardStateFactoryBase.handleDeadMinions(node, deckPlayer0, deckPlayer1);
// add the new node to the tree
boardState.addChild(node);
}
return boardState;
}
/**
* Derived classes should implement this function for targtable battlecries.
*
* @param side
* @param targetMinion
* @param boardState
* @param deckPlayer0
* @param deckPlayer1
* @return
* @throws HSException
*/
public HearthTreeNode useTargetableBattlecry_core(PlayerSide side, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1) throws HSException {
return null;
}
public EnumSet<BattlecryTargetType> getBattlecryTargets() {
return EnumSet.of(BattlecryTargetType.NO_BATTLECRY);
}
/**
* Use an untargetable battlecry.
*
* @param minionPlacementTarget
* @param boardState
* @param deckPlayer0
* @param deckPlayer1
* @param singleRealizationOnly
* @return
* @throws HSException
*/
public HearthTreeNode useUntargetableBattlecry(Minion minionPlacementTarget, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException {
HearthTreeNode toRet = this.useUntargetableBattlecry_core(minionPlacementTarget, boardState, deckPlayer0,
deckPlayer1, singleRealizationOnly);
if(toRet != null) {
// Check for dead minions
toRet = BoardStateFactoryBase.handleDeadMinions(toRet, deckPlayer0, deckPlayer1);
}
return toRet;
}
public HearthTreeNode useUntargetableBattlecry_core(Minion minionPlacementTarget, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException {
return null;
}
/**
*
* Places a minion on the board by using the card in hand
*
*
*
* @param side
* @param targetMinion The target minion (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position.
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @return The boardState is manipulated and returned
* @throws HSException
*/
@Override
protected HearthTreeNode use_core(PlayerSide side, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException {
if(hasBeenUsed || side == PlayerSide.WAITING_PLAYER || boardState.data_.modelForSide(side).getNumMinions() >= 7)
return null;
HearthTreeNode toRet = boardState;
toRet.data_.getCurrentPlayer().subtractMana(this.getManaCost(PlayerSide.CURRENT_PLAYER, boardState));
toRet.data_.removeCard_hand(this);
toRet = this
.summonMinion(side, targetMinion, boardState, deckPlayer0, deckPlayer1, true, singleRealizationOnly);
return toRet;
}
/**
*
* Places a minion on the board via a summon effect
*
* This function is meant to be used when summoning minions through means other than a direct card usage.
*
*
* @param targetSide
* @param targetMinion The target minion (can be a Hero). If it is a Hero, then the minion is placed on the last (right most) spot on the board.
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @param deckPlayer1 The deck of player1
* @param wasTransformed If the minion was 'summoned' as a result of a transform effect (e.g. Hex, Polymorph), set this to true.
*
* @return The boardState is manipulated and returned
*/
public HearthTreeNode summonMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean wasPlayed, boolean singleRealizationOnly) throws HSException {
if(boardState.data_.modelForSide(targetSide).getNumMinions() >= 7)
return null;
HearthTreeNode toRet = boardState;
toRet = this
.summonMinion_core(targetSide, targetMinion, toRet, deckPlayer0, deckPlayer1, singleRealizationOnly);
// Battlecry if available
for(BattlecryTargetType btt : this.getBattlecryTargets()) {
switch (btt) {
case NO_TARGET:
toRet = this.useUntargetableBattlecry(targetMinion, toRet, deckPlayer0, deckPlayer1,
singleRealizationOnly);
break;
case ENEMY_HERO:
toRet = this.useTargetableBattlecry(PlayerSide.WAITING_PLAYER,
PlayerSide.WAITING_PLAYER.getPlayer(toRet).getHero(), toRet, deckPlayer0, deckPlayer1);
break;
case FRIENDLY_HERO:
toRet = this.useTargetableBattlecry(PlayerSide.CURRENT_PLAYER,
PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getHero(), toRet, deckPlayer0, deckPlayer1);
break;
case ENEMY_MINIONS:
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if (!minion.getStealthed())
toRet = this.useTargetableBattlecry(PlayerSide.WAITING_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
case FRIENDLY_MINIONS:
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(minion != this)
toRet = this.useTargetableBattlecry(PlayerSide.CURRENT_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
case ENEMY_BEASTS:
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(minion instanceof Beast)
toRet = this.useTargetableBattlecry(PlayerSide.WAITING_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
case FRIENDLY_BEASTS:
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(minion != this && minion instanceof Beast)
toRet = this.useTargetableBattlecry(PlayerSide.CURRENT_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
case ENEMY_MURLOCS:
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(minion instanceof Murloc)
toRet = this.useTargetableBattlecry(PlayerSide.WAITING_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
case FRIENDLY_MURLOCS:
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(minion != this && minion instanceof Murloc)
toRet = this.useTargetableBattlecry(PlayerSide.CURRENT_PLAYER, minion, toRet, deckPlayer0,
deckPlayer1);
}
break;
default:
break;
}
}
if(wasPlayed)
toRet = this.notifyMinionPlayed(toRet, targetSide, deckPlayer0, deckPlayer1);
toRet = this.notifyMinionSummon(toRet, targetSide, deckPlayer0, deckPlayer1);
return toRet;
}
/**
*
* Places a minion on the board via a summon effect
*
* This function is meant to be used when summoning minions through means other than a direct card usage.
*
*
* @param targetSide
* @param targetMinion The target minion (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position.
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @return The boardState is manipulated and returned
* @param deckPlayer0 The deck of player0
* @param deckPlayer1 The deck of player1
* @throws HSException
*/
protected HearthTreeNode summonMinion_core(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException {
HearthTreeNode toRet = this.placeMinion(targetSide, targetMinion, boardState, deckPlayer0, deckPlayer1,
singleRealizationOnly);
if(!charge_) {
hasAttacked_ = true;
}
hasBeenUsed = true;
return toRet;
}
public HearthTreeNode placeMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException {
if(isHero(targetMinion))
boardState.data_.placeMinion(targetSide, this, 0);
else
boardState.data_.placeMinion(targetSide, this,
targetSide.getPlayer(boardState).getMinions().indexOf(targetMinion) + 1);
return this.notifyMinionPlacement(boardState, targetSide, deckPlayer0, deckPlayer1);
}
/**
*
* Attack with the minion
*
*
*
* @param targetMinionPlayerSide
* @param targetMinion The target minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @return The boardState is manipulated and returned
*/
public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState,
Deck deckPlayer0, Deck deckPlayer1) throws HSException {
// can't attack a stealthed target
if(targetMinion.getStealthed())
return null;
if(frozen_) {
this.hasAttacked_ = true;
this.frozen_ = false;
return boardState;
}
// Notify all that an attack is beginning
HearthTreeNode toRet = boardState;
if(toRet != null) {
// Notify all that a minion is created
toRet = toRet.data_.getCurrentPlayerHero().minionAttackEvent(toRet);
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionAttackEvent(toRet);
}
toRet = toRet.data_.getWaitingPlayerHero().minionAttackEvent(toRet);
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionAttackEvent(toRet);
}
}
int attackerIndex = this instanceof Hero ? 0 : PlayerSide.CURRENT_PLAYER.getPlayer(boardState).getMinions()
.indexOf(this) + 1;
int targetIndex = targetMinion instanceof Hero ? 0 : targetMinionPlayerSide.getPlayer(boardState).getMinions()
.indexOf(targetMinion) + 1;
// Do the actual attack
toRet = this.attack_core(targetMinionPlayerSide, targetMinion, boardState, deckPlayer0, deckPlayer1);
// check for and remove dead minions
if(toRet != null) {
toRet.setAction(new HearthAction(Verb.ATTACK, PlayerSide.CURRENT_PLAYER, attackerIndex,
targetMinionPlayerSide, targetIndex));
toRet = BoardStateFactoryBase.handleDeadMinions(toRet, deckPlayer0, deckPlayer1);
}
// Attacking means you lose stealth
if(toRet != null)
this.stealthed_ = false;
return toRet;
}
/**
*
* Attack with the minion
*
*
*
* @param targetMinionPlayerSide
* @param targetMinion The target minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @return The boardState is manipulated and returned
*/
protected HearthTreeNode attack_core(PlayerSide targetMinionPlayerSide, Minion targetMinion,
HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1) throws HSException {
if(hasAttacked_) {
// minion has already attacked
return null;
}
if(targetMinionPlayerSide == PlayerSide.CURRENT_PLAYER) {
return null;
}
if(this.getTotalAttack() <= 0) {
return null;
}
HearthTreeNode toRet = boardState;
byte origAttack = targetMinion.getTotalAttack();
toRet = targetMinion.takeDamage(this.getTotalAttack(), PlayerSide.CURRENT_PLAYER, targetMinionPlayerSide,
toRet, deckPlayer0, deckPlayer1, false, false);
toRet = this.takeDamage(origAttack, targetMinionPlayerSide, PlayerSide.CURRENT_PLAYER, toRet, deckPlayer0,
deckPlayer1, false, false);
if(windFury_ && !hasWindFuryAttacked_)
hasWindFuryAttacked_ = true;
else
hasAttacked_ = true;
return toRet;
}
// Various notifications
protected HearthTreeNode notifyMinionSummon(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
HearthTreeNode toRet = boardState;
toRet = toRet.data_.getCurrentPlayerHero().minionSummonEvent(PlayerSide.CURRENT_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionSummonEvent(PlayerSide.CURRENT_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionSummonEvent(PlayerSide.WAITING_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionSummonEvent(PlayerSide.WAITING_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
return toRet;
}
protected HearthTreeNode notifyMinionPlacement(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
HearthTreeNode toRet = boardState;
toRet = toRet.data_.getCurrentPlayerHero().minionPlacedEvent(PlayerSide.CURRENT_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionPlacedEvent(PlayerSide.CURRENT_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionPlacedEvent(PlayerSide.WAITING_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionPlacedEvent(PlayerSide.WAITING_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
return toRet;
}
protected HearthTreeNode notifyMinionPlayed(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0,
Deck deckPlayer1) throws HSException {
HearthTreeNode toRet = boardState;
toRet = toRet.data_.getCurrentPlayerHero().minionPlayedEvent(PlayerSide.CURRENT_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.CURRENT_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionPlayedEvent(PlayerSide.CURRENT_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
toRet = toRet.data_.getWaitingPlayerHero().minionPlayedEvent(PlayerSide.WAITING_PLAYER, targetSide, this,
toRet, deckPlayer0, deckPlayer1);
for(Minion minion : PlayerSide.WAITING_PLAYER.getPlayer(toRet).getMinions()) {
if(!minion.silenced_)
toRet = minion.minionPlayedEvent(PlayerSide.WAITING_PLAYER, targetSide, this, toRet, deckPlayer0,
deckPlayer1);
}
return toRet;
}
// Hooks for various events
/**
* Called whenever another minion comes on board
*
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
*
* */
public HearthTreeNode minionPlacedEvent(PlayerSide thisMinionPlayerSide, PlayerSide summonedMinionPlayerSide,
Minion summonedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
* Called whenever a minion is played (i.e., if a minion card was used to directly place a minion on the board)
*
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
*
* */
public HearthTreeNode minionPlayedEvent(PlayerSide thisMinionPlayerSide, PlayerSide summonedMinionPlayerSide,
Minion summonedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
* Called whenever another minion is summoned
*
* @param thisMinionPlayerSide
* @param summonedMinionPlayerSide
* @param summonedMinion The summoned minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @param deckPlayer1 The deck of player1
* @return The boardState is manipulated and returned
* */
public HearthTreeNode minionSummonEvent(PlayerSide thisMinionPlayerSide, PlayerSide summonedMinionPlayerSide,
Minion summonedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
* Called whenever another minion is summoned, before the summoning
*
* @param thisMinionPlayerSide
* @param summonedMinionPlayerSide
* @param summonedMinion The summoned minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0
* @param deckPlayer1 The deck of player1
* @return The boardState is manipulated and returned
* */
public HearthTreeNode minionAfterSummonEvent(PlayerSide thisMinionPlayerSide, PlayerSide summonedMinionPlayerSide,
Minion summonedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
*
* Called whenever another minion is attacking another character
*
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
*
* */
public HearthTreeNode minionAttackEvent(HearthTreeNode boardState) throws HSInvalidPlayerIndexException {
return boardState;
}
/**
*
* Called whenever another minion is damaged
*
*
* @param thisMinionPlayerSide
* @param damagedPlayerSide
* @param damagedMinion The damaged minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0 @return The boardState is manipulated and returned
* */
public HearthTreeNode minionDamagedEvent(PlayerSide thisMinionPlayerSide, PlayerSide damagedPlayerSide,
Minion damagedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
*
* Called whenever another minion dies
*
*
* @param thisMinionPlayerSide
* @param deadMinionPlayerSide
* @param deadMinion The dead minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0 @return The boardState is manipulated and returned
* */
public HearthTreeNode minionDeadEvent(PlayerSide thisMinionPlayerSide, PlayerSide deadMinionPlayerSide,
Minion deadMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
/**
*
* Called whenever another character (including the hero) is healed
*
*
* @param thisMinionPlayerSide
* @param healedMinionPlayerSide
* @param healedMinion The healed minion
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
* @param deckPlayer0 The deck of player0 @return The boardState is manipulated and returned
* */
public HearthTreeNode minionHealedEvent(PlayerSide thisMinionPlayerSide, PlayerSide healedMinionPlayerSide,
Minion healedMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1)
throws HSInvalidPlayerIndexException {
return boardState;
}
@Override
public JSONObject toJSON() {
JSONObject json = super.toJSON();
json.put("attack", attack_);
json.put("baseAttack", baseAttack_);
if(health_ != maxHealth_) json.put("health", health_);
json.put("baseHealth", baseHealth_);
json.put("maxHealth", maxHealth_);
if(taunt_) json.put("taunt", taunt_);
if(divineShield_) json.put("divineShield", divineShield_);
if(windFury_) json.put("windFury", windFury_);
if(charge_) json.put("charge", charge_);
if(frozen_) json.put("frozen", frozen_);
if(silenced_) json.put("silenced", silenced_);
if(hasAttacked_) json.put("hasAttacked", hasAttacked_);
if(spellDamage_ != 0) json.put("spellDamage", spellDamage_);
return json;
}
/**
* Deep copy of the object
*
* Note: the event actions are not actually deep copied.
*/
@Override
public Card deepCopy() {
Minion minion = null;
try {
minion = getClass().newInstance();
} catch(InstantiationException e) {
log.error("instantiation error", e);
} catch(IllegalAccessException e) {
log.error("illegal access error", e);
}
if(minion == null) {
throw new RuntimeException("unable to instantiate minion.");
}
minion.name_ = name_;
minion.baseManaCost = baseManaCost;
minion.attack_ = attack_;
minion.health_ = health_;
minion.baseAttack_ = baseAttack_;
minion.extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd_;
minion.auraAttack_ = auraAttack_;
minion.baseHealth_ = baseHealth_;
minion.maxHealth_ = maxHealth_;
minion.auraHealth_ = auraHealth_;
minion.spellDamage_ = spellDamage_;
minion.taunt_ = taunt_;
minion.divineShield_ = divineShield_;
minion.windFury_ = windFury_;
minion.charge_ = charge_;
minion.hasAttacked_ = hasAttacked_;
minion.hasWindFuryAttacked_ = hasWindFuryAttacked_;
minion.frozen_ = frozen_;
minion.silenced_ = silenced_;
minion.stealthed_ = stealthed_;
minion.heroTargetable_ = heroTargetable_;
minion.summoned_ = summoned_;
minion.transformed_ = transformed_;
minion.destroyOnTurnStart_ = destroyOnTurnStart_;
minion.destroyOnTurnEnd_ = destroyOnTurnEnd_;
minion.deathrattleAction_ = deathrattleAction_;
minion.attackAction_ = attackAction_;
minion.isInHand_ = isInHand_;
minion.hasBeenUsed = hasBeenUsed;
// TODO: continue here.
return minion;
}
@Override
public boolean equals(Object other) {
if(!super.equals(other)) {
return false;
}
Minion otherMinion = (Minion)other;
if(health_ != otherMinion.health_)
return false;
if(maxHealth_ != otherMinion.maxHealth_)
return false;
if(baseHealth_ != otherMinion.baseHealth_)
return false;
if(auraHealth_ != otherMinion.auraHealth_)
return false;
if(attack_ != otherMinion.attack_)
return false;
if(baseAttack_ != otherMinion.baseAttack_)
return false;
if(extraAttackUntilTurnEnd_ != otherMinion.extraAttackUntilTurnEnd_)
return false;
if(auraAttack_ != otherMinion.auraAttack_)
return false;
if(taunt_ != otherMinion.taunt_)
return false;
if(divineShield_ != otherMinion.divineShield_)
return false;
if(windFury_ != otherMinion.windFury_)
return false;
if(charge_ != otherMinion.charge_)
return false;
if(stealthed_ != otherMinion.stealthed_)
return false;
if(hasAttacked_ != otherMinion.hasAttacked_)
return false;
if(heroTargetable_ != otherMinion.heroTargetable_)
return false;
if(hasWindFuryAttacked_ != otherMinion.hasWindFuryAttacked_)
return false;
if(frozen_ != otherMinion.frozen_)
return false;
if(silenced_ != otherMinion.silenced_)
return false;
if(summoned_ != otherMinion.summoned_)
return false;
if(transformed_ != otherMinion.transformed_)
return false;
if(destroyOnTurnStart_ != otherMinion.destroyOnTurnStart_)
return false;
if(destroyOnTurnEnd_ != otherMinion.destroyOnTurnEnd_)
return false;
if(spellDamage_ != otherMinion.spellDamage_)
return false;
// This is checked for reference equality
if(deathrattleAction_ != ((Minion)other).deathrattleAction_)
return false;
// This is checked for reference equality
if(attackAction_ != ((Minion)other).attackAction_)
return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (taunt_ ? 1 : 0);
result = 31 * result + (divineShield_ ? 1 : 0);
result = 31 * result + (windFury_ ? 1 : 0);
result = 31 * result + (charge_ ? 1 : 0);
result = 31 * result + (hasAttacked_ ? 1 : 0);
result = 31 * result + (hasWindFuryAttacked_ ? 1 : 0);
result = 31 * result + (frozen_ ? 1 : 0);
result = 31 * result + (silenced_ ? 1 : 0);
result = 31 * result + (stealthed_ ? 1 : 0);
result = 31 * result + (heroTargetable_ ? 1 : 0);
result = 31 * result + health_;
result = 31 * result + maxHealth_;
result = 31 * result + baseHealth_;
result = 31 * result + auraHealth_;
result = 31 * result + attack_;
result = 31 * result + baseAttack_;
result = 31 * result + extraAttackUntilTurnEnd_;
result = 31 * result + auraAttack_;
result = 31 * result + (summoned_ ? 1 : 0);
result = 31 * result + (transformed_ ? 1 : 0);
result = 31 * result + (destroyOnTurnStart_ ? 1 : 0);
result = 31 * result + (destroyOnTurnEnd_ ? 1 : 0);
result = 31 * result + spellDamage_;
result = 31 * result + (deathrattleAction_ != null ? deathrattleAction_.hashCode() : 0);
result = 31 * result + (attackAction_ != null ? attackAction_.hashCode() : 0);
result = 31 * result + (placementImportant_ ? 1 : 0);
return result;
}
public boolean currentPlayerBoardFull(HearthTreeNode boardState) {
return PlayerSide.CURRENT_PLAYER.getPlayer(boardState).getNumMinions() >= 7;
}
} |
package com.jsoniter.spi;
import java.lang.reflect.*;
import java.util.*;
import static java.lang.reflect.Modifier.isTransient;
public class ClassDescriptor {
public ClassInfo classInfo;
public Class clazz;
public Map<String, Type> lookup;
public ConstructorDescriptor ctor;
public List<Binding> fields;
public List<Binding> setters;
public List<Binding> getters;
public List<WrapperDescriptor> bindingTypeWrappers;
public List<Method> keyValueTypeWrappers;
public List<UnwrapperDescriptor> unwrappers;
public boolean asExtraForUnknownProperties;
public Binding onMissingProperties;
public Binding onExtraProperties;
private ClassDescriptor() {
}
public static ClassDescriptor getDecodingClassDescriptor(ClassInfo classInfo, boolean includingPrivate) {
Class clazz = classInfo.clazz;
Map<String, Type> lookup = collectTypeVariableLookup(clazz);
ClassDescriptor desc = new ClassDescriptor();
desc.classInfo = classInfo;
desc.clazz = clazz;
desc.lookup = lookup;
desc.ctor = getCtor(clazz);
desc.setters = getSetters(lookup, classInfo, includingPrivate);
desc.getters = new ArrayList<Binding>();
desc.fields = getFields(lookup, classInfo, includingPrivate);
desc.bindingTypeWrappers = new ArrayList<WrapperDescriptor>();
desc.keyValueTypeWrappers = new ArrayList<Method>();
desc.unwrappers = new ArrayList<UnwrapperDescriptor>();
for (Extension extension : JsoniterSpi.getExtensions()) {
extension.updateClassDescriptor(desc);
}
for (Binding field : desc.fields) {
if (field.valueType instanceof Class) {
Class valueClazz = (Class) field.valueType;
if (valueClazz.isArray()) {
field.valueCanReuse = false;
continue;
}
}
field.valueCanReuse = field.valueTypeLiteral.nativeType == null;
}
decodingDeduplicate(desc);
if (includingPrivate) {
if (desc.ctor.ctor != null) {
desc.ctor.ctor.setAccessible(true);
}
if (desc.ctor.staticFactory != null) {
desc.ctor.staticFactory.setAccessible(true);
}
for (WrapperDescriptor setter : desc.bindingTypeWrappers) {
setter.method.setAccessible(true);
}
}
for (Binding binding : desc.allDecoderBindings()) {
if (binding.fromNames == null) {
binding.fromNames = new String[]{binding.name};
}
if (binding.field != null && includingPrivate) {
binding.field.setAccessible(true);
}
if (binding.method != null && includingPrivate) {
binding.method.setAccessible(true);
}
if (binding.decoder != null) {
JsoniterSpi.addNewDecoder(binding.decoderCacheKey(), binding.decoder);
}
}
return desc;
}
public static ClassDescriptor getEncodingClassDescriptor(ClassInfo classInfo, boolean includingPrivate) {
Class clazz = classInfo.clazz;
Map<String, Type> lookup = collectTypeVariableLookup(clazz);
ClassDescriptor desc = new ClassDescriptor();
desc.classInfo = classInfo;
desc.clazz = clazz;
desc.lookup = lookup;
desc.fields = getFields(lookup, classInfo, includingPrivate);
desc.getters = getGetters(lookup, classInfo, includingPrivate);
desc.bindingTypeWrappers = new ArrayList<WrapperDescriptor>();
desc.keyValueTypeWrappers = new ArrayList<Method>();
desc.unwrappers = new ArrayList<UnwrapperDescriptor>();
for (Extension extension : JsoniterSpi.getExtensions()) {
extension.updateClassDescriptor(desc);
}
encodingDeduplicate(desc);
for (Binding binding : desc.allEncoderBindings()) {
if (binding.toNames == null) {
binding.toNames = new String[]{binding.name};
}
if (binding.field != null && includingPrivate) {
binding.field.setAccessible(true);
}
if (binding.method != null && includingPrivate) {
binding.method.setAccessible(true);
}
if (binding.encoder != null) {
JsoniterSpi.addNewEncoder(binding.encoderCacheKey(), binding.encoder);
}
}
return desc;
}
// TODO: do not remove, set fromNames to []
private static void decodingDeduplicate(ClassDescriptor desc) {
HashMap<String, Binding> byName = new HashMap<String, Binding>();
for (Binding field : desc.fields) {
for (String fromName : field.fromNames) {
if (byName.containsKey(fromName)) {
throw new JsonException("field decode from same name: " + fromName);
}
byName.put(fromName, field);
}
}
ArrayList<Binding> iteratingSetters = new ArrayList<Binding>(desc.setters);
Collections.reverse(iteratingSetters);
for (Binding setter : iteratingSetters) {
for (String fromName : setter.fromNames) {
Binding existing = byName.get(fromName);
if (existing == null) {
byName.put(fromName, setter);
continue;
}
if (desc.fields.remove(existing)) {
continue;
}
if (existing.method != null && existing.method.getName().equals(setter.method.getName())) {
// inherited interface setter
// iterate in reverse order, so that the setter from child class will be kept
desc.setters.remove(existing);
continue;
}
throw new JsonException("setter decode from same name: " + fromName);
}
}
for (WrapperDescriptor wrapper : desc.bindingTypeWrappers) {
for (Binding param : wrapper.parameters) {
for (String fromName : param.fromNames) {
Binding existing = byName.get(fromName);
if (existing == null) {
byName.put(fromName, param);
continue;
}
if (desc.fields.remove(existing)) {
continue;
}
if (desc.setters.remove(existing)) {
continue;
}
throw new JsonException("wrapper parameter decode from same name: " + fromName);
}
}
}
for (Binding param : desc.ctor.parameters) {
for (String fromName : param.fromNames) {
Binding existing = byName.get(fromName);
if (existing == null) {
byName.put(fromName, param);
continue;
}
if (desc.fields.remove(existing)) {
continue;
}
if (desc.setters.remove(existing)) {
continue;
}
throw new JsonException("ctor parameter decode from same name: " + fromName);
}
}
}
private static void encodingDeduplicate(ClassDescriptor desc) {
HashMap<String, Binding> byToName = new HashMap<String, Binding>();
HashMap<String, Binding> byFieldName = new HashMap<String, Binding>();
for (Binding field : desc.fields) {
for (String toName : field.toNames) {
if (byToName.containsKey(toName)) {
throw new JsonException("field encode to same name: " + toName);
}
byToName.put(toName, field);
}
byFieldName.put(field.name, field);
}
for (Binding getter : new ArrayList<Binding>(desc.getters)) {
Binding existing = byFieldName.get(getter.name);
if (existing != null) {
existing.toNames = new String[0];
}
for (String toName : getter.toNames) {
existing = byToName.get(toName);
if (existing == null) {
byToName.put(toName, getter);
continue;
}
existing.toNames = new String[0];
}
}
}
private static ConstructorDescriptor getCtor(Class clazz) {
ConstructorDescriptor cctor = new ConstructorDescriptor();
if (JsoniterSpi.canCreate(clazz)) {
cctor.objectFactory = JsoniterSpi.getObjectFactory(clazz);
return cctor;
}
try {
cctor.ctor = clazz.getDeclaredConstructor();
} catch (Exception e) {
cctor.ctor = null;
}
return cctor;
}
private static List<Binding> getFields(Map<String, Type> lookup, ClassInfo classInfo, boolean includingPrivate) {
ArrayList<Binding> bindings = new ArrayList<Binding>();
for (Field field : getAllFields(classInfo.clazz, includingPrivate)) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (!includingPrivate && !Modifier.isPublic(field.getType().getModifiers())) {
continue;
}
if (includingPrivate) {
field.setAccessible(true);
}
Binding binding = createBindingFromField(lookup, classInfo, field);
if (isTransient(field.getModifiers())) {
binding.toNames = new String[0];
binding.fromNames = new String[0];
}
bindings.add(binding);
}
return bindings;
}
private static Binding createBindingFromField(Map<String, Type> lookup, ClassInfo classInfo, Field field) {
try {
Binding binding = new Binding(classInfo, lookup, field.getGenericType());
binding.fromNames = new String[]{field.getName()};
binding.toNames = new String[]{field.getName()};
binding.name = field.getName();
binding.annotations = field.getAnnotations();
binding.field = field;
return binding;
} catch (Exception e) {
throw new JsonException("failed to create binding for field: " + field, e);
}
}
private static List<Field> getAllFields(Class clazz, boolean includingPrivate) {
List<Field> allFields = Arrays.asList(clazz.getFields());
if (includingPrivate) {
allFields = new ArrayList<Field>();
Class current = clazz;
while (current != null) {
allFields.addAll(Arrays.asList(current.getDeclaredFields()));
current = current.getSuperclass();
}
}
return allFields;
}
private static List<Binding> getSetters(Map<String, Type> lookup, ClassInfo classInfo, boolean includingPrivate) {
ArrayList<Binding> setters = new ArrayList<Binding>();
for (Method method : getAllMethods(classInfo.clazz, includingPrivate)) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
String methodName = method.getName();
if (methodName.length() < 4) {
continue;
}
if (!methodName.startsWith("set")) {
continue;
}
Type[] paramTypes = method.getGenericParameterTypes();
if (paramTypes.length != 1) {
continue;
}
if (!includingPrivate && !Modifier.isPublic(method.getParameterTypes()[0].getModifiers())) {
continue;
}
if (includingPrivate) {
method.setAccessible(true);
}
try {
String fromName = translateSetterName(methodName);
Field field = null;
try {
field = method.getDeclaringClass().getDeclaredField(fromName);
} catch (NoSuchFieldException e) {
// ignore
}
Binding setter = new Binding(classInfo, lookup, paramTypes[0]);
if (field != null && isTransient(field.getModifiers())) {
setter.fromNames = new String[0];
} else {
setter.fromNames = new String[]{fromName};
}
setter.name = fromName;
setter.method = method;
setter.annotations = method.getAnnotations();
setters.add(setter);
} catch (Exception e) {
throw new JsonException("failed to create binding from setter: " + method, e);
}
}
return setters;
}
private static List<Method> getAllMethods(Class clazz, boolean includingPrivate) {
List<Method> allMethods = Arrays.asList(clazz.getMethods());
if (includingPrivate) {
allMethods = new ArrayList<Method>();
Class current = clazz;
while (current != null) {
allMethods.addAll(Arrays.asList(current.getDeclaredMethods()));
current = current.getSuperclass();
}
}
return allMethods;
}
private static String translateSetterName(String methodName) {
if (!methodName.startsWith("set")) {
return null;
}
String fromName = methodName.substring("set".length());
char[] fromNameChars = fromName.toCharArray();
fromNameChars[0] = Character.toLowerCase(fromNameChars[0]);
fromName = new String(fromNameChars);
return fromName;
}
private static List<Binding> getGetters(Map<String, Type> lookup, ClassInfo classInfo, boolean includingPrivate) {
ArrayList<Binding> getters = new ArrayList<Binding>();
for (Method method : getAllMethods(classInfo.clazz, includingPrivate)) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
String methodName = method.getName();
if ("getClass".equals(methodName)) {
continue;
}
if (methodName.length() < 4) {
continue;
}
if (!methodName.startsWith("get")) {
continue;
}
if (method.getGenericParameterTypes().length != 0) {
continue;
}
String toName = methodName.substring("get".length());
char[] toNameChars = toName.toCharArray();
toNameChars[0] = Character.toLowerCase(toNameChars[0]);
toName = new String(toNameChars);
Binding getter = new Binding(classInfo, lookup, method.getGenericReturnType());
Field field = null;
try {
field = method.getDeclaringClass().getDeclaredField(toName);
} catch (NoSuchFieldException e) {
// ignore
}
if (field != null && isTransient(field.getModifiers())) {
getter.toNames = new String[0];
} else {
getter.toNames = new String[]{toName};
}
getter.name = toName;
getter.method = method;
getter.annotations = method.getAnnotations();
getters.add(getter);
}
return getters;
}
private static Map<String, Type> collectTypeVariableLookup(Type type) {
HashMap<String, Type> vars = new HashMap<String, Type>();
if (null == type) {
return vars;
}
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
Type[] actualTypeArguments = pType.getActualTypeArguments();
Class clazz = (Class) pType.getRawType();
for (int i = 0; i < clazz.getTypeParameters().length; i++) {
TypeVariable variable = clazz.getTypeParameters()[i];
vars.put(variable.getName() + "@" + clazz.getCanonicalName(), actualTypeArguments[i]);
}
vars.putAll(collectTypeVariableLookup(clazz.getGenericSuperclass()));
return vars;
}
if (type instanceof Class) {
Class clazz = (Class) type;
vars.putAll(collectTypeVariableLookup(clazz.getGenericSuperclass()));
return vars;
}
throw new JsonException("unexpected type: " + type);
}
public List<Binding> allBindings() {
ArrayList<Binding> bindings = new ArrayList<Binding>(8);
bindings.addAll(fields);
if (setters != null) {
bindings.addAll(setters);
}
if (getters != null) {
bindings.addAll(getters);
}
if (ctor != null) {
bindings.addAll(ctor.parameters);
}
if (bindingTypeWrappers != null) {
for (WrapperDescriptor setter : bindingTypeWrappers) {
bindings.addAll(setter.parameters);
}
}
return bindings;
}
public List<Binding> allDecoderBindings() {
ArrayList<Binding> bindings = new ArrayList<Binding>(8);
bindings.addAll(fields);
bindings.addAll(setters);
if (ctor != null) {
bindings.addAll(ctor.parameters);
}
for (WrapperDescriptor setter : bindingTypeWrappers) {
bindings.addAll(setter.parameters);
}
return bindings;
}
public List<Binding> allEncoderBindings() {
ArrayList<Binding> bindings = new ArrayList<Binding>(8);
bindings.addAll(fields);
bindings.addAll(getters);
return bindings;
}
public List<EncodeTo> encodeTos() {
HashMap<String, Integer> previousAppearance = new HashMap<String, Integer>();
ArrayList<EncodeTo> encodeTos = new ArrayList<EncodeTo>(8);
collectEncodeTo(encodeTos, fields, previousAppearance);
collectEncodeTo(encodeTos, getters, previousAppearance);
ArrayList<EncodeTo> removedNulls = new ArrayList<EncodeTo>(encodeTos.size());
for (EncodeTo encodeTo : encodeTos) {
if (encodeTo != null) {
removedNulls.add(encodeTo);
}
}
return removedNulls;
}
private void collectEncodeTo(ArrayList<EncodeTo> encodeTos, List<Binding> fields, HashMap<String, Integer> previousAppearance) {
for (Binding field : fields) {
for (String toName : field.toNames) {
if (previousAppearance.containsKey(toName)) {
encodeTos.set(previousAppearance.get(toName), null);
}
previousAppearance.put(toName, encodeTos.size());
EncodeTo encodeTo = new EncodeTo();
encodeTo.binding = field;
encodeTo.toName = toName;
encodeTos.add(encodeTo);
}
}
}
} |
package com.justjournal.rss;
import com.justjournal.utility.Xml;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Component
public class HeadlineBean {
private static final char endl = '\n';
class HeadlineContext {
protected URL u;
protected InputStream inputXML;
protected DocumentBuilder builder;
protected Document document;
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
}
protected HeadlineContext getRssDocument(final String uri)
throws Exception {
final HeadlineContext hc = new HeadlineContext();
//Open the file for reading:
hc.u = new URL(uri);
hc.inputXML = hc.u.openStream();
//Build document:
hc.factory.setValidating(false);
hc.factory.setIgnoringComments(true);
hc.factory.setCoalescing(true);
hc.builder = hc.factory.newDocumentBuilder();
hc.document = hc.builder.parse(hc.inputXML);
return hc;
}
public String parse(@NonNull final String url) {
try {
log.info("Starting parse");
HeadlineContext hc = getRssDocument(url);
log.info("Fetched, now create");
// output variable
final StringBuilder sb = new StringBuilder();
String contentTitle = "";
String contentLink = "";
String contentDescription = "";
String contentLastBuildDate = "";
String contentGenerator = "";
log.info("Prepare xml nodelists");
final org.w3c.dom.NodeList channelList = hc.document.getElementsByTagName("channel");
final org.w3c.dom.NodeList chnodes = channelList.item(0).getChildNodes();
String imageUrl = null;
String imageTitle = null;
String imageLink = "";
String imageWidth = null;
String imageHeight = null;
log.debug("Iterate through the nodelists");
for (int k = 0; k < chnodes.getLength(); k++) {
final org.w3c.dom.Node curNode = chnodes.item(k);
if (curNode.getNodeName().equals("title")) {
contentTitle = curNode.getChildNodes().item(0).getNodeValue();
} else if (curNode.getNodeName().equals("link")) {
contentLink = curNode.getChildNodes().item(0).getNodeValue();
} else if (curNode.getNodeName().equals("description")) {
contentDescription = curNode.getChildNodes().item(0).getNodeValue();
} else if (curNode.getNodeName().equals("lastBuildDate")) {
contentLastBuildDate = curNode.getChildNodes().item(0).getNodeValue();
} else if (curNode.getNodeName().equals("generator")) {
contentGenerator = curNode.getChildNodes().item(0).getNodeValue();
} else if (curNode.getNodeName().equals("image")) {
org.w3c.dom.NodeList imageNodes = curNode.getChildNodes();
for (int z = 0; z < imageNodes.getLength(); z++) {
if (imageNodes.item(z).getNodeName().equals("url")) {
imageUrl = imageNodes.item(z).getChildNodes().item(0).getNodeValue();
} else if (imageNodes.item(z).getNodeName().equals("height")) {
imageHeight = imageNodes.item(z).getChildNodes().item(0).getNodeValue();
} else if (imageNodes.item(z).getNodeName().equals("width")) {
imageWidth = imageNodes.item(z).getChildNodes().item(0).getNodeValue();
} else if (imageNodes.item(z).getNodeName().equals("title")) {
imageTitle = imageNodes.item(z).getChildNodes().item(0).getNodeValue();
} else if (imageNodes.item(z).getNodeName().equals("link")) {
imageLink = imageNodes.item(z).getChildNodes().item(0).getNodeValue();
}
}
}
}
log.debug("Prepare HTML output");
// create header!
sb.append("<div style=\"width: 100%; padding: .1in; background: #F2F2F2;\" class=\"ljfhead\">");
sb.append(endl);
sb.append("<!-- Generator: ");
sb.append(contentGenerator);
sb.append("
sb.append(endl);
if (imageUrl != null) {
sb.append("<span style=\"padding: 5px; float:left; ");
if (imageWidth != null && Integer.parseInt(imageWidth) > 0) {
sb.append("width:");
sb.append(imageWidth);
sb.append("px; ");
}
if (imageHeight != null && Integer.parseInt(imageHeight) > 0) {
sb.append("height:");
sb.append(imageHeight);
sb.append("px; ");
}
sb.append("position: relative;\">");
sb.append("<a href=\"");
sb.append(imageLink);
sb.append("\">");
sb.append("<img src=\"");
sb.append(imageUrl);
if (imageHeight != null && imageWidth != null
&& Integer.parseInt(imageWidth) > 0 && Integer.parseInt(imageHeight) > 0) {
// Only add height and width attributes if they are defined in the feed.
sb.append("\" height=\"");
sb.append(imageHeight);
sb.append("\" width=\"");
sb.append(imageWidth);
}
sb.append("\" alt=\"");
sb.append(imageTitle);
sb.append("\" title=\"");
sb.append(imageTitle);
sb.append("\" /></a></span>");
sb.append(endl);
}
sb.append("<h3 ");
if (contentDescription != null) {
sb.append("title=\"");
sb.append(contentDescription);
sb.append("\"");
}
sb.append(">");
sb.append(contentTitle);
sb.append("</h3>");
sb.append(endl);
// some rss feeds don't have a last build date
if (contentLastBuildDate != null && contentLastBuildDate.length() > 0) {
sb.append("<p>Updated: ");
sb.append(contentLastBuildDate);
sb.append("<br />");
} else {
sb.append("<p>");
}
/* if (contentDescription != null) {
sb.append(contentDescription);
sb.append("<br />");
}*/
if (contentLink != null) {
sb.append("<a href=\"").append(contentLink).append("\">[").append(contentLink).append("]</a>");
}
sb.append("</p>");
sb.append(endl);
sb.append("<div style=\"clear: both;\"> </div>");
sb.append(endl);
sb.append("</div>");
sb.append(endl);
//Generate the NodeList;
org.w3c.dom.NodeList nodeList = hc.document.getElementsByTagName("item");
sb.append("<ol class=\"RssItems\">");
sb.append(endl);
for (int i = 0; i < nodeList.getLength() && i < 16; i++) {
org.w3c.dom.NodeList childList = nodeList.item(i).getChildNodes();
// some of the properties of <items>
String link = null;
String title = null;
String pubDate = null;
String description = null;
String guid = null;
for (int j = 0; j < childList.getLength(); j++) {
if (childList.item(j).getNodeName().equals("link")) {
link = childList.item(j).getChildNodes().item(0).getNodeValue();
} else if (childList.item(j).getNodeName().equals("title")) {
title = childList.item(j).getChildNodes().item(0).getNodeValue();
} else if (childList.item(j).getNodeName().equals("pubDate")) {
pubDate = childList.item(j).getChildNodes().item(0).getNodeValue();
} else if (childList.item(j).getNodeName().equals("description")) {
description = childList.item(j).getChildNodes().item(0).getNodeValue();
} else if (childList.item(j).getNodeName().equals("guid")) {
guid = childList.item(j).getChildNodes().item(0).getNodeValue();
}
}
// assert the basic properties are there.
if (link != null && title != null) {
sb.append("<li class=\"RssItem\">");
sb.append("<span onclick=\"expandcontent(this, 'r").append(url.hashCode()).append("_").append(i).append("')\" class=\"RssItemTitle\">");
sb.append("<span class=\"showstate\"></span> ");
sb.append("<!-- guid: ");
sb.append(guid);
sb.append("
sb.append("<a href=\"");
sb.append(link);
sb.append("\" title=\"");
sb.append(Xml.cleanString(title));
sb.append("\" >");
sb.append(Xml.cleanString(title));
sb.append("</a>");
sb.append("</span>");
sb.append(endl);
sb.append("<div id=\"r").append(url.hashCode()).append("_").append(i).append("\" class=\"switchcontent\">");
sb.append("<br />");
sb.append("<span class=\"RssItemDesc\">");
/*
/<(script|noscript|object|embed|style|frameset|frame|iframe)[>\s\S]*<\/\\1>/i /<\/?!?(param|link|meta|doctype|div|font)[^>]*>/i /(class|style|id)=\"[^\"]*\"/i
*/
Pattern p = Pattern.compile("/<(script|noscript|object|embed|style|frameset|frame|iframe|link)[>\\s\\S]*<\\/\\1>/i");
Matcher m = p.matcher(description);
String result = m.replaceAll("");
sb.append(result);
sb.append("</span>");
sb.append(" <span class=\"RssReadMore\">");
sb.append("<a href=\"");
sb.append(link); // TODO: was guid ... why
sb.append("\">");
sb.append("Read More</a></span>");
sb.append(endl);
// some rss versions don't have a pub date per entry
if (pubDate != null) {
sb.append(" <br /><span class=\"RssItemPubDate\">");
sb.append(pubDate);
sb.append("</span>");
sb.append(endl);
}
sb.append("</div>");
sb.append(endl);
sb.append("</li>");
sb.append(endl);
}
}
sb.append("</ol>");
sb.append(endl);
return sb.toString();
} catch (final java.io.FileNotFoundException e404) {
log.warn("Feed is not available " + url + e404.getMessage(), e404);
return "<p>404 Not Found. The feed is no longer available. " + url + endl;
} catch (final org.xml.sax.SAXParseException sp) {
if (sp.getMessage().contains("Premature end of file"))
return "<p>Feed is empty at " + url;
else
return "<p>Bad Feed " + sp.toString() + " for url: " + url + endl;
} catch (final Exception e) {
return "<p>Error, could not process request: " + e.toString() + " for url: " + url + endl;
}
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:16-08-31");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package com.matt.forgehax.mods;
import com.google.common.collect.Lists;
import com.matt.forgehax.Wrapper;
import com.matt.forgehax.util.Utils;
import com.matt.forgehax.util.command.*;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import com.sun.xml.internal.ws.message.Util;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.common.config.Configuration;
import com.matt.forgehax.asm.events.PacketEvent;
import net.minecraft.network.play.client.CPacketChatMessage;
import net.minecraftforge.event.world.WorldEvent;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
@RegisterMod
public class IgnoreMod extends ToggleMod {
private long lastMessageTime = 0L;
private Pattern pattern = Pattern.compile("^([\\w*<>]+)");
private List<String> ignoreList = Lists.newCopyOnWriteArrayList();
public IgnoreMod() {
super("IgnoreMod", false, "Clientside ignore");
}
private void parseNameFile(File file) {
if (!file.exists() || !file.isFile()) return;
ignoreList.clear();
try {
Scanner scanner = new Scanner(new FileReader(file));
scanner.useDelimiter("\r\n");
while (scanner.hasNext()) {
String name = scanner.next();
if (name.length() > 16)
name = name.substring(0, 15);
ignoreList.add(name);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@SubscribeEvent
public void onWorldLoad(WorldEvent.Load event) {
File nameFile = new File(MOD.getBaseDirectory(), "ignorelist.txt");
parseNameFile(nameFile);
}
@SubscribeEvent
public void onClientChat(ClientChatReceivedEvent event) {
String message = (event.getMessage().getUnformattedText());
Matcher matcher = pattern.matcher(message);
if (matcher.find()) {
String messagePlayer = message.substring(matcher.start(), matcher.end()).trim()
.replaceAll("<>","").toLowerCase();
if (ignoreList.contains(messagePlayer) || message.contains(" ur ignored get raped"))
event.setCanceled(true); // chat message has been (((shut down)))
if (System.currentTimeMillis() >= lastMessageTime + 1500L) {
CPacketChatMessage packet = new CPacketChatMessage("/pm " + messagePlayer + " ur ignored get raped");
Utils.OUTGOING_PACKET_IGNORE_LIST.add(packet);
Wrapper.getNetworkManager().sendPacket(packet);
lastMessageTime = System.currentTimeMillis();
}
}
}
@Override
public void onLoad() {
CommandRegistry.registerGlobal(new CommandBuilder()
.setName("ignore")
.setDescription("Ignore a player")
.setProcessor(options -> {
List<?> args = options.nonOptionArguments();
if (args.size() > 0) {
String addName = String.valueOf(args.get(0));
// do stuff
if (ignoreList.contains((addName))) {
ignoreList.remove(ignoreList.indexOf(addName));
MC.player.sendMessage(new TextComponentString("\u00A7a" + addName + " has been unignored"));
}
else {
ignoreList.add(addName);
MC.player.sendMessage(new TextComponentString("\u00A77" + addName + " has been ignored"));
}
try {
File nameFile = new File(MOD.getBaseDirectory(), "ignorelist.txt");
FileWriter fw = new FileWriter(nameFile);
BufferedWriter bw = new BufferedWriter(fw);
for (String s : ignoreList) {
bw.write(s + "\r\n");
}
bw.close();
fw.close();
} catch (Exception e) {
}
// end of doing stuff
return true;
} else {
// missing argument
}
return false;
})
.build()
);
}
} |
package com.moandjiezana.toml;
import static com.moandjiezana.toml.ValueConverterUtils.INVALID;
import static com.moandjiezana.toml.ValueConverterUtils.parse;
import static com.moandjiezana.toml.ValueConverterUtils.parser;
import java.util.List;
import java.util.regex.Pattern;
class TomlParser {
private static final Pattern MULTILINE_ARRAY_REGEX = Pattern.compile("\\s*\\[([^\\]]*)");
private static final Pattern MULTILINE_ARRAY_REGEX_END = Pattern.compile("\\s*\\]");
private static final ValueConverters VALUE_ANALYSIS = new ValueConverters();
private final Results results = new Results();
Results run(String tomlString) {
if (tomlString.isEmpty()) {
return results;
}
String[] lines = tomlString.split("[\\n\\r]");
StringBuilder multilineBuilder = new StringBuilder();
Multiline multiline = Multiline.NONE;
String key = null;
String value = null;
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
if (line != null && multiline != Multiline.STRING) {
line = line.trim();
}
if (isComment(line) || line.isEmpty()) {
continue;
}
if (isTableArray(line)) {
String tableName = getTableArrayName(line);
if (tableName != null) {
results.startTableArray(tableName);
String afterTableName = line.substring(tableName.length() + 4);
if (!isComment(afterTableName)) {
results.errors.append("Invalid table array definition: " + line + "\n\n");
}
} else {
results.errors.append("Invalid table array definition: " + line + "\n\n");
}
continue;
}
if (multiline.isNotMultiline() && isTable(line)) {
String tableName = getTableName(line);
if (tableName != null) {
results.startTables(tableName);
} else {
results.errors.append("Invalid table definition: " + line + "\n\n");
}
continue;
}
if (multiline.isNotMultiline() && !line.contains("=")) {
results.errors.append("Invalid key definition: " + line);
continue;
}
String[] pair = line.split("=", 2);
if (multiline.isNotMultiline() && MULTILINE_ARRAY_REGEX.matcher(pair[1].trim()).matches()) {
multiline = Multiline.ARRAY;
key = pair[0].trim();
multilineBuilder.append(removeComment(pair[1]));
continue;
}
if (multiline.isNotMultiline() && pair[1].trim().startsWith("\"\"\"")) {
multiline = Multiline.STRING;
multilineBuilder.append(pair[1]);
key = pair[0].trim();
if (pair[1].trim().indexOf("\"\"\"", 3) > -1) {
multiline = Multiline.NONE;
pair[1] = multilineBuilder.toString().trim();
multilineBuilder.delete(0, multilineBuilder.length());
} else {
continue;
}
}
if (multiline == Multiline.ARRAY) {
String lineWithoutComment = removeComment(line);
multilineBuilder.append(lineWithoutComment);
if (MULTILINE_ARRAY_REGEX_END.matcher(lineWithoutComment).matches()) {
multiline = Multiline.NONE;
value = multilineBuilder.toString();
multilineBuilder.delete(0, multilineBuilder.length());
} else {
continue;
}
} else if (multiline == Multiline.STRING) {
multilineBuilder.append(line);
if (line.contains("\"\"\"")) {
multiline = Multiline.NONE;
value = multilineBuilder.toString().trim();
multilineBuilder.delete(0, multilineBuilder.length());
} else {
multilineBuilder.append('\n');
continue;
}
} else {
key = pair[0].trim();
value = pair[1].trim();
}
if (!isKeyValid(key)) {
results.errors.append("Invalid key name: " + key + "\n");
continue;
}
Object convertedValue = VALUE_ANALYSIS.convert(value);
if (convertedValue != INVALID) {
results.addValue(key, convertedValue);
} else {
results.errors.append("Invalid key/value: " + key + " = " + value + "\n");
}
}
return results;
}
private boolean isTableArray(String line) {
return line.startsWith("[[");
}
private String getTableArrayName(String line) {
List<Object> resultValue = parse(parser().TableArray(), line);
if (resultValue == null) {
return null;
}
return (String) resultValue.get(0);
}
private boolean isTable(String line) {
return line.startsWith("[");
}
private String getTableName(String line) {
List<Object> resultValue = parse(parser().Table(), line);
if (resultValue == null) {
return null;
}
return (String) resultValue.get(0);
}
private boolean isKeyValid(String key) {
if (key.contains("#") || key.trim().isEmpty()) {
return false;
}
return true;
}
private boolean isComment(String line) {
if (line == null || line.isEmpty()) {
return true;
}
char[] chars = line.toCharArray();
for (char c : chars) {
if (Character.isWhitespace(c)) {
continue;
}
return c == '
}
return false;
}
private String removeComment(String line) {
line = line.trim();
if (line.startsWith("\"")) {
int startOfComment = line.indexOf('#', line.lastIndexOf('"'));
if (startOfComment > -1) {
return line.substring(0, startOfComment - 1).trim();
}
} else {
int startOfComment = line.indexOf('
if (startOfComment > -1) {
return line.substring(0, startOfComment - 1).trim();
}
}
return line;
}
private static enum Multiline {
NONE, ARRAY, STRING;
public boolean isNotMultiline() {
return this == NONE;
}
}
} |
package com.molina.cvmfs.catalog;
import com.molina.cvmfs.common.DatabaseObject;
import com.molina.cvmfs.directoryentry.DirectoryEntry;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* @author Jose Molina Colmenero
*
* Wraps the basic functionality of CernVM-FS Catalogs
*/
public class Catalog extends DatabaseObject {
public static final char CATALOG_ROOT_PREFIX = 'C';
protected float schema;
protected int schemaRevision;
protected String hash;
public static Catalog open(String catalogPath) throws SQLException {
return new Catalog(new File(catalogPath), "");
}
public float getSchema() {
return schema;
}
public Catalog(File databaseFile, String catalogHash) throws SQLException {
super(databaseFile);
this.hash = catalogHash;
readProperties();
guessRootPrefixIfNeeded();
guessLastModifiedIfNeeded();
checkValidity();
}
protected void checkValidity() {
}
protected void guessLastModifiedIfNeeded() {
}
protected void guessRootPrefixIfNeeded() {
}
protected void readProperties() {
}
public boolean hasNested() {
return nestedCount() > 0;
}
/**
* Returns the number of nested catalogs in the catalog
* @return the number of nested catalogs in this catalog
*/
public int nestedCount(){
ResultSet rs = null;
int numCatalogs = 0;
try {
rs = runSQL("SELECT count(*) FROM nested_catalogs;");
if (rs.next())
numCatalogs = rs.getInt(0);
} catch (SQLException e) {
return 0;
}
return numCatalogs;
}
/**
* List CatalogReferences to all contained nested catalogs
* @return array of CatalogReference containing all nested catalogs in this catalog
*/
public CatalogReference[] listNested() {
boolean newVersion = (schema <= 1.2 && schemaRevision > 0);
String sqlQuery;
if (newVersion) {
sqlQuery = "SELECT path, sha1, size FROM nested_catalogs";
} else {
sqlQuery = "SELECT path, sha1 FROM nested_catalogs";
}
ResultSet rs;
ArrayList<CatalogReference> arr = new ArrayList<CatalogReference>();
try {
rs = runSQL(sqlQuery);
while (rs.next()) {
String path = rs.getString(0);
String sha1 = rs.getString(1);
int size = 0;
if (newVersion)
size = rs.getInt(2);
arr.add(new CatalogReference(path, sha1, size));
}
} catch (SQLException e) {
return new CatalogReference[0];
}
return arr.toArray(new CatalogReference[arr.size()]);
}
public CatalogStatistics getStatistics() {
try {
return new CatalogStatistics(this);
} catch (SQLException e) {
return null;
}
}
/**
* Find the best matching nested CatalogReference for a given path
* @param needlePath path to search in the catalog
* @return The catalogs that best matches the given path
*/
public CatalogReference findNestedForPath(String needlePath) {
CatalogReference[] catalogRefs = listNested();
CatalogReference bestMatch = null;
int bestMatchScore = 0;
String realNeedlePath = cannonicalizePath(needlePath);
for (CatalogReference nestedCatalog : catalogRefs) {
if (realNeedlePath.startsWith(nestedCatalog.getRootPath()) &&
nestedCatalog.getRootPath().length() > bestMatchScore) {
bestMatchScore = nestedCatalog.getRootPath().length();
bestMatch = nestedCatalog;
}
}
return bestMatch;
}
/**
* Create a directory listing of the given directory path
* @param path path to be listed
* @return a list with all the DirectoryEntries contained in that path
*/
public DirectoryEntry[] listDirectory(String path) {
}
private static String cannonicalizePath(String path) {
if (path == null)
return "";
return new File(path).getAbsolutePath();
}
} |
package com.peak.salut;
import android.content.Context;
import com.peak.salut.Callbacks.SalutDataCallback;
public class SalutDataReceiver {
protected SalutDataCallback dataCallback;
protected Context context;
public SalutDataReceiver(Context applicationContext, SalutDataCallback dataCallback) {
this.dataCallback = dataCallback;
this.context = applicationContext;
}
} |
package com.wanasit.chrono;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.wanasit.chrono.filter.LowProbabilityFormatFilter;
import com.wanasit.chrono.filter.PrefixCheckFilter;
import com.wanasit.chrono.parser.en.*;
import com.wanasit.chrono.parser.jp.JPStandartDateFormatParser;
import com.wanasit.chrono.refiner.MergeDateAndTimeRefiner;
import com.wanasit.chrono.refiner.MergeDateRangeRefiner;
import com.wanasit.chrono.refiner.RemoveOverlapRefiner;
public class ChronoOptions {
public static final ChronoOptions sharedOptions = createStandartOptions();
public static ChronoOptions createStandartOptions() {
ChronoOptions options = new ChronoOptions();
// All Parsers
options.parserClasses.add(ENInternationalStandardParser.class);
options.parserClasses.add(ENMonthNameLittleEndianParser.class);
options.parserClasses.add(ENMonthNameMiddleEndianParser.class);
options.parserClasses.add(ENSlashBigEndianDateFormatParser.class);
options.parserClasses.add(ENSlashDateFormatParser.class);
options.parserClasses.add(ENTimeExpressionParser.class);
options.parserClasses.add(JPStandartDateFormatParser.class);
// Standard Pipeline
options.refinerClasses.add(PrefixCheckFilter.class);
options.refinerClasses.add(RemoveOverlapRefiner.class);
options.refinerClasses.add(MergeDateAndTimeRefiner.class);
options.refinerClasses.add(MergeDateRangeRefiner.class);
options.refinerClasses.add(LowProbabilityFormatFilter.class);
return options;
}
public List< Class<? extends Parser > > parserClasses = null;
public List< Class<? extends Refiner> > refinerClasses = null;
public Integer timezoneOffset = null;
public Map<String, Integer> timezoneMap = null;
protected ChronoOptions() {
this.parserClasses = new LinkedList<Class<? extends Parser>>();
this.refinerClasses = new LinkedList<Class<? extends Refiner>>();
this.timezoneOffset = Calendar.getInstance().getTimeZone().getOffset(0);
this.timezoneMap = new HashMap<String, Integer>();
}
} |
package com.whammich.sstow;
import com.whammich.sstow.util.EntityMapper;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ConfigHandler {
public static Configuration config;
public static List<String> entityList = new ArrayList<String>();
public static int spawnCap;
public static int soulStealerID;
public static int soulStealerWeight;
public static void init(File file) {
config = new Configuration(file);
syncConfig();
}
public static void syncConfig() {
String category;
category = "Entity List";
handleEntityList(category);
category = "General";
spawnCap = config.getInt("spawnCap", category, 30, 0, 256, "Max amount of mobs spawned by a given spawner in a 16 block radius.");
category = "Enchantments";
soulStealerID = config.getInt("soulStealerID", category, 70, 63, 256, "ID for the Soul Stealer enchantment. If you have Enchantment ID conflicts, change this.");
soulStealerWeight = config.getInt("soulStealerWeight", category, 3, 1, 10, "Weight of the Soul Stealer enchantment. Higher values make it more common.");
if (config.hasChanged())
config.save();
}
private static void handleEntityList(String category) {
for (String name : EntityMapper.entityList)
if (config.get(category, name, true).getBoolean(true))
entityList.add(name);
}
} |
package com.yahoo.sketches.fdt;
import static com.yahoo.sketches.Util.MAX_LG_NOM_LONGS;
import java.util.List;
import com.yahoo.memory.Memory;
import com.yahoo.sketches.BinomialBoundsN;
import com.yahoo.sketches.SketchesArgumentException;
import com.yahoo.sketches.tuple.strings.ArrayOfStringsSketch;
/**
* A Frequent Distinct Tuples sketch.
*
* <p>Given a multiset of tuples with dimensions <i>{d1,d2, d3, ..., dN}</i>, and a primary subset of
* dimensions <i>M < N</i>, the task is to identify the combinations of <i>M</i> subset dimensions
* that have the most frequent number of distinct combinations of the <i>N-M</i> non-primary
* dimensions.
*
* <p>For example, assume <i>N=3, M=2</i>, where the primary dimensions are <i>(d1, d2)</i>.
* After populating the sketch with a stream of tuples, we wish to identify the primary dimension
* combinations of <i>(d1, d2)</i> that have the most frequent number of distinct occurrences of
* <i>d3</i>.
*
* <p>Alternatively, if we choose the primary dimension as <i>d1</i>, then we can identify the
* <i>d1</i>s that have the most frequent distinct combinations of <i>(d2 and d3)</i>. The choice of
* which dimensions to choose as the primary dimensions is performed in a post-processing phase
* after the sketch has been populated.
*
* <p>As a simple concrete example, let's assume <i>N = 2</i> and let <i>d1 := IP address</i>, and
* <i>d2 := User ID</i>.
* Let's choose <i>d1</i> as the primary dimension, then the sketch allows the identification of the
* <i>IP addresses</i> that have the largest populations of distinct <i>User IDs</i>. Conversely,
* if we choose <i>d2</i> as the primary dimension, the sketch allows the identification of the
* <i>User IDs</i> with the largest populations of distinct <i>IP addresses</i>.
*
* <p>An important caveat is that if the distribution is too flat, there may not be any
* "most frequent" combinations of the primary keys above the threshold. Also, if one primary key
* is too dominant, the sketch may be able to only report on the single most frequent primary
* key combination, which means the possible existance of false negatives.
*
* <p>In this implementation the input tuples presented to the sketch are string arrays.
*
* @author Lee Rhodes
*/
public class FdtSketch extends ArrayOfStringsSketch {
/**
* Create new instance of Frequent Distinct Tuples sketch with the given
* Log-base2 of required nominal entries.
* @param lgK Log-base2 of required nominal entries.
*/
public FdtSketch(final int lgK) {
super(lgK);
}
/**
* Used by deserialization.
* @param mem the image of a FdtSketch
*/
FdtSketch(final Memory mem) {
super(mem);
}
/**
* Create a new instance of Frequent Distinct Tuples sketch with a size determined by the given
* threshold and rse.
* @param threshold : the fraction, between zero and 1.0, of the total distinct stream length
* that defines a "Frequent" (or heavy) item.
* @param rse the maximum Relative Standard Error for the estimate of the distinct population of a
* reported tuple (selected with a primary key) at the threshold.
*/
public FdtSketch(final double threshold, final double rse) {
super(computeLgK(threshold, rse));
}
/**
* Update the sketch with the given string array tuple.
* @param tuple the given string array tuple.
*/
public void update(final String[] tuple) {
super.update(tuple, tuple);
}
/**
* Returns a List of Rows of the most frequent distinct population of subset tuples represented
* by the count of entries of that subset
* @param priKeyIndices these indices define the primary dimensions of the input tuples
* @param limit the maximum number of rows (subset groups) to return. If this value is ≤ 0, all
* rows will be returned.
* @param numStdDev
* <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a>
* @return a List of Rows of the most frequent distinct population of subset tuples represented
* by the count of entries of that subset
*/
public List<Group<String>> getResult(final int[] priKeyIndices, final int limit, final int numStdDev) {
final PostProcessor proc = new PostProcessor(this);
return proc.getGroupList(priKeyIndices, numStdDev, limit);
}
/**
* Returns the PostProcessor that enables multiple queries against the sketch results.
* @return the PostProcessor
*/
public PostProcessor getPostProcessor() {
return new PostProcessor(this);
}
/**
* Gets the estimate of the distinct population of subset tuples represented by the count of
* entries of that subset.
* @param numSubsetEntries number of entries for a chosen subset of the sketch.
* @return the estimate of the distinct population represented by the sketch subset.
*/
public double getEstimate(final int numSubsetEntries) {
if (!isEstimationMode()) { return numSubsetEntries; }
return numSubsetEntries / getTheta();
}
/**
* Gets the estimate of the lower bound of the distinct population represented by a sketch subset,
* given numStdDev and numSubsetEntries.
* @param numStdDev
* <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a>
* @param numSubsetEntries number of entries for a chosen subset of the sketch.
* @return the estimate of the lower bound of the distinct population represented by the sketch
* subset given numStdDev and numSubsetEntries.
*/
public double getLowerBound(final int numStdDev, final int numSubsetEntries) {
if (!isEstimationMode()) { return numSubsetEntries; }
return BinomialBoundsN.getLowerBound(numSubsetEntries, getTheta(), numStdDev, isEmpty());
}
/**
* Gets the estimate of the upper bound of the distinct population represented by a sketch subset,
* given numStdDev and numSubsetEntries.
* @param numStdDev
* <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a>
* @param numSubsetEntries number of entries for a chosen subset of the sketch.
* @return the estimate of the upper bound of the distinct population represented by the sketch
* subset given numStdDev and numSubsetEntries.
*/
public double getUpperBound(final int numStdDev, final int numSubsetEntries) {
if (!isEstimationMode()) { return numSubsetEntries; }
return BinomialBoundsN.getUpperBound(numSubsetEntries, getTheta(), numStdDev, isEmpty());
}
// Restricted
/**
* Computes LgK given the threshold and RSE.
* @param threshold the fraction, between zero and 1.0, of the total stream length that defines
* a "Frequent" (or heavy) tuple.
* @param rse the maximum Relative Standard Error for the estimate of the distinct population of a
* reported tuple (selected with a primary key) at the threshold.
* @return LgK
*/
static int computeLgK(final double threshold, final double rse) {
final double v = Math.ceil(1.0 / (threshold * rse * rse));
final int lgK = (int) Math.ceil(Math.log(v) / Math.log(2));
if (lgK > MAX_LG_NOM_LONGS) {
throw new SketchesArgumentException("Requested Sketch (LgK = " + lgK + ") is too large, "
+ "either increase the threshold, the rse or both.");
}
return lgK;
}
} |
package de.predic8.routes;
import de.predic8.Endpoints;
import de.predic8.util.*;
import org.apache.camel.builder.RouteBuilder;
public class ArchiverRoutes extends RouteBuilder {
public void configure() throws Exception {
//from("file:document-archive/in?noop=true").routeId("Archiver")
from("file:document-archive/in?readLock=changed").routeId("ArchiverRoute")
.log("Got File: ${in.header.CamelFileName}")
.setProperty("fileName").simple("/${date:now:yyyy}/${date:now:MM}/${date:now:HH-mm-ss-S}_${in.header.CamelFileName}")
.process(new NormalizeFileName())
.process(new CreateMessageDigest())
.to(Endpoints.archiveFolder)
.to("direct:get-last-hash")
.process(new AddHashedBodyToDigest())
.setProperty("entry").simple("${date:now:yyyy-MM-dd HH:mm:ss} ${property.fileName} ${property.digest}")
.setBody().simple("${property.entry}\n")
.transform(body().append("\n"))
.to(Endpoints.logFile)
.to(Endpoints.notifyFile)
.setBody().simple("${property.entry}");
/* SEND HASH TO TWITTER
.to(String.format("twitter://timeline/user?consumerKey=%s&consumerSecret=%s&accessToken=%s&accessTokenSecret=%s"
, PropertyFile.getInstance("twitter_consumerKey")
, PropertyFile.getInstance("twitter_consumerSecret")
, PropertyFile.getInstance("twitter_accessToken")
, PropertyFile.getInstance("twitter_accessTokenSecret")));
*/
from("direct:get-last-hash").routeId("LastHash")
.process(new LogExists())
.choice()
.when(exchangeProperty("fileExists"))
.process(new GetLastHash())
.otherwise()
.setBody().simple("123")
.end();
}
} |
package de.prob2.ui;
import java.io.IOException;
import java.util.HashMap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import de.prob2.ui.animations.AnimationsView;
import de.prob2.ui.history.HistoryView;
import de.prob2.ui.modelchecking.ModelcheckingController;
import de.prob2.ui.operations.OperationsView;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Accordion;
import javafx.scene.control.TitledPane;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
@Singleton
public final class AnimationPerspective extends BorderPane {
// TODO improve DragDrop/Docking
// FIXME "expanded" empty accordions
// FIXME drag view model checking
// TODO? revert to SplitPane
@FXML
private OperationsView operations;
@FXML
private TitledPane operationsTP;
@FXML
private HistoryView history;
@FXML
private TitledPane historyTP;
@FXML
private ModelcheckingController modelcheck;
@FXML
private TitledPane modelcheckTP;
@FXML
private AnimationsView animations;
@FXML
private TitledPane animationsTP;
@FXML
private Accordion leftAccordion;
@FXML
private Accordion rightAccordion;
@FXML
private Accordion topAccordion;
@FXML
private Accordion bottomAccordion;
private boolean dragged;
private ImageView snapshot = new ImageView();
private HashMap<Node, TitledPane> nodeMap = new HashMap<Node, TitledPane>();
@Inject
private AnimationPerspective(FXMLLoader loader) {
loader.setLocation(getClass().getResource("animation_perspective.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void initialize() {
double initialHeight = 200;
double initialWidth = 280;
operations.setPrefSize(initialWidth,initialHeight);
history.setPrefSize(initialWidth,initialHeight);
modelcheck.setPrefSize(initialWidth,initialHeight);
animations.setPrefSize(initialWidth,initialHeight);
nodeMap.put(operations,operationsTP);
nodeMap.put(history,historyTP);
nodeMap.put(modelcheck,modelcheckTP);
nodeMap.put(animations,animationsTP);
leftAccordion.setExpandedPane(operationsTP);
onDrag();
}
private void onDrag() {
for (Node node:nodeMap.keySet()){
registerDrag(node);
}
}
private void registerDrag(final Node node){
node.setOnMouseEntered(mouseEvent -> this.setCursor(Cursor.OPEN_HAND));
node.setOnMousePressed(mouseEvent -> this.setCursor(Cursor.CLOSED_HAND));
node.setOnMouseDragEntered(mouseEvent -> {
dragged = true;
mouseEvent.consume();
});
node.setOnMouseDragged(mouseEvent -> {
Point2D position = this.sceneToLocal(new Point2D(mouseEvent.getSceneX(), mouseEvent.getSceneY()));
snapshot.relocate(position.getX(), position.getY());
mouseEvent.consume();
});
node.setOnMouseReleased(mouseEvent -> {
this.setCursor(Cursor.DEFAULT);
if (dragged){
dragDropped(node,mouseEvent);
}
dragged = false;
snapshot.setImage(null);
((BorderPane) this.getParent()).getChildren().remove(snapshot);
mouseEvent.consume();
});
node.setOnDragDetected(mouseEvent -> {
node.startFullDrag();
SnapshotParameters snapParams = new SnapshotParameters();
snapParams.setFill(Color.TRANSPARENT);
snapshot.setImage(node.snapshot(snapParams,null));
snapshot.setFitWidth(200);
snapshot.setPreserveRatio(true);
((BorderPane) this.getParent()).getChildren().add(snapshot);
mouseEvent.consume();
});
}
private void dragDropped(final Node node, MouseEvent mouseEvent){
//System.out.println(node.getClass().toString() + " dragged, isResizable() = "+node.isResizable());
TitledPane nodeTP = nodeMap.get(node);
Accordion accordion = (Accordion) nodeTP.getParent();
nodeTP.setCollapsible(false);
/*if (accordion.getPanes().contains(nodeTP)) {
if (this.getRight() == null) {
this.setRight(node);
} else if (this.getTop() == null) {
this.setTop(node);
} else if (this.getBottom() == null) {
this.setBottom(node);
} else if (this.getLeft() == null) {
this.setLeft(node);
}*/
if (rightAccordion.getPanes().isEmpty()) {
rightAccordion.getPanes().add(nodeTP);
} else if (topAccordion.getPanes().isEmpty()) {
nodeTP.setCollapsible(true);
topAccordion.getPanes().add(nodeTP);
} else if (bottomAccordion.getPanes().isEmpty()) {
nodeTP.setCollapsible(true);
bottomAccordion.getPanes().add(nodeTP);
} else {
leftAccordion.getPanes().add(nodeTP);
}
accordion.getPanes().remove(nodeTP);
nodeTP.setExpanded(true);
if (((Accordion) nodeTP.getParent()).getPanes().size()>1){
nodeTP.setCollapsible(true);
}
leftAccordion.getPanes().get(0).setExpanded(true);
if (leftAccordion.getPanes().size()==1){
leftAccordion.getPanes().get(0).setCollapsible(false);
} else {
leftAccordion.getPanes().get(0).setCollapsible(true);
}
Point2D position = this.sceneToLocal(new Point2D(mouseEvent.getSceneX(), mouseEvent.getSceneY()));
System.out.println("X = " + position.getX() + "; Y = " + position.getY());
System.out.println(this.getScene().getWidth() + ":" +this.getScene().getHeight());
/*if (accordion.getPanes().size()==1){
this.setLeft(node);
this.getChildren().remove(accordion);
}*/
/*} else {
if (!this.getChildren().contains(accordion)){
accordion.getPanes().add(nodeMap.get(this.getLeft()));
this.setLeft(accordion);
}
accordion.getPanes().add(nodeTP);
nodeTP.setContent(node);
accordion.setExpandedPane(nodeTP);
this.getChildren().remove(node);
}*/
}
} |
package de.prob2.ui.prob2fx;
import java.io.IOException;
import java.util.Map;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import de.prob.animator.IAnimator;
import de.prob.animator.command.GetCurrentPreferencesCommand;
import de.prob.exception.CliError;
import de.prob.exception.ProBError;
import de.prob.model.representation.AbstractModel;
import de.prob.scripting.Api;
import de.prob.scripting.ModelTranslationError;
import de.prob.statespace.AnimationSelector;
import de.prob.statespace.IAnimationChangeListener;
import de.prob.statespace.State;
import de.prob.statespace.StateSpace;
import de.prob.statespace.Trace;
import de.prob.statespace.Transition;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyListProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
* A singleton writable property that represents the current {@link Trace}. It
* also provides convenience properties and methods for easy interaction with
* JavaFX components using property binding.
*/
@Singleton
public final class CurrentTrace extends SimpleObjectProperty<Trace> {
private final AnimationSelector animationSelector;
private final Api api;
private final BooleanProperty exists;
private final BooleanProperty animatorBusy;
private final CurrentState currentState;
private final CurrentStateSpace stateSpace;
private final CurrentModel model;
private final ListProperty<Transition> transitionListWritable;
private final ListProperty<Transition> transitionList;
private final BooleanProperty canGoBack;
private final BooleanProperty canGoForward;
private final ObjectProperty<Trace> back;
private final ObjectProperty<Trace> forward;
@Inject
private CurrentTrace(
final AnimationSelector animationSelector,
final Api api,
final CurrentState currentState,
final CurrentStateSpace currentStateSpace,
final CurrentModel currentModel
) {
super(null);
this.animationSelector = animationSelector;
this.animationSelector.registerAnimationChangeListener(new IAnimationChangeListener() {
@Override
public void traceChange(final Trace currentTrace, final boolean currentAnimationChanged) {
Platform.runLater(() -> CurrentTrace.this.set(currentTrace));
}
@Override
public void animatorStatus(final boolean busy) {
Platform.runLater(() -> CurrentTrace.this.animatorBusy.set(busy));
}
});
this.api = api;
this.exists = new SimpleBooleanProperty(this, "exists", false);
this.exists.bind(Bindings.isNotNull(this));
this.animatorBusy = new SimpleBooleanProperty(this, "animatorBusy", false);
this.animatorBusy.addListener((observable, from, to) -> {
if (to) {
this.get().getStateSpace().startTransaction();
} else {
this.get().getStateSpace().endTransaction();
}
});
this.currentState = currentState;
this.stateSpace = currentStateSpace;
this.model = currentModel;
this.transitionListWritable = new SimpleListProperty<>(this, "transitionListWritable",
FXCollections.observableArrayList());
this.transitionList = new SimpleListProperty<>(this, "transitionList",
FXCollections.unmodifiableObservableList(this.transitionListWritable));
this.canGoBack = new SimpleBooleanProperty(this, "canGoBack", false);
this.canGoForward = new SimpleBooleanProperty(this, "canGoForward", false);
this.back = new SimpleObjectProperty<>(this, "back", null);
this.forward = new SimpleObjectProperty<>(this, "forward", null);
this.addListener((observable, from, to) -> {
if (to == null) {
clearProperties();
} else {
this.animationSelector.traceChange(to);
this.currentState.set(to.getCurrentState());
this.stateSpace.set(to.getStateSpace());
this.model.set(to.getModel());
this.transitionListWritable.setAll(to.getTransitionList());
this.canGoBack.set(to.canGoBack());
this.canGoForward.set(to.canGoForward());
this.back.set(to.back());
this.forward.set(to.forward());
}
});
}
private void clearProperties() {
this.currentState.set(null);
this.stateSpace.set(null);
this.model.set(null);
this.transitionListWritable.clear();
this.canGoBack.set(false);
this.canGoForward.set(false);
this.back.set(null);
this.forward.set(null);
}
/**
* A read-only boolean property indicating whether a current trace exists
* (i. e. is not null).
*
* @return a boolean property indicating whether a current trace exists
*/
public ReadOnlyBooleanProperty existsProperty() {
return this.exists;
}
/**
* Return whether a current trace exists (i. e. is not null).
*
* @return whether a current trace exists
*/
public boolean exists() {
return this.existsProperty().get();
}
/**
* A writable property indicating whether the animator is currently busy. It
* holds the last value reported by
* {@link IAnimationChangeListener#animatorStatus(boolean)}. When written
* to, {@link IAnimator#startTransaction()} or
* {@link IAnimator#endTransaction()} is called on the current
* {@link StateSpace}.
*
* @return a property indicating whether the animator is currently busy
*/
public BooleanProperty animatorBusyProperty() {
return this.animatorBusy;
}
/**
* Return whether the animator is currently busy.
*
* @return whether the animator is currently busy
*/
public boolean isAnimatorBusy() {
return this.animatorBusyProperty().get();
}
/**
* Set the animator's busy status.
*
* @param busy
* the new busy status
*/
public void setAnimatorBusy(final boolean busy) {
this.animatorBusyProperty().set(busy);
}
/**
* A {@link CurrentState} holding the current {@link Trace}'s {@link State}.
*
* @return a {@link CurrentState} holding the current {@link Trace}'s
* {@link State}
*/
public CurrentState currentStateProperty() {
return this.currentState;
}
/**
* Get the current {@link Trace}'s {@link State}.
*
* @return the current {@link Trace}'s {@link State}
*/
public State getCurrentState() {
return this.currentStateProperty().get();
}
/**
* A {@link CurrentStateSpace} holding the current {@link Trace}'s
* {@link StateSpace}.
*
* @return a {@link CurrentStateSpace} holding the current {@link Trace}'s
* {@link StateSpace}
*/
public CurrentStateSpace stateSpaceProperty() {
return this.stateSpace;
}
/**
* Get the current {@link Trace}'s {@link StateSpace}.
*
* @return the current {@link Trace}'s {@link StateSpace}
*/
public StateSpace getStateSpace() {
return this.stateSpaceProperty().get();
}
/**
* A {@link CurrentModel} holding the current {@link Trace}'s
* {@link AbstractModel}.
*
* @return a {@link CurrentModel} holding the current {@link Trace}'s
* {@link AbstractModel}
*/
public CurrentModel modelProperty() {
return this.model;
}
/**
* Get the current {@link Trace}'s {@link AbstractModel}.
*
* @return the current {@link Trace}'s {@link AbstractModel}
*/
public AbstractModel getModel() {
return this.modelProperty().get();
}
/**
* A read-only list property holding a read-only {@link ObservableList}
* version of the current {@link Trace}'s transition list.
*
* @return a read-only list property holding a read-only observable list
* version of the current {@link Trace}'s transition list
*/
public ReadOnlyListProperty<Transition> transitionListProperty() {
return this.transitionList;
}
/**
* Get the current {@link Trace}'s transition list as a read-only
* {@link ObservableList}.
*
* @return the current {@link Trace}'s transition list as a read-only
* {@link ObservableList}
*/
public ObservableList<Transition> getTransitionList() {
return this.transitionListProperty().get();
}
/**
* A read-only property indicating whether it is possible to go backward
* from the current trace.
*
* @return a read-only property indicating whether it is possible to go
* backward from the current trace
*/
public ReadOnlyBooleanProperty canGoBackProperty() {
return this.canGoBack;
}
/**
* Return whether it is possible to go backward from the current trace.
*
* @return whether it is possible to go backward from the current trace
*/
public boolean canGoBack() {
return this.canGoBackProperty().get();
}
/**
* A read-only property indicating whether it is possible to go forward from
* the current trace.
*
* @return a read-only property indicating whether it is possible to go
* forward from the current trace
*/
public ReadOnlyBooleanProperty canGoForwardProperty() {
return this.canGoForward;
}
/**
* Return whether it is possible to go forward from the current trace.
*
* @return whether it is possible to go forward from the current trace
*/
public boolean canGoForward() {
return this.canGoForwardProperty().get();
}
/**
* A read-only property holding the {@link Trace} that is one transition
* backward of the current one.
*
* @return a read-only property holding the {@link Trace} that is one
* transition backward of the current one
*/
public ReadOnlyObjectProperty<Trace> backProperty() {
return this.back;
}
/**
* Get the {@link Trace} that is one transition backward of the current one.
*
* @return the {@link Trace} that is one transition backward of the current
* one
*/
public Trace back() {
return this.backProperty().get();
}
/**
* A read-only property holding the {@link Trace} that is one transition
* forward of the current one.
*
* @return a read-only property holding the {@link Trace} that is one
* transition forward of the current one
*/
public ReadOnlyObjectProperty<Trace> forwardProperty() {
return this.forward;
}
/**
* Get the {@link Trace} that is one transition forward of the current one.
*
* @return the {@link Trace} that is one transition forward of the current
* one
*/
public Trace forward() {
return this.forwardProperty().get();
}
public void reload(final Trace trace, final Map<String, String> preferences) throws IOException, ModelTranslationError {
final String filename = trace.getModel().getModelFile().getAbsolutePath();
final Trace newTrace = new Trace(api.b_load(filename, preferences));
this.animationSelector.removeTrace(trace);
this.animationSelector.addNewAnimation(newTrace);
}
public void reload(final Trace trace) throws IOException, ModelTranslationError {
final GetCurrentPreferencesCommand cmd = new GetCurrentPreferencesCommand();
this.getStateSpace().execute(cmd);
this.reload(trace, cmd.getPreferences());
}
} |
package de.retest.recheck;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestCaseFinder {
private static final Logger logger = LoggerFactory.getLogger( TestCaseFinder.class );
private TestCaseFinder() {}
/*
* TODO We need a special implementation for data-driven testing with annotations such as JUnit's @Theory, because
* then a single method is invoked multiple times.
*/
private static final Set<String> testCaseAnnotations = new HashSet<>( Arrays.asList(
// JUnit Vintage (v4)
"org.junit.Test",
"org.junit.Before",
"org.junit.After",
"org.junit.BeforeClass",
"org.junit.AfterClass",
// JUnit Jupiter (v5)
"org.junit.jupiter.api.Test",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.AfterAll",
"org.junit.jupiter.params.ParameterizedTest",
// TestNG
"org.testng.annotations.Test",
"org.testng.annotations.BeforeMethod",
"org.testng.annotations.AfterMethod",
"org.testng.annotations.BeforeClass",
"org.testng.annotations.AfterClass" ) );
public static StackTraceElement findTestCaseMethodInStack() {
for ( final StackTraceElement[] stack : Thread.getAllStackTraces().values() ) {
final StackTraceElement testCaseStackElement = findTestCaseMethodInStack( stack );
if ( testCaseStackElement != null ) {
return testCaseStackElement;
}
}
return null;
}
public static StackTraceElement findTestCaseMethodInStack( final StackTraceElement[] trace ) {
boolean inTestCase = false;
for ( int i = 0; i < trace.length; i++ ) {
if ( isTestCase( trace[i] ) ) {
inTestCase = true;
} else if ( inTestCase ) {
return trace[i - 1];
}
}
return null;
}
private static boolean isTestCase( final StackTraceElement element ) {
final Method method = tryToFindMethodForStackTraceElement( element );
if ( method == null ) {
return false;
}
final Annotation[] annotations = method.getAnnotations();
for ( final Annotation annotation : annotations ) {
final String annotationName = annotation.annotationType().getName();
if ( testCaseAnnotations.contains( annotationName ) ) {
return true;
}
}
return false;
}
private static Method tryToFindMethodForStackTraceElement( final StackTraceElement element ) {
final Class<?> clazz;
Method method = null;
try {
clazz = Class.forName( element.getClassName() );
} catch ( final ClassNotFoundException e ) {
return null;
}
try {
for ( final Method methodCandidate : clazz.getDeclaredMethods() ) {
if ( methodCandidate.getName().equals( element.getMethodName() ) ) {
if ( method == null ) {
method = methodCandidate;
} else {
// two methods with same name found, can't determine correct one!
return null;
}
}
}
} catch ( final NoClassDefFoundError noClass ) {
logger.error( "Could not analyze method due to NoClassDefFoundError: ", noClass.getMessage() );
}
return method;
}
} |
package delta_service.web;
import SPARQLParser.SPARQL.InvalidSPARQLException;
import SPARQLParser.SPARQL.SPARQLQuery;
import com.fasterxml.jackson.databind.ObjectMapper;
import delta_service.config.Configuration;
import delta_service.query.QueryInfo;
import delta_service.query.QueryService;
import delta_service.query.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@RestController
public class RootController {
@Inject
private QueryService queryService;
private static final Logger log = LoggerFactory.getLogger(RootController.class);
/**
* initializes the callback service with 2 call back sets (allDifferences and effectiveDifferences)
*/
@PostConstruct
public void init()
{
}
/**
* Auto wired web entry point
*
* expects a body in the form
* {
* "callback":"<CALLBACKLOCATION>"
* }
*
* a Call Back object with this location is instantiated and added to the all differences set
* @param request
* @param response
* @param body
* @return
*/
@RequestMapping(value = "/registerForPotentialDifferences")
public ResponseEntity<String> registerAD(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) String body)
{
Map<String, Object> jsonMap;
try {
ObjectMapper mapper = new ObjectMapper();
jsonMap = mapper.readValue(body, Map.class);
String callbackString = (String)jsonMap.get("callback");
this.queryService.addCallBack("potentialDifferences", callbackString);
}
catch(IOException e)
{
e.printStackTrace();
}
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
/**
* Auto wired web entry point
*
* expects a body in the form
* {
* "callback":"<CALLBACKLOCATION>"
* }
*
* a Call Back object with this location is instantiated and added to the effective differences set
* @param request
* @param response
* @param body
* @return
*/
@RequestMapping(value = "/registerForEffectiveDifferences")
public ResponseEntity<String> registerED(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) String body)
{
Map<String, Object> jsonMap;
try {
ObjectMapper mapper = new ObjectMapper();
jsonMap = mapper.readValue(body, Map.class);
String callbackString = (String)jsonMap.get("callback");
this.queryService.addCallBack("effectiveDifferences", callbackString);
}
catch(IOException e)
{
e.printStackTrace();
}
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
/**
* TODO: Add more supported content types there is a problem with the text/turtle content-type
* TODO: for some reason the StringHttpMessageConverter barfs on it...
* @param request
* @param response
* @param body
* @return
* @throws InvalidSPARQLException
*/
@RequestMapping(value = "/sparql", produces = {"application/sparql-results+xml", "application/sparql-results+json", "text/html"})
public ResponseEntity<String> preProcessQuery(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) String body) throws InvalidSPARQLException
{
try {
/*
* Getting the query string,... somehow
*/
String queryString;
if (request.getParameterMap().containsKey("query")) {
queryString = request.getParameter("query");
try {
queryString = URLDecoder.decode(queryString, "UTF-8");
}catch(Exception e)
{
e.printStackTrace();
}
}
else
{
queryString = URLDecoder.decode(body, "UTF-8");
if(queryString.toLowerCase().startsWith("update="))
{
queryString = queryString.substring(7, queryString.length());
}
if(queryString.toLowerCase().startsWith("query="))
{
queryString = queryString.substring(6, queryString.length());
}
}
/*
* Getting the headers ... somehow
*/
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> henum = request.getHeaderNames();
while(henum.hasMoreElements())
{
String headerName = henum.nextElement();
headers.put(headerName, request.getHeader(headerName));
}
/*
* if UPDATE then ...
*/
SPARQLQuery.Type queryType = null;
try {
queryType = SPARQLQuery.extractType(queryString);
}catch(InvalidSPARQLException invalidSPARQLException)
{
invalidSPARQLException.printStackTrace();
}
if(queryType.equals(SPARQLQuery.Type.UPDATE)) {
/*
* Getting the parsed query object ... somehow
*/
SPARQLQuery parsedQuery = new SPARQLQuery(queryString);
// prepare the query object
QueryInfo queryInfo = new QueryInfo();
queryInfo.headers = headers;
queryInfo.endpoint = Configuration.updateEndpoint;
queryInfo.originalQuery = queryString;
queryInfo.query = parsedQuery;
// register it for processing
this.queryService.registerUpdateQuery(queryInfo);
// while it has not been process ... wait
while(this.queryService.getProcessedQueries().contains(queryInfo) == false)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// extract the response and remove all other info
String queryResponse = queryInfo.response.responseText;
this.queryService.getProcessedQueries().remove(queryInfo);
// setting the headers...
if(queryInfo.response.responseHeaders != null)
{
for(String header : queryInfo.response.responseHeaders.keySet())
{
response.setHeader(header, queryInfo.response.responseHeaders.get(header));
}
}
// and then return the result
return new ResponseEntity<String>(queryInfo.response.responseText, HttpStatus.OK);
}
/**
* If we are dealing with a SELECT query we can just return the response as is...
*/
if(!queryType.equals(SPARQLQuery.Type.UPDATE))
{
Response sparqlResponse = this.queryService.sparqlService.getSPARQLResponse(Configuration.queryEndpoint + "?query=" + URLEncoder.encode(queryString, "UTF-8"), headers);
String qrp = sparqlResponse.responseText;
for(String header:sparqlResponse.responseHeaders.keySet())
{
response.setHeader(header, sparqlResponse.responseHeaders.get(header));
}
return new ResponseEntity<String>(qrp, HttpStatus.OK);
}
}catch(InvalidSPARQLException e)
{
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok("");
}
} |
package edu.ucsf.mousedatabase;
import java.sql.*;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import edu.ucsf.mousedatabase.beans.MouseSubmission;
import edu.ucsf.mousedatabase.beans.UserData;
import edu.ucsf.mousedatabase.dataimport.ImportHandler;
import edu.ucsf.mousedatabase.dataimport.ImportHandler.ImportObjectType;
import edu.ucsf.mousedatabase.objects.*;
import edu.ucsf.mousedatabase.servlets.ReportServlet;
import org.apache.commons.lang3.StringUtils;
public class DBConnect {
//set this to true for debugging
private static final boolean logQueries = false;
private static final String mouseRecordTableColumns =
"mouse.id, name, mousetype, modification_type," +
"transgenictype.transgenictype,regulatory_element_comment as 'regulatory element',"
+"expressedsequence.expressedsequence, reporter_comment as 'reporter', strain, " +
"general_comment, source, mta_required, repository_id, repository.repository, " +
"repository_catalog_number,gensat,other_comment, gene.mgi as 'gene MGI', " +
"gene.symbol as 'gene symbol', gene.fullname as 'gene name',cryopreserved," +
"status,endangered,submittedmouse_id, targetgenes.mgi as 'target gene MGI'," +
"targetgenes.symbol as 'target gene symbol', targetgenes.fullname as 'target gene name', official_name\r\n";
private static final String mouseRecordTableJoins =
" left join mousetype on mouse.mousetype_id=mousetype.id\r\n"
+" left join gene on mouse.gene_id=gene.id\r\n"
+" left join gene as targetgenes on mouse.target_gene_id=targetgenes.id\r\n"
+" left join transgenictype on mouse.transgenictype_id=transgenictype.id\r\n"
+" left join expressedsequence on mouse.expressedsequence_id=expressedsequence.id\r\n"
+" left join repository on mouse.repository_id=repository.id\r\n ";
private static final String mouseRecordQueryHeader =
"SELECT " +
mouseRecordTableColumns
+" FROM mouse\r\n"
+ mouseRecordTableJoins;
private static final String mouseRecordQueryCountHeader =
"SELECT count(*) as count"
+" FROM mouse\r\n"
+ mouseRecordTableJoins;
private static final String mouseSubmissionQueryHeader =
"SELECT submittedmouse.* , mouse.id as mouseRecordID\r\n"
+ " FROM submittedmouse left join mouse on submittedmouse.id=mouse.submittedmouse_id\r\n ";
private static final String changeRequestQueryHeader =
"SELECT changerequest.*, mouse.name\r\n" +
" FROM changerequest left join mouse on changerequest.mouse_id=mouse.id\r\n ";
private static final String holderQueryHeader =
"SELECT holder.*, (select count(*) \r\n" +
" FROM mouse_holder_facility left join mouse on mouse_holder_facility.mouse_id=mouse.id\r\n" +
" WHERE holder_id=holder.id and covert=0 and mouse.status='live') as 'mice held'\r\n" +
" FROM holder\r\n ";
private static final String facilityQueryHeader =
"SELECT id, facility, description, code" +
", (select count(*) from mouse_holder_facility where facility_id=facility.id) as 'mice held'\r\n" +
" FROM facility\r\n ";
private static final String mouseHolderQueryHeader =
"SELECT holder_id, facility_id, covert, cryo_live_status, firstname, lastname, " +
"department, email, alternate_email, tel, facility" +
"\r\n FROM mouse_holder_facility t1 left join holder on t1.holder_id=holder.id " +
"left join facility on t1.facility_id=facility.id \r\n";
private static final String geneQueryHeader = "SELECT id,fullname,symbol,mgi \r\n FROM gene\r\n ";
private static final String mouseIDSearchTermsRegex = "^(
private static Connection connect() throws Exception
{
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/mouse_inventory");
return ds.getConnection();
}
catch (Exception e)
{
Log.Error("Problem connecting",e);
throw e;
}
}
/*Comparator<Sub> comparator = new Comparator<Sub>(){
public int compare(Sub a, Sub b)
{
return HTMLGeneration.emptyIfNull(a.PIName)
.compareTo(HTMLGeneration.emptyIfNull(b.PIName));
}
};
Collections.sort(linesByRecipientPI,comparator);
*/
for (Sub sub : linesByRecipientPI) {
//TODO why don't we want the PIName as well??
result.append(sub.Line);
}
return result.toString();
} |
package fr.minepod.bootstrap;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
public class CrashReport {
public static void SendReport(String exception, String when) {
try {
if(Config.Logger != null)
Config.Logger.severe(exception);
String debugMsg = "";
if(new File(Config.DebugFilePath).exists())
debugMsg = fr.minepod.Utils.Files.ReadFile(Config.DebugFilePath);
javax.swing.JOptionPane.showMessageDialog(null, exception + "\n" + Langage.WHEN.toString() + when + "\n\n\n" + Langage.DEBUGINFORMATIONS.toString() + ":\n\n" + debugMsg, Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
} catch (HeadlessException e) {
if(Config.Logger != null)
Config.Logger.severe(e.toString());
javax.swing.JOptionPane.showMessageDialog(null, e.toString(), Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
if(Config.Logger != null)
Config.Logger.severe(e.toString());
javax.swing.JOptionPane.showMessageDialog(null, e.toString(), Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
}
System.exit(0);
}
} |
package frc.team4215.stronghold;
import java.util.ArrayList;
import edu.wpi.first.wpilibj.I2C;
public class I2CAccel {
private static I2C accel;
private static final double coeff = .061;
private static boolean pingFlag;
private final static byte WHO_AM_I = 0x0F, CTRL_REG = 0x1F, OUT_REG = 0x28,
FIFO_SRC_REG = 0x2F;
private static final double G_IN_IPS2 = 386.09;
private static byte[] buffL = new byte[1], buffH = new byte[1],
ID = new byte[1];
private static double[] accelVal = new double[3];
private static double[] velocVal = new double[3];
private static double[] positVal = new double[3];
private static Thread pingerThread;
/**
* Should always size it as [x][3].
*/
protected static double[][] velocity;
protected static double[] position;
public static void initAccel() {
accel = new I2C(I2C.Port.kOnboard, 0x1D);
// Accelerometer
byte[] reg12 = new byte[1];
accel.read(0x12, 1, reg12);
accel.write(CTRL_REG + 1, 0x57); // 0x20
accel.write(CTRL_REG + 3, 0x00);// 4); //0x22
accel.write(CTRL_REG + 4, 0x00);// 4); //0x23
accel.write(CTRL_REG + 6, 0x00); // 0x25
accel.write(CTRL_REG + 7, 0x00); // 0x26
accel.read(WHO_AM_I, 1, ID);
}
public static void velInteg() {
accel.read(I2CAccel.FIFO_SRC_REG, 1, buffL);
final int loopCount = buffL[0] & 0x1f;
ArrayList<double[]> accelList = new ArrayList<double[]>();
for (int i = 0; i < loopCount; i++) {
pingAccel();
accelList.add(accelVal);
}
}
public static void distInteg() {
}
/**
* @param data
* Sized as [X][3]
* @param delt
* change of time between each two values
* @return
*/
private static double[] integrate(double[][] data, double delt) {
return null; // placeholder
}
/**
* @return a copy of accelVal.
*/
public static double[] pingAccel() {
accel.read(OUT_REG, 1, buffL);
accel.read(OUT_REG + 1, 1, buffH);
accelVal[0] = concatCorrect(buffH[0], buffL[0]);
accelVal[0] /= 1000;
accelVal[0] *= G_IN_IPS2;
accel.read(OUT_REG + 2, 1, buffL);
accel.read(OUT_REG + 3, 1, buffH);
accelVal[1] = concatCorrect(buffH[0], buffL[0]);
accelVal[1] /= 1000;
accelVal[1] *= G_IN_IPS2;
accel.read(OUT_REG + 4, 1, buffL);
accel.read(OUT_REG + 5, 1, buffH);
accelVal[2] = concatCorrect(buffH[0], buffL[0]);
accelVal[2] /= 1000;
accelVal[2] *= G_IN_IPS2;
RobotModule.logger.info("Accel: " + accelVal[1]);
return accelVal.clone();
}
public static double concatCorrect(byte h, byte l) {
int high = Byte.toUnsignedInt(h);
int low = Byte.toUnsignedInt(l);
int test = ((0xFF & high) << 8) + (0xFF & low);
test = ((test > 0x7FFF) ? test - 0xFFFF : test);
test *= coeff;
if (test > 65) return test;
else return 0;
}
public static void pingerStart() {
Runnable pinger = () -> {
while (pingFlag) {
pingAccel();
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
pingerThread = new Thread(pinger);
pingFlag = true;
pingerThread.start();
}
public static double[] getAccel() {
return accelVal;
}
public static void pingerStop() {
pingFlag = false;
}
} |
package io.bdrc.gittodbs;
import static io.bdrc.libraries.Models.getMd5;
import static io.bdrc.gittodbs.FusekiHelpers.printUsage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.jena.graph.Graph;
import org.apache.jena.ontology.DatatypeProperty;
import org.apache.jena.ontology.OntDocumentManager;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.ontology.Restriction;
import org.apache.jena.query.Dataset;
import org.apache.jena.rdf.model.InfModel;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.reasoner.Reasoner;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RDFParser;
import org.apache.jena.riot.RiotException;
import org.apache.jena.riot.system.StreamRDFLib;
import org.apache.jena.sparql.util.Context;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.apache.jena.vocabulary.OWL2;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.errors.InvalidObjectIdException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TransferHelpers {
public static final String RESOURCE_PREFIX = "http://purl.bdrc.io/resource/";
public static final String GRAPH_PREFIX = "http://purl.bdrc.io/graph/";
public static final String CORE_PREFIX = "http://purl.bdrc.io/ontology/core/";
public static final String CONTEXT_URL = "http://purl.bdrc.io/context.jsonld";
public static final String ADMIN_PREFIX = "http://purl.bdrc.io/ontology/admin/";
public static final String DATA_PREFIX = "http://purl.bdrc.io/data/";
public static final String ADMIN_DATA_PREFIX = "http://purl.bdrc.io/admindata/";
public static final String SKOS_PREFIX = "http://www.w3.org/2004/02/skos/core
public static final String VCARD_PREFIX = "http://www.w3.org/2006/vcard/ns
public static final String TBR_PREFIX = "http://purl.bdrc.io/ontology/toberemoved/";
public static final String OWL_PREFIX = "http://www.w3.org/2002/07/owl
public static final String RDF_PREFIX = "http://www.w3.org/1999/02/22-rdf-syntax-ns
public static final String RDFS_PREFIX = "http://www.w3.org/2000/01/rdf-schema
public static final String XSD_PREFIX = "http://www.w3.org/2001/XMLSchema
public static final String BDA = ADMIN_DATA_PREFIX;
public static final String BDG = GRAPH_PREFIX;
public static final String BDR = RESOURCE_PREFIX;
public static final String BDO = CORE_PREFIX;
public static final String ADM = ADMIN_PREFIX;
public static final Context ctx = new Context();
private static Map<String, DocType> strToDocType = new HashMap<>();
public enum DocType {
CORPORATION("corporation"),
ETEXT("etext"),
ETEXTCONTENT("etextcontent"),
ITEM("item"),
LINEAGE("lineage"),
OFFICE("office"),
PERSON("person"),
PLACE("place"),
PRODUCT("product"),
TOPIC("topic"),
WORK("work"),
TEST("test");
private String label;
private DocType(String label) {
this.label = label;
strToDocType.put(label, this);
}
public static DocType getType(String label) {
return strToDocType.get(label);
}
@Override
public String toString() {
return label;
}
}
public static void setPrefixes(Model m, DocType type) {
m.setNsPrefix("", CORE_PREFIX);
m.setNsPrefix("adm", ADMIN_PREFIX);
// m.setNsPrefix("bdd", DATA_PREFIX);
m.setNsPrefix("bdr", RESOURCE_PREFIX);
m.setNsPrefix("tbr", TBR_PREFIX);
//m.setNsPrefix("owl", OWL_PREFIX);
m.setNsPrefix("rdf", RDF_PREFIX);
m.setNsPrefix("rdfs", RDFS_PREFIX);
m.setNsPrefix("skos", SKOS_PREFIX);
m.setNsPrefix("xsd", XSD_PREFIX);
if (type == DocType.PLACE)
m.setNsPrefix("vcard", VCARD_PREFIX);
}
public static Logger logger = LoggerFactory.getLogger(TransferHelpers.class);
public static boolean progress = false;
public static long TRANSFER_TO = 50; // seconds
public static ExecutorService executor = Executors.newCachedThreadPool();
public static String adminNS = "http://purl.bdrc.io/ontology/admin/";
public static OntModel ontModel = null;
public static Reasoner bdrcReasoner = null;
public static void init() throws MalformedURLException {
if (GitToDB.transferFuseki) {
FusekiHelpers.init(GitToDB.fusekiHost, GitToDB.fusekiPort, GitToDB.fusekiName);
}
if (GitToDB.transferCouch) {
CouchHelpers.init(GitToDB.couchdbHost, GitToDB.couchdbPort, GitToDB.libFormat);
}
ontModel = getOntologyModel();
bdrcReasoner = BDRCReasoner.getReasoner(ontModel);
}
public static void sync(int howMany) {
int nbLeft = howMany;
nbLeft = nbLeft - syncType(DocType.PERSON, nbLeft);
nbLeft = nbLeft - syncType(DocType.ITEM, nbLeft);
nbLeft = nbLeft - syncType(DocType.WORK, nbLeft);
// nbLeft = nbLeft - syncType(DocType.ETEXT, nbLeft);
if (GitToDB.libFormat) {
closeConnections();
return;
}
nbLeft = nbLeft - syncType(DocType.CORPORATION, nbLeft);
nbLeft = nbLeft - syncType(DocType.PLACE, nbLeft);
nbLeft = nbLeft - syncType(DocType.TOPIC, nbLeft);
nbLeft = nbLeft - syncType(DocType.LINEAGE, nbLeft);
nbLeft = nbLeft - syncType(DocType.PRODUCT, nbLeft);
nbLeft = nbLeft - syncType(DocType.OFFICE, nbLeft);
nbLeft = nbLeft - syncType(DocType.ETEXTCONTENT, nbLeft);
closeConnections();
}
public static void closeConnections() {
if (GitToDB.transferFuseki)
FusekiHelpers.closeConnections();
}
public static int syncType(DocType type, int nbLeft) {
int i = 0;
// random result for uncoherent couch and fuseki
if (GitToDB.transferFuseki)
i = syncTypeFuseki(type, nbLeft);
if (GitToDB.transferCouch && type != DocType.ETEXTCONTENT)
i = syncTypeCouch(type, nbLeft);
return i;
}
public static Model modelFromPath(String path, DocType type, String mainId) {
if (type == DocType.ETEXTCONTENT) {
String bucket = getMd5(mainId);
String dirpath = GitToDB.gitDir + DocType.ETEXT + "s/"+bucket+"/";
boolean looking = bucket.compareTo("c3") > 0 && bucket.compareTo("d4") < 0;
if (looking) {
printUsage(">>>> modelFromPath USAGE for " + mainId + " BEFORE ETEXT modelFromPath ");
}
Model etextM = modelFromPath(dirpath+mainId+".trig", DocType.ETEXT, mainId);
if (looking) {
printUsage("|||| modelFromPath USAGE for " + mainId + " AFTER ETEXT modelFromPath ");
}
Model res = EtextContents.getModel(path, mainId, etextM);
if (looking) {
printUsage("<<<< modelFromPath USAGE for " + mainId + " AFTER ETEXTCONTENTS getModel ");
}
return res;
}
Model model = ModelFactory.createDefaultModel();
Graph g = model.getGraph();
if (path.endsWith(".ttl")) {
try {
RDFParser.create()
.source(path)
.lang(RDFLanguages.TTL)
.parse(StreamRDFLib.graph(g));
} catch (RiotException e) {
logger.error("error reading "+path);
return null;
}
} else if (path.endsWith(".trig")) {
try {
Dataset dataset = RDFDataMgr.loadDataset(path);
Iterator<String> iter = dataset.listNames();
if (iter.hasNext()) {
String graphUri = iter.next();
if (iter.hasNext())
logger.error("modelFromFileName " + path + " getting named model: " + graphUri + ". Has more graphs! ");
model = dataset.getNamedModel(graphUri);
}
} catch (RiotException e) {
logger.error("error reading "+path);
return null;
}
}
setPrefixes(model, type);
return model;
}
public static String mainIdFromPath(String path, DocType type) {
if (path == null || path.length() < 6)
return null;
if (type != DocType.ETEXTCONTENT && !(path.endsWith(".ttl") || path.endsWith(".trig")))
return null;
if (type == DocType.ETEXTCONTENT && !path.endsWith(".txt"))
return null;
if (path.charAt(2) == '/')
return path.substring(3, path.length()-(path.endsWith(".trig") ? 5 : 4));
return path.substring(0, path.length() - (path.endsWith(".trig") ? 5 : 4));
}
public static void addFileFuseki(DocType type, String dirPath, String filePath) {
final String mainId = mainIdFromPath(filePath, type);
if (mainId == null)
return;
Model m = modelFromPath(dirPath+filePath, type, mainId);
final String rev = GitHelpers.getLastRefOfFile(type, filePath); // not sure yet what to do with it
FusekiHelpers.setModelRevision(m, type, rev, mainId);
m = getInferredModel(m);
String graphName = BDG+mainId;
FusekiHelpers.transferModel(graphName, m);
}
public static void logFileHandling(int i, String path, boolean fuseki) {
TransferHelpers.logger.debug("sending "+path+" to "+(fuseki ? "Fuseki" : "Couchdb"));
if (i % 100 == 0 && progress)
logger.info(path + ":" + i);
}
public static int syncTypeFuseki(DocType type, int nbLeft) {
if (nbLeft == 0)
return 0;
String gitRev = GitHelpers.getHeadRev(type);
String dirpath = GitToDB.gitDir + type + "s/";
if (gitRev == null) {
TransferHelpers.logger.error("cannot extract latest revision from the git repo at "+dirpath);
return 0;
}
String distRev = FusekiHelpers.getLastRevision(type);
int i = 0;
if (distRev == null || distRev.isEmpty()) {
TreeWalk tw = GitHelpers.listRepositoryContents(type);
TransferHelpers.logger.info("sending all " + type + " files to Fuseki");
try {
while (tw.next()) {
if (i+1 > nbLeft)
return nbLeft;
i = i + 1;
logFileHandling(i, tw.getPathString(), true);
addFileFuseki(type, dirpath, tw.getPathString());
}
FusekiHelpers.finishDatasetTransfers();
} catch (IOException e) {
TransferHelpers.logger.error("", e);
return 0;
}
} else {
final List<DiffEntry> entries;
try {
entries = GitHelpers.getChanges(type, distRev);
} catch (InvalidObjectIdException | MissingObjectException e) {
TransferHelpers.logger.error("distant fuseki revision "+distRev+" is invalid, please fix it");
return 0;
}
TransferHelpers.logger.info("sending changed " + type + " files changed since "+distRev+" to Fuseki");
for (DiffEntry de : entries) {
if (i+1 > nbLeft)
return nbLeft;
i = i + 1;
final String path = de.getNewPath();
logFileHandling(i, path, true);
final String oldPath = de.getOldPath();
if (path.equals("/dev/null") || !path.equals(oldPath)) {
final String mainId = mainIdFromPath(oldPath, type);
if (mainId != null) {
FusekiHelpers.deleteModel(BDR+mainId);
}
}
if (!path.equals("/dev/null"))
addFileFuseki(type, dirpath, path);
}
}
FusekiHelpers.setLastRevision(gitRev, type);
return i;
}
public static void addFileCouch(final DocType type, final String dirPath, final String filePath) {
final String mainId = mainIdFromPath(filePath, type);
if (mainId == null)
return;
final Model m = modelFromPath(dirPath+filePath, type, mainId);
final long modelSize = m.size();
final String rev = GitHelpers.getLastRefOfFile(type, filePath); // not sure yet what to do with it
final Map<String,Object> jsonObject;
if (GitToDB.libFormat)
jsonObject = LibFormat.modelToJsonObject(m, type);
else
jsonObject = JSONLDFormatter.modelToJsonObject(m, type, mainId);
if (jsonObject == null)
return;
CouchHelpers.jsonObjectToCouch(jsonObject, mainId, type, rev, modelSize);
}
public static int syncTypeCouch(DocType type, int nbLeft) {
if (nbLeft == 0)
return 0;
final String gitRev = GitHelpers.getHeadRev(type);
final String dirpath = GitToDB.gitDir + type + "s/";
if (gitRev == null) {
TransferHelpers.logger.error("cannot extract latest revision from the git repo at "+dirpath);
return 0;
}
final String distRev = CouchHelpers.getLastRevision(type);
int i = 0;
if (distRev == null || distRev.isEmpty()) {
TransferHelpers.logger.info("sending all " + type + " files to Couch");
TreeWalk tw = GitHelpers.listRepositoryContents(type);
try {
while (tw.next()) {
if (i+1 > nbLeft)
return nbLeft;
i = i + 1;
logFileHandling(i, tw.getPathString(), true);
addFileCouch(type, dirpath, tw.getPathString());
}
} catch (IOException e) {
TransferHelpers.logger.error("", e);
return 0;
}
CouchHelpers.finishBulkTransfers();
} else {
final List<DiffEntry> entries;
try {
entries = GitHelpers.getChanges(type, distRev);
} catch (InvalidObjectIdException | MissingObjectException e1) {
TransferHelpers.logger.error("distant couch revision "+distRev+" is invalid, please fix it");
return 0;
}
TransferHelpers.logger.info("sending "+entries.size()+" " + type + " files changed since "+distRev+" to Couch");
for (DiffEntry de : entries) {
if (i+1 > nbLeft)
return nbLeft;
i = i + 1;
final String path = de.getNewPath();
logFileHandling(i, path, false);
final String oldPath = de.getOldPath();
if (path.equals("/dev/null") || !path.equals(oldPath)) {
final String mainId = mainIdFromPath(oldPath, type);
if (mainId != null) {
CouchHelpers.couchDelete(mainId, type);
}
}
if (!path.equals("/dev/null"))
addFileCouch(type, dirpath, path);
}
}
CouchHelpers.setLastRevision(gitRev, type);
return i;
}
public static String getFullUrlFromDocId(String docId) {
int colonIndex = docId.indexOf(":");
if (colonIndex < 0) return docId;
return RESOURCE_PREFIX+docId.substring(colonIndex+1);
}
public static InfModel getInferredModel(Model m) {
return ModelFactory.createInfModel(bdrcReasoner, m);
}
// for debugging purposes only
public static void printModel(Model m) {
RDFDataMgr.write(System.out, m, RDFFormat.TURTLE_PRETTY);
}
// change Range Datatypes from rdf:PlainLitteral to rdf:langString
public static void rdf10tordf11(OntModel o) {
Resource RDFPL = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral");
Resource RDFLS = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString");
ExtendedIterator<DatatypeProperty> it = o.listDatatypeProperties();
while(it.hasNext()) {
DatatypeProperty p = it.next();
if (p.hasRange(RDFPL)) {
p.removeRange(RDFPL);
p.addRange(RDFLS);
}
}
ExtendedIterator<Restriction> it2 = o.listRestrictions();
while(it2.hasNext()) {
Restriction r = it2.next();
Statement s = r.getProperty(OWL2.onDataRange); // is that code obvious? no
if (s != null && s.getObject().asResource().equals(RDFPL)) {
s.changeObject(RDFLS);
}
}
}
public static OntModel getOntologyModel() {
OntDocumentManager ontManager = new OntDocumentManager("owl-schema/ont-policy.rdf;https://raw.githubusercontent.com/buda-base/owl-schema/master/ont-policy.rdf");
ontManager.setProcessImports(true); // not really needed since ont-policy sets it, but what if someone changes the policy
OntModelSpec ontSpec = new OntModelSpec( OntModelSpec.OWL_DL_MEM );
ontSpec.setDocumentManager( ontManager );
OntModel ontModel = ontManager.getOntology( adminNS, ontSpec );
rdf10tordf11(ontModel);
logger.info("getOntologyModel ontModel.size() = " + ontModel.size());
return ontModel;
}
public static void transferOntology() {
logger.info("Transferring Ontology: " + CORE_PREFIX+"ontologySchema");
FusekiHelpers.transferModel(CORE_PREFIX+"ontologySchema", ontModel, true);
}
} |
package io.tokra.audio.wav;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.tokra.audio.wav.WavInfo.FMT;
import io.tokra.audio.wav.WavInfo.RIFF;
/**
* @author ToKra
*/
public class WavProcessing {
private static final Logger logger = LoggerFactory.getLogger(WavProcessing.class);
public static void saveInputStreamToWav(InputStream samples, String location) {
try {
/* File f = new File("C:/outFile.wav"); */
File f = new File(location);
f.createNewFile();
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[10000];
int len;
while ((len = samples.read(buf)) > 0){
out.write(buf, 0, len);
}
out.close();
logger.debug("\n\tWav File : '{}' ...was created", location);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @author Tomas Kramaric
* @since Feb 24, 2015
* @param wavFile
* @return
* @throws IOException
* @throws URISyntaxException
*/
public static WavInfo readWavFileSamples(File wavFile) throws IOException, URISyntaxException {
StopWatch sw = new StopWatch();
sw.start();
long length = getFileLenght(wavFile);
WavInfo wav = null;
RIFF riff = null;
FMT fmt = null;
ByteBuffer buf = ByteBuffer.allocate((int)length);
FileInputStream fis = new FileInputStream(wavFile);
FileChannel fileChannel = fis.getChannel();
while (fileChannel.read(buf) > 0) {
buf.flip();
while (buf.hasRemaining()) {
String headerChunkId = getText(buf, 4);
int headerChunkSize = getNumber(buf, 4);
logger.trace("Header_ChunkId: '{}', Header_ChunkSize: '{}'", headerChunkId, headerChunkSize);
switch (headerChunkId) {
case "RIFF":
riff = new RIFF(buf);
// logger.debug("{}", riff);
break;
case "fmt ":
fmt = WavInfo.FMT.getFmtChunk(buf);
// logger.debug("{}", fmt);
break;
case "data":
wav = processDataChunk(buf, headerChunkSize);
wav.setRiff(riff);
wav.setFmt(fmt);
logger.debug("{}", wav);
break;
default:
getNumber(buf, headerChunkSize);
break;
}
}
buf.clear();
}
fis.close();
sw.stop();
logger.info("ReadWavFileSamples... Runtime: '{}' ms", sw.getTime());
return wav;
}
/**
* @author Tomas Kramaric
* @since Feb 24, 2015
* @param buf
* @param headerChunkSize
* @return
* @throws IOException
*/
protected static WavInfo processDataChunk(ByteBuffer buf, int headerChunkSize) throws IOException {
StopWatch sw = new StopWatch();
sw.start();
short[] lowerBits = new short[headerChunkSize];
short[] upperBits = new short[headerChunkSize];
readBits(buf, lowerBits, upperBits);
short[] samples = decodePCM16bit(lowerBits, upperBits);
sw.stop();
logger.info("Processing Data Chunk... Runtime: '{}' ms", sw.getTime());
{ /* store results */
WavInfo wav = new WavInfo();
wav.setSamplesLowerBits(lowerBits);
wav.setSamplesUpperBits(upperBits);
wav.setDecodedSamples(samples);
return wav;
}
}
/**
*
* @author ToKra
* @since Feb 24, 2015
* @param file
* @return
* @throws IOException
*/
public static long getFileLenght(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
int length = is.available();
logger.debug("File path: '{}', Length: '{}'", file.getAbsolutePath(), length);
return length;
} finally {
is.close();
}
}
/**
*
* @author ToKra
* @since Feb 23, 2015
* @param byteBuffer
* @param arrayLength
* @return
* @throws IOException
*/
public static int getNumber(ByteBuffer byteBuffer, int arrayLength) throws IOException{
int number = 0;
for (int i = 0; i < arrayLength; i++) {
byte read = byteBuffer.get();
int readUnsigned = getUnsignedByte(read);
number += (int) (Math.pow(2, i * 8) * readUnsigned);
}
return number;
}
/**
*
* @author ToKra
* @since Feb 23, 2015
* @param byteBuffer
* @param arrayLenght
* @return
* @throws IOException
*/
public static String getText(ByteBuffer byteBuffer, int arrayLenght) throws IOException{
char[] array = new char[arrayLenght];
for (int i = 0; i < arrayLenght; i++){
char c = (char) byteBuffer.get();
array[i] = c;
}
return new String(array);
}
/**
*
* @author ToKra
* @since Feb 23, 2015
* @param param
* @return
*/
public static short getUnsignedByte(byte param) {
return (short) (param & 0xFF);
}
/**
*
* @author ToKra
* @since Feb 23, 2015
* @param byteBuffer
* @param lowerBits
* @param upperBits
* @throws IOException
*/
public static void readBits(ByteBuffer byteBuffer, short[] lowerBits, short[] upperBits) throws IOException {
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < lowerBits.length; i++) {
if(byteBuffer.hasRemaining()){
byte readLower = byteBuffer.get();
byte readUpper = byteBuffer.get();
short readLowerUnsigned = getUnsignedByte(readLower);
short readUpperUnsigned = getUnsignedByte(readUpper);
lowerBits[i] = readLowerUnsigned;
upperBits[i] = readUpperUnsigned;
} else {
break;
}
}
logger.trace("Read LowerBits: '{}', Read UpperBits: '{}'", lowerBits.length, upperBits.length);
sw.stop();
logger.debug("Reading data bits... Runtime: '{}' ms", sw.getTime());
}
/**
* Decodes PCM data to samples
*
* @author ToKra
* @since Feb 23, 2015
* @param lower
* @param upper
* @return
*/
public static short[] decodePCM16bit(short[] lower, short[] upper){
StopWatch sw = new StopWatch();
sw.start();
short[] samples = new short[lower.length];
for(int i = 0; i < lower.length; i++){
short sampleLittle = (short) ((lower[i] & 0xFF) | (upper[i] << 8)); //http://www.jsresources.org/faq_audio.html#reconstruct_samples
samples[i] = sampleLittle;
// logger.trace("Sample: '{}', Value: '{}'", i, sampleLittle);
}
sw.stop();
logger.debug("Decode PCM... Runtime: '{}' ms", sw.getTime());
return samples;
}
/**
* @author Tomas Kramaric
* @lastModified 12.5.2014 | refactor
* @param foldedVoiceSamples
* @return {@link ByteArrayOutputStream} wav representation
*/
public static ByteArrayOutputStream createWavFromAudioSamples(List<Short> foldedVoiceSamples) {
int wavSize = foldedVoiceSamples.size() * 2 + 36;
int dataSize = foldedVoiceSamples.size() * 2;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
logger.info("Creating WAV header");
dos.write("RIFF".getBytes()); // chunk ID
dos.writeInt(intLittleEndian(wavSize)); // velkost wavka -8
dos.write("WAVE".getBytes()); // RIFF typ
dos.write("fmt ".getBytes()); // subchunk ID
dos.writeInt(intLittleEndian(16)); // velkost fmt chunku
dos.writeShort(shortLittleEndian(1)); // audio format
dos.writeShort(shortLittleEndian(1)); // pocet kanalov
dos.writeInt(intLittleEndian(16000)); // sample rate
dos.writeInt(intLittleEndian(32000)); // byte rate
dos.writeShort(shortLittleEndian(2)); // wave blok zarovnanie
dos.writeShort(shortLittleEndian(16)); // bit/sakunda
dos.write("data".getBytes()); // subchunk2 ID
dos.writeInt(intLittleEndian(dataSize)); // dlzka datovej casti
logger.info("Creating WAV content");
for(Short sample : foldedVoiceSamples){
dos.writeShort(shortLittleEndian(sample.shortValue()));
}
dos.flush();
} catch (IOException e) {
logger.info("Could not create WAV content");
}
return baos;
}
public static InputStream getWavInputStreamFromAudioSamples(List<Short> foldedVoiceSamples) {
ByteArrayOutputStream baos = WavProcessing.createWavFromAudioSamples(foldedVoiceSamples);
if (baos != null) {
return new ByteArrayInputStream(baos.toByteArray());
}
return null;
}
protected static final int intLittleEndian(int v) {
return (v >>> 24) | (v << 24) | ((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
}
protected static final int shortLittleEndian(int v) {
return ((v >>> 8) & 0x00FF) | ((v << 8) & 0xFF00);
}
} |
package io.webfolder.cdp.command;
import io.webfolder.cdp.annotation.Domain;
import io.webfolder.cdp.annotation.Experimental;
import io.webfolder.cdp.annotation.Optional;
import io.webfolder.cdp.annotation.Returns;
import io.webfolder.cdp.type.network.ConnectionType;
import io.webfolder.cdp.type.network.Cookie;
import io.webfolder.cdp.type.network.CookieSameSite;
import io.webfolder.cdp.type.network.ErrorReason;
import io.webfolder.cdp.type.network.GetResponseBodyResult;
import java.util.List;
import java.util.Map;
/**
* Network domain allows tracking network activities of the page
* It exposes information about http, file, data and other requests and responses, their headers, bodies, timing, etc
*/
@Domain("Network")
public interface Network {
/**
* Enables network tracking, network events will now be delivered to the client.
*
* @param maxTotalBufferSize Buffer size in bytes to use when preserving network payloads (XHRs, etc).
* @param maxResourceBufferSize Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc).
*/
void enable(@Experimental @Optional Integer maxTotalBufferSize,
@Experimental @Optional Integer maxResourceBufferSize);
/**
* Disables network tracking, prevents network events from being sent to the client.
*/
void disable();
/**
* Allows overriding user agent with the given string.
*
* @param userAgent User agent to use.
*/
void setUserAgentOverride(String userAgent);
/**
* Specifies whether to always send extra HTTP headers with the requests from this page.
*
* @param headers Map with extra HTTP headers.
*/
void setExtraHTTPHeaders(Map<String, Object> headers);
/**
* Returns content served for the given request.
*
* @param requestId Identifier of the network request to get content for.
*
* @return GetResponseBodyResult
*/
GetResponseBodyResult getResponseBody(String requestId);
/**
* Blocks URLs from loading.
*
* @param urls URL patterns to block. Wildcards ('*') are allowed.
*/
@Experimental
void setBlockedURLs(List<String> urls);
/**
* This method sends a new XMLHttpRequest which is identical to the original one. The following parameters should be identical: method, url, async, request body, extra headers, withCredentials attribute, user, password.
*
* @param requestId Identifier of XHR to replay.
*/
@Experimental
void replayXHR(String requestId);
/**
* Tells whether clearing browser cache is supported.
*
* @return True if browser cache can be cleared.
*/
@Returns("result")
Boolean canClearBrowserCache();
/**
* Clears browser cache.
*/
void clearBrowserCache();
/**
* Tells whether clearing browser cookies is supported.
*
* @return True if browser cookies can be cleared.
*/
@Returns("result")
Boolean canClearBrowserCookies();
/**
* Clears browser cookies.
*/
void clearBrowserCookies();
/**
* Returns all browser cookies for the current URL. Depending on the backend support, will return detailed cookie information in the <tt>cookies</tt> field.
*
* @param urls The list of URLs for which applicable cookies will be fetched
*
* @return Array of cookie objects.
*/
@Experimental
@Returns("cookies")
List<Cookie> getCookies(@Optional List<String> urls);
/**
* Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the <tt>cookies</tt> field.
*
* @return Array of cookie objects.
*/
@Experimental
@Returns("cookies")
List<Cookie> getAllCookies();
/**
* Deletes browser cookie with given name, domain and path.
*
* @param cookieName Name of the cookie to remove.
* @param url URL to match cooke domain and path.
*/
@Experimental
void deleteCookie(String cookieName, String url);
/**
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @param url The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie.
* @param name The name of the cookie.
* @param value The value of the cookie.
* @param domain If omitted, the cookie becomes a host-only cookie.
* @param path Defaults to the path portion of the url parameter.
* @param secure Defaults ot false.
* @param httpOnly Defaults to false.
* @param sameSite Defaults to browser default behavior.
* @param expirationDate If omitted, the cookie becomes a session cookie.
*
* @return True if successfully set cookie.
*/
@Experimental
@Returns("success")
Boolean setCookie(String url, String name, String value, @Optional String domain,
@Optional String path, @Optional Boolean secure, @Optional Boolean httpOnly,
@Optional CookieSameSite sameSite, @Optional Double expirationDate);
/**
* Tells whether emulation of network conditions is supported.
*
* @return True if emulation of network conditions is supported.
*/
@Experimental
@Returns("result")
Boolean canEmulateNetworkConditions();
/**
* Activates emulation of network conditions.
*
* @param offline True to emulate internet disconnection.
* @param latency Additional latency (ms).
* @param downloadThroughput Maximal aggregated download throughput.
* @param uploadThroughput Maximal aggregated upload throughput.
* @param connectionType Connection type if known.
*/
void emulateNetworkConditions(Boolean offline, Double latency, Double downloadThroughput,
Double uploadThroughput, @Optional ConnectionType connectionType);
/**
* Toggles ignoring cache for each request. If <tt>true</tt>, cache will not be used.
*
* @param cacheDisabled Cache disabled state.
*/
void setCacheDisabled(Boolean cacheDisabled);
/**
* Toggles ignoring of service worker for each request.
*
* @param bypass Bypass service worker and load from network.
*/
@Experimental
void setBypassServiceWorker(Boolean bypass);
/**
* For testing.
*
* @param maxTotalSize Maximum total buffer size.
* @param maxResourceSize Maximum per-resource size.
*/
@Experimental
void setDataSizeLimitsForTest(Integer maxTotalSize, Integer maxResourceSize);
/**
* Returns the DER-encoded certificate.
*
* @param origin Origin to get certificate for.
*/
@Experimental
@Returns("tableNames")
List<String> getCertificate(String origin);
@Experimental
void setRequestInterceptionEnabled(Boolean enabled);
/**
* Response to Network.requestIntercepted which either modifies the request to continue with any modifications, or blocks it, or completes it with the provided response bytes. If a network fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted event will be sent with the same InterceptionId.
*
* @param errorReason If set this causes the request to fail with the given reason.
* @param rawResponse If set the requests completes using with the provided base64 encoded raw response, including HTTP status line and headers etc...
* @param url If set the request url will be modified in a way that's not observable by page.
* @param method If set this allows the request method to be overridden.
* @param postData If set this allows postData to be set.
* @param headers If set this allows the request headers to be changed.
*/
@Experimental
void continueInterceptedRequest(String interceptionId, @Optional ErrorReason errorReason,
@Optional String rawResponse, @Optional String url, @Optional String method,
@Optional String postData, @Optional Map<String, Object> headers);
/**
* Enables network tracking, network events will now be delivered to the client.
*/
void enable();
/**
* Returns all browser cookies for the current URL. Depending on the backend support, will return detailed cookie information in the <tt>cookies</tt> field.
*
* @return Array of cookie objects.
*/
@Experimental
@Returns("cookies")
List<Cookie> getCookies();
/**
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @param url The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie.
* @param name The name of the cookie.
* @param value The value of the cookie.
*
* @return True if successfully set cookie.
*/
@Experimental
@Returns("success")
Boolean setCookie(String url, String name, String value);
/**
* Activates emulation of network conditions.
*
* @param offline True to emulate internet disconnection.
* @param latency Additional latency (ms).
* @param downloadThroughput Maximal aggregated download throughput.
* @param uploadThroughput Maximal aggregated upload throughput.
*/
void emulateNetworkConditions(Boolean offline, Double latency, Double downloadThroughput,
Double uploadThroughput);
/**
* Response to Network.requestIntercepted which either modifies the request to continue with any modifications, or blocks it, or completes it with the provided response bytes. If a network fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted event will be sent with the same InterceptionId.
*
*/
@Experimental
void continueInterceptedRequest(String interceptionId);
} |
package lee.study.down.util;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lee.study.down.HttpDownServer;
import lee.study.down.dispatch.HttpDownCallback;
import lee.study.down.hanndle.HttpDownInitializer;
import lee.study.down.model.ChunkInfo;
import lee.study.down.model.HttpDownInfo;
import lee.study.down.model.HttpRequestInfo;
import lee.study.down.model.TaskInfo;
import lee.study.proxyee.server.HttpProxyServer;
import lee.study.proxyee.util.ProtoUtil;
import lee.study.proxyee.util.ProtoUtil.RequestProto;
public class HttpDownUtil {
public static boolean checkHeadKey(HttpHeaders httpHeaders, String regex) {
for (Entry<String, String> entry : httpHeaders) {
if (entry.getKey().matches(regex)) {
return true;
}
}
return false;
}
/**
* url
*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
return checkHead(httpRequest, HttpHeaderNames.HOST, regex);
}
/**
* Referer
*/
public static boolean checkReferer(HttpRequest httpRequest, String regex) {
return checkHead(httpRequest, HttpHeaderNames.REFERER, regex);
}
/**
* http
*/
public static boolean checkHead(HttpRequest httpRequest, CharSequence headName, String regex) {
String host = httpRequest.headers().get(headName);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
url = host + httpRequest.uri();
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest,
HttpResponse httpResponse, Channel clientChannel) {
HttpHeaders httpHeaders = httpResponse.headers();
HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo,
HttpRequestInfo.adapter(httpRequest));
HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo);
httpHeaders.clear();
httpResponse.setStatus(HttpResponseStatus.OK);
httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html");
String js =
"<script>window.top.location.href='http://localhost:" + HttpDownServer.VIEW_SERVER_PORT
+ "/#/newTask/" + httpDownInfo
.getTaskInfo().getId()
+ "';</script>";
HttpContent content = new DefaultLastHttpContent();
content.content().writeBytes(js.getBytes());
httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length);
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(content);
clientChannel.close();
}
public static TaskInfo getTaskInfo(HttpRequest httpRequest, HttpHeaders resHeaders,
NioEventLoopGroup loopGroup) {
TaskInfo taskInfo = new TaskInfo(
UUID.randomUUID().toString(), "", getDownFileName(httpRequest, resHeaders), 1,
getDownFileSize(resHeaders), false, 0, 0, 0, 0, null, null);
//chunked
if (resHeaders.contains(HttpHeaderNames.CONTENT_LENGTH)) {
CountDownLatch cdl = new CountDownLatch(1);
try {
final ProtoUtil.RequestProto requestProto = ProtoUtil.getRequestProto(httpRequest);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(loopGroup)
.channel(NioSocketChannel.class) // NioSocketChannelchannel
.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
if (requestProto.getSsl()) {
ch.pipeline().addLast(HttpProxyServer.clientSslCtx.newHandler(ch.alloc()));
}
ch.pipeline().addLast("httpCodec", new HttpClientCodec());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx0, Object msg0)
throws Exception {
if (msg0 instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse) msg0;
//206
if (httpResponse.status().equals(HttpResponseStatus.PARTIAL_CONTENT)) {
taskInfo.setSupportRange(true);
}
cdl.countDown();
} else if (msg0 instanceof DefaultLastHttpContent) {
ctx0.channel().close();
}
}
});
}
});
ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort()).sync();
httpRequest.headers().set(HttpHeaderNames.RANGE, "bytes=0-0");
cf.channel().writeAndFlush(httpRequest);
cdl.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return taskInfo;
}
public static String getDownFileName(HttpRequest httpRequest, HttpHeaders resHeaders) {
String fileName = null;
String disposition = resHeaders.get(HttpHeaderNames.CONTENT_DISPOSITION);
if (disposition != null) {
//attachment;filename=1.rar attachment;filename=*UTF-8''1.rar
Pattern pattern = Pattern.compile("^.*filename\\*?=\"?(?:.*'')?([^\"]*)\"?$");
Matcher matcher = pattern.matcher(disposition);
if (matcher.find()) {
char[] chs = matcher.group(1).toCharArray();
byte[] bts = new byte[chs.length];
//nettybytechar HttpObjectDecoder(:803)
for (int i = 0; i < chs.length; i++) {
bts[i] = (byte) chs[i];
}
try {
fileName = new String(bts, "UTF-8");
fileName = URLDecoder.decode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
fileName = null;
}
}
}
if (fileName == null) {
Pattern pattern = Pattern.compile("^.*/([^/]*)$");
Matcher matcher = pattern.matcher(httpRequest.uri());
if (matcher.find()) {
fileName = matcher.group(1);
}
}
return fileName == null ? ".xxx" : fileName;
}
public static long getDownFileSize(HttpHeaders resHeaders) {
String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
if (contentLength != null) {
return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
} else {
return -1;
}
}
public static void taskDown(HttpDownInfo httpDownInfo, HttpDownCallback callback)
throws Exception {
TaskInfo taskInfo = httpDownInfo.getTaskInfo();
taskInfo.setCallback(callback);
RequestProto requestProto = ProtoUtil.getRequestProto(httpDownInfo.getRequest());
File file = new File(taskInfo.getFilePath() + File.separator + taskInfo.getFileName());
if (file.exists()) {
file.delete();
}
try (
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")
) {
randomAccessFile.setLength(taskInfo.getTotalSize());
taskInfo.setStatus(1);
taskInfo.setStartTime(System.currentTimeMillis());
callback.start(taskInfo);
for (int i = 0; i < taskInfo.getChunkInfoList().size(); i++) {
chunkDown(httpDownInfo, taskInfo.getChunkInfoList().get(i), requestProto);
/*ChunkInfo chunkInfo = taskInfo.getChunkInfoList().get(i);
ChannelFuture cf = HttpDownServer.DOWN_BOOT
.handler(
new HttpDownInitializer(requestProto.getSsl(), taskInfo, chunkInfo, callback))
.connect(requestProto.getHost(), requestProto.getPort());
//
chunkInfo.setStatus(1);
chunkInfo.setStartTime(System.currentTimeMillis());
callback.chunkStart(taskInfo, chunkInfo);
cf.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
httpDownInfo.getRequest().headers()
.set(HttpHeaderNames.RANGE,
"bytes=" + chunkInfo.getStartPosition() + "-" + chunkInfo.getEndPosition());
future.channel().writeAndFlush(httpDownInfo.getRequest());
}
});*/
}
} catch (Exception e) {
throw e;
}
}
public static void chunkDown(HttpDownInfo httpDownInfo, ChunkInfo chunkInfo,
RequestProto requestProto)
throws Exception {
TaskInfo taskInfo = httpDownInfo.getTaskInfo();
HttpDownCallback callback = taskInfo.getCallback();
ChannelFuture cf = HttpDownServer.DOWN_BOOT
.handler(
new HttpDownInitializer(requestProto.getSsl(), taskInfo, chunkInfo, callback))
.connect(requestProto.getHost(), requestProto.getPort());
cf.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
httpDownInfo.getRequest().headers()
.set(HttpHeaderNames.RANGE,
"bytes=" + chunkInfo.getNowStartPosition() + "-" + chunkInfo.getEndPosition());
future.channel().writeAndFlush(httpDownInfo.getRequest());
} else {
//30s
TimeUnit.SECONDS.sleep(30);
retryDown(taskInfo, chunkInfo);
}
});
}
public static void retryDown(TaskInfo taskInfo, ChunkInfo chunkInfo)
throws Exception {
safeClose(chunkInfo.getChannel(), chunkInfo.getFileChannel());
chunkInfo.setNowStartPosition(chunkInfo.getOriStartPosition() + chunkInfo.getDownSize());
HttpDownInfo httpDownInfo = HttpDownServer.DOWN_CONTENT.get(taskInfo.getId());
RequestProto requestProto = ProtoUtil
.getRequestProto(httpDownInfo.getRequest());
chunkDown(httpDownInfo, chunkInfo, requestProto);
}
public static void safeClose(Channel channel, FileChannel fileChannel) {
try {
if (channel != null && channel.isOpen()) {
channel.close();
}
if (fileChannel != null && fileChannel.isOpen()) {
fileChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void serialize(Serializable object, String path) throws IOException {
try (
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path))
) {
outputStream.writeObject(object);
}
}
public static Object deserialize(String path) throws IOException, ClassNotFoundException {
try (
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))
) {
return ois.readObject();
}
}
} |
package libshapedraw.internal;
import java.util.LinkedHashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import libshapedraw.ApiInfo;
import libshapedraw.LibShapeDraw;
import libshapedraw.MinecraftAccess;
import libshapedraw.animation.trident.TridentConfig;
import libshapedraw.event.LSDEventListener;
import libshapedraw.event.LSDGameTickEvent;
import libshapedraw.event.LSDPreRenderEvent;
import libshapedraw.event.LSDRespawnEvent;
import libshapedraw.internal.Util.FileLogger;
import libshapedraw.internal.Util.NullLogger;
import libshapedraw.primitive.ReadonlyVector3;
import libshapedraw.shape.Shape;
import org.lwjgl.opengl.GL11;
/**
* Internal singleton controller class, lazily instantiated.
* Relies on a bootstrapper (mod_LibShapeDraw) to feed it Minecraft game events.
*/
public class Controller {
private static Controller instance;
private final Logger log;
private final LinkedHashSet<LibShapeDraw> apiInstances;
private int topApiInstanceId;
private MinecraftAccess minecraftAccess;
private boolean initialized;
private long lastDump;
private Controller() {
if (GlobalSettings.isLoggingEnabled()) {
log = new FileLogger(ModDirectory.DIRECTORY, ApiInfo.getName(), GlobalSettings.isLoggingAppend());
} else {
log = new NullLogger();
}
apiInstances = new LinkedHashSet<LibShapeDraw>();
topApiInstanceId = 0;
TridentConfig trident = TridentConfig.getInstance();
trident.addPropertyInterpolator(new ReadonlyColorPropertyInterpolator());
trident.addPropertyInterpolator(new ReadonlyVector3PropertyInterpolator());
trident.addPropertyInterpolator(new ReadonlyLineStylePropertyInterpolator());
log.info(ApiInfo.getName() + " v" + ApiInfo.getVersion() + " by " + ApiInfo.getAuthors());
log.info(ApiInfo.getUrl());
log.info(getClass().getName() + " instantiated");
}
public static Controller getInstance() {
if (instance == null) {
instance = new Controller();
}
return instance;
}
public static Logger getLog() {
return getInstance().log;
}
public static MinecraftAccess getMinecraftAccess() {
return getInstance().minecraftAccess;
}
/**
* @return true if the bootstrapper has been instantiated and is linked up to the controller
*/
public static boolean isInitialized() {
return getInstance().initialized;
}
/**
* Called by the bootstrapper.
*/
public void initialize(MinecraftAccess minecraftAccess) {
if (isInitialized()) {
throw new IllegalStateException("multiple initializations of controller");
}
this.minecraftAccess = minecraftAccess;
initialized = true;
log.info(getClass().getName() + " initialized");
}
/**
* Called by LibShapeDraw's constructor.
*/
public String registerApiInstance(LibShapeDraw apiInstance, String ownerId) {
if (apiInstances.contains(apiInstance)) {
throw new IllegalStateException("already registered");
}
topApiInstanceId++;
String apiInstanceId = apiInstance.getClass().getSimpleName() + "#" + topApiInstanceId + ":" + ownerId;
apiInstances.add(apiInstance);
log.info("registered API instance " + apiInstanceId);
return apiInstanceId;
}
/**
* Called by LibShapeDraw.unregister.
*/
public boolean unregisterApiInstance(LibShapeDraw apiInstance) {
boolean result = apiInstances.remove(apiInstance);
if (result) {
log.info("unregistered API instance " + apiInstance.getInstanceId());
}
return result;
}
/**
* Called by the bootstrapper.
* Dispatch the respawn event.
*/
public void respawn(ReadonlyVector3 playerCoords, boolean isNewServer, boolean isNewDimension) {
log.finer("respawn");
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDRespawnEvent event = new LSDRespawnEvent(apiInstance, playerCoords, isNewServer, isNewDimension);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
listener.onRespawn(event);
}
}
}
}
/**
* Called by the bootstrapper.
* Periodically dump API state to log if configured to do so.
* Dispatch gameTick events.
*/
public void gameTick(ReadonlyVector3 playerCoords) {
log.finer("gameTick");
if (GlobalSettings.getLoggingDebugDumpInterval() > 0) {
long now = System.currentTimeMillis();
if (now > lastDump + GlobalSettings.getLoggingDebugDumpInterval()) {
dump();
lastDump = now;
}
}
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDGameTickEvent event = new LSDGameTickEvent(apiInstance, playerCoords);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onGameTick(event);
}
}
}
}
}
/**
* Called by the bootstrapper.
* Dispatch preRender events.
* Render all registered shapes.
*/
public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) {
log.finer("render");
int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC);
GL11.glPushMatrix();
GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ());
for (LibShapeDraw apiInstance : apiInstances) {
if (!apiInstance.getEventListeners().isEmpty()) {
LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden);
for (LSDEventListener listener : apiInstance.getEventListeners()) {
if (listener != null) {
listener.onPreRender(event);
}
}
}
if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) {
for (Shape shape : apiInstance.getShapes()) {
if (shape != null) {
shape.render(minecraftAccess);
}
}
}
}
GL11.glPopMatrix();
GL11.glDepthMask(true);
GL11.glDepthFunc(origDepthFunc);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
/**
* Log all the things.
*/
public boolean dump() {
if (!log.isLoggable(Level.INFO)) {
return false;
}
final String INDENT = " ";
StringBuilder line = new StringBuilder().append(this).append(":\n");
for (LibShapeDraw apiInstance : apiInstances) {
line.append(INDENT).append(apiInstance).append(":\n");
line.append(INDENT).append(INDENT).append("visible=");
line.append(apiInstance.isVisible()).append('\n');
line.append(INDENT).append(INDENT).append("visibleWhenHidingGui=");
line.append(apiInstance.isVisibleWhenHidingGui()).append('\n');
line.append(INDENT).append(INDENT).append("shapes=");
line.append(apiInstance.getShapes().size()).append(":\n");
for (Shape shape : apiInstance.getShapes()) {
line.append(INDENT).append(INDENT).append(INDENT).append(shape).append('\n');
}
line.append(INDENT).append(INDENT).append("eventListeners=");
line.append(apiInstance.getEventListeners().size()).append(":\n");
for (LSDEventListener listener : apiInstance.getEventListeners()) {
line.append(INDENT).append(INDENT).append(INDENT).append(listener).append('\n');
}
}
log.info(line.toString());
return true;
}
} |
package net.imagej.ops.topology;
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import net.imagej.ops.Ops;
import net.imagej.ops.special.function.AbstractUnaryFunctionOp;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.roi.labeling.BoundingBox;
import net.imglib2.type.BooleanType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.util.ValuePair;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* An N-dimensional box counting that can be used to estimate the fractal
* dimension of an interval
* <p>
* The algorithm repeatedly lays a fixed grid on the interval, and counts the
* number of sections that contain foreground. After each step the grid is made
* finer by a factor of {@link #scaling}. If the objects in the interval are
* fractal, the proportion of foreground sections should increase as the grid
* gets finer.
* </p>
* <p>
* Produces a set of points (log(foreground count), -log(section size)) for
* curve fitting. The slope of the function gives the fractal dimension of the
* interval.
* </p>
*
* @author Richard Domander (Royal Veterinary College, London)
* @author Per Christian Henden
* @author Jens Bache-Wiig
*/
@Plugin(type = Ops.Topology.BoxCount.class)
public class BoxCount<B extends BooleanType<B>> extends
AbstractUnaryFunctionOp<RandomAccessibleInterval<B>, List<ValuePair<DoubleType, DoubleType>>>
implements Ops.Topology.BoxCount
{
/** Starting size of the grid sections in pixels */
@Parameter(required = false, persist = false)
private Long maxSize = 48L;
/** Minimum size of the grid sections in pixels */
@Parameter(required = false, persist = false)
private Long minSize = 6L;
/** Grid downscaling factor */
@Parameter(required = false, persist = false)
private Double scaling = 1.2;
/**
* Number of times the grid is moved in each dimension to find the best fit
* <p>
* The best fitting grid covers the objects in the interval with the least
* amount of sections.
* </p>
* <p>
* NB Additional moves multiply algorithm's time complexity by n^d!
* </p>
*/
@Parameter(required = false, persist = false)
private Long gridMoves = 0L;
/**
* Counts the number of foreground sections in the interval repeatedly with
* different size sections
*
* @param input an n-dimensional binary interval
* @return A list of (log(foreground count), -log(section size))
* {@link ValuePair} objects for curve fitting
*/
@Override
public List<ValuePair<DoubleType, DoubleType>> calculate(
final RandomAccessibleInterval<B> input)
{
final List<ValuePair<DoubleType, DoubleType>> points = new ArrayList<>();
final int dimensions = input.numDimensions();
final long[] sizes = new long[dimensions];
final long numTranslations = 1 + gridMoves;
input.dimensions(sizes);
for (long sectionSize = maxSize; sectionSize >= minSize; sectionSize /=
scaling)
{
final long translationAmount = Math.max(1, sectionSize / numTranslations);
final Stream<long[]> translations = translationStream(numTranslations,
translationAmount, dimensions - 1, new long[dimensions]);
final LongStream foregroundCounts = countTranslatedGrids(input,
translations, sizes, sectionSize);
final long foreground = foregroundCounts.min().orElse(0);
final double logSize = -Math.log(sectionSize);
final double logCount = Math.log(foreground);
final ValuePair<DoubleType, DoubleType> point = new ValuePair<>(
new DoubleType(logSize), new DoubleType(logCount));
points.add(point);
}
return points;
}
/**
* Count foreground sections in all grids created from the translations
*
* @param input N-dimensional binary interval
* @param translations Stream of translation coordinates in n-dimensions
* @param sizes Sizes of the interval's dimensions in pixels
* @param sectionSize Size of a section in the grids
* @return Foreground sections counted in each grid
*/
private static <B extends BooleanType<B>> LongStream countTranslatedGrids(
final RandomAccessibleInterval<B> input, final Stream<long[]> translations,
final long[] sizes, final long sectionSize)
{
final int lastDimension = sizes.length - 1;
return translations.parallel().mapToLong(gridOffset -> {
final LongType foreground = new LongType();
final long[] sectionPosition = new long[sizes.length];
countGrid(input, lastDimension, sizes, gridOffset, sectionPosition,
sectionSize, foreground);
return foreground.get();
});
}
/**
* Creates a {@link net.imglib2.View} of the given grid section in the
* interval
* <p>
* Fits the view inside the bounds of the interval.
* </p>
*
* @param interval An n-dimensional interval with binary elements
* @param sizes Sizes of the interval's dimensions
* @param coordinates Starting coordinates of the section
* @param sectionSize Size of the section (n * n * ... n)
* @return A view of the interval spanning n pixels in each dimension from the
* coordinates. Null if view couldn't be set inside the interval
*/
private static <B extends BooleanType<B>> IntervalView<B> sectionView(
final RandomAccessibleInterval<B> interval, final long[] sizes,
final long[] coordinates, final long sectionSize)
{
final int n = sizes.length;
final long[] startPosition = IntStream.range(0, n).mapToLong(i -> Math.max(
0, coordinates[i])).toArray();
final long[] endPosition = IntStream.range(0, n).mapToLong(i -> Math.min(
(sizes[i] - 1), (coordinates[i] + sectionSize - 1))).toArray();
final boolean badBox = IntStream.range(0, n).anyMatch(
d -> (startPosition[d] >= sizes[d]) || (endPosition[d] < 0) ||
(endPosition[d] < startPosition[d]));
if (badBox) {
return null;
}
final BoundingBox box = new BoundingBox(n);
box.update(startPosition);
box.update(endPosition);
return Views.offsetInterval(interval, box);
}
/** Checks if the view has any foreground elements */
private static <B extends BooleanType<B>> boolean hasForeground(
IntervalView<B> view)
{
final Spliterator<B> spliterator = view.spliterator();
return StreamSupport.stream(spliterator, false).anyMatch(BooleanType::get);
}
/**
* Recursively counts the number of foreground sections in the grid over the
* given interval
*
* @param interval An n-dimensional interval with binary elements
* @param dimension Current dimension processed, start from the last
* @param sizes Sizes of the interval's dimensions in pixels
* @param translation Translation of grid start in each dimension
* @param sectionPosition The accumulated position of the current grid section
* (start from [0, 0, ... 0])
* @param sectionSize Size of a grid section (n * n * ... n)
* @param foreground Number of foreground sections found so far (start from 0)
*/
private static <B extends BooleanType<B>> void countGrid(
final RandomAccessibleInterval<B> interval, final int dimension,
final long[] sizes, final long[] translation, final long[] sectionPosition,
final long sectionSize, final LongType foreground)
{
for (int p = 0; p < sizes[dimension]; p += sectionSize) {
sectionPosition[dimension] = translation[dimension] + p;
if (dimension == 0) {
final IntervalView<B> box = sectionView(interval, sizes,
sectionPosition, sectionSize);
if (box != null && hasForeground(box)) {
foreground.inc();
}
}
else {
countGrid(interval, dimension - 1, sizes, translation, sectionPosition,
sectionSize, foreground);
}
}
}
/**
* Creates a {@link Stream} of t * 2^n translations in n-dimensions
* <p>
* The elements in the stream are arrays of coordinates [0, 0, .. 0], [-i, 0,
* .. 0], [0, -i, 0, .. 0], .. [-i, -i, .. -i], [-2i, 0, .. 0] .. [-ti, -ti,
* .. -ti], where each array has n elements, i = number of pixels translated,
* and t = number of translations. If the translations were positive, a part
* of the interval would not get inspected, because it always starts from [0,
* 0, ... 0].
* </p>
* <p>
* The order of arrays in the stream is not guaranteed.
* </p>
*
* @param numTranslations Number of translations (1 produces
* Stream.of(long[]{0, 0, .. 0}))
* @param amount Number of pixels shifted in translations
* @param dimension Current translation dimension (start from last)
* @param translation The accumulated position of the current translation
* (start from {0, 0, .. 0})
* @return A stream of coordinates of the translations
*/
private static Stream<long[]> translationStream(final long numTranslations,
final long amount, final int dimension, final long[] translation)
{
final Stream.Builder<long[]> builder = Stream.builder();
generateTranslations(numTranslations, amount, dimension, translation,
builder);
return builder.build();
}
/**
* Adds translations to the given {@link Stream.Builder}
*
* @see #translationStream(long, long, int, long[])
*/
private static void generateTranslations(final long numTranslations,
final long amount, final int dimension, final long[] translation,
final Stream.Builder<long[]> builder)
{
for (int t = 0; t < numTranslations; t++) {
translation[dimension] = -t * amount;
if (dimension == 0) {
builder.add(translation.clone());
}
else {
generateTranslations(numTranslations, amount, dimension - 1,
translation, builder);
}
}
}
} |
package net.krinsoft.chat;
import net.krinsoft.chat.api.Manager;
import net.krinsoft.chat.api.Target;
import net.krinsoft.chat.targets.Channel;
import net.krinsoft.chat.targets.ChatPlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.*;
/**
*
* @author krinsdeath
*/
public class ChannelManager implements Manager {
private ChatCore plugin;
private HashMap<String, Channel> channels = new HashMap<String, Channel>();
private boolean world_channels;
private FileConfiguration configuration;
private File config;
public ChannelManager(ChatCore instance) {
clean();
plugin = instance;
registerConfiguration();
registerChannels();
}
public void clean() {
for (Channel channel : channels.values()) {
channel.persist();
}
channels.clear();
}
@Override
public FileConfiguration getConfig() {
if (configuration == null) {
configuration = YamlConfiguration.loadConfiguration(config);
configuration.setDefaults(YamlConfiguration.loadConfiguration(config));
}
return configuration;
}
@Override
public void saveConfig() {
try {
getConfig().save(config);
} catch (Exception e) {
plugin.warn("An error occurred while trying to save 'channels.yml'");
}
}
@Override
public ChatCore getPlugin() {
return plugin;
}
public void registerConfiguration() {
config = new File(plugin.getDataFolder(), "channels.yml");
if (!config.exists()) {
getConfig().setDefaults(YamlConfiguration.loadConfiguration(plugin.getClass().getResourceAsStream("/defaults/channels.yml")));
getConfig().options().copyDefaults(true);
saveConfig();
}
world_channels = getConfig().getBoolean("world_channels");
}
public void registerChannels() {
Set<String> channels = getConfig().getConfigurationSection("channels").getKeys(false);
for (String channel : channels) {
createChannel(null, channel);
}
plugin.debug("Default Channel: " + getDefaultChannel());
}
public void log(String channel, String message) {
plugin.log("[" + channel + "] " + message);
}
/**
* Adds the specified player to the given channel
* @param player The player to add to the channel
* @param channel The name of the channel we're adding the player to
* @return The handle of the channel the player was added to
*/
public Channel addPlayerToChannel(Player player, String channel) {
Channel chan = channels.get(channel.toLowerCase());
if (chan == null) {
chan = new Channel(this, channel, player);
plugin.debug("Channel '" + channel + "' created");
}
if (!chan.contains(player)) {
chan.join(player);
}
return channels.put(channel.toLowerCase(), chan);
}
/**
* Removes the specified player from the given channel
* @param player The player we're removing from the channel
* @param channel The channel we're removing the player from
* @return The handle of the channel the player was removed from
*/
public Channel removePlayerFromChannel(Player player, String channel) {
// get the specified channel
Channel chan = channels.get(channel.toLowerCase());
if (chan == null) {
// no channel by that name existed, so we do nothing
return null;
} else {
// remove the player from the channel
if (chan.contains(player) && getPlayerChannelList(player).size() > 1) {
chan.part(player);
if (chan.getOccupants().size() < 1 && !chan.isPermanent()) {
// channel is empty! let's get rid of it
chan = channels.remove(channel.toLowerCase());
plugin.debug("Channel '" + chan.getName() + "' is empty: removing...");
}
}
return chan;
}
}
public void playerWorldChange(Player p, String from, String to) {
if (!world_channels) { return; }
if (plugin.getPlayerManager().isPlayerRegistered(p.getName())) {
ChatPlayer player = plugin.getPlayerManager().getPlayer(p.getName());
removePlayerFromChannel(p, from);
Target target = addPlayerToChannel(p, to);
if (player.getTarget().getName().equals(from)) {
player.setTarget(target);
}
player.setWorld(plugin.getWorldManager().getAlias(to));
}
}
void removePlayerFromAllChannels(Player player) {
for (Channel channel : new HashSet<Channel>(channels.values())) {
if (channel.contains(player)) {
channel.part(player);
if (channel.getOccupants().size() == 0 && !channel.isPermanent()) {
channels.remove(channel.getName().toLowerCase());
plugin.debug("Channel '" + channel.getName() + "' is empty: removing...");
}
}
}
}
public Channel getChannel(String channel) {
return channels.get(channel.toLowerCase());
}
public Channel getGlobalChannel() {
return getChannel(getDefaultChannel());
}
public String getDefaultChannel() {
return getConfig().getString("default", "Global");
}
public Channel createChannel(Player player, String channel) {
Channel chan = new Channel(this, channel, player);
if (player != null) {
chan.join(player);
}
channels.put(channel.toLowerCase(), chan);
return channels.get(channel.toLowerCase());
}
public List<Channel> getChannels() {
List<Channel> chans = new ArrayList<Channel>();
for (Channel chan : channels.values()) {
chans.add(chan);
}
return chans;
}
public List<Channel> getPlayerChannelList(Player player) {
List<Channel> list = new ArrayList<Channel>();
for (Channel chan : channels.values()) {
if (chan.contains(player)) {
list.add(chan);
}
}
return list;
}
public void connect() {
for (Channel chan : channels.values()) {
chan.connect();
}
}
} |
package nicolecade.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.result.Result;
import nicolecade.recipe.domain.Category;
import nicolecade.recipe.domain.Ingredient;
import nicolecade.recipe.domain.Recipe;
import nicolecade.recipe.domain.Review;
import nicolecade.recipe.domain.User;
import nicolecade.recipe.service.CategoryService;
import nicolecade.recipe.service.IngredientService;
import nicolecade.recipe.service.RecipeService;
import nicolecade.recipe.service.ReviewService;
import nicolecade.recipe.service.UserService;
import nicolecade.util.db.Neo4jSessionFactory;
import nicolecade.util.io.UserInput;
import nicolecade.view.MenuSession;
public enum ActionEnum implements Action {
EXIT_ACTION {
@Override
public void execute() {
System.out.println("Good bye!");
System.exit(0);
}
},
LOGOUT {
@Override
public void execute() {
MenuSession.singleton().setUser(null);
}
},
FOOD_BUDDY_RECOMMENDATIONS {
@Override
public void execute() {
final Session session = Neo4jSessionFactory.getInstance()
.getNeo4jSession();
final String username = "narruda";
String countCondition = "count (r)";
String titleAttribute = "title";
String recipeLabel = "f";
final Result result = session.query(
"match (n:User {username:'" + username
+ "'})-[FOOD_BUDDIES]-(m:User)<-[:LEFT_BY]-(r:Review {likedIt:true})<-[:HAS_REVIEW]-("
+ recipeLabel + ":Recipe) return " + recipeLabel
+ ", " + countCondition,
Collections.<String, LinkedHashMap> emptyMap());
LinkedHashMap<String, Integer> recipeToVotesMap = new LinkedHashMap<>();
for (Map<String, Object> row : result) {
recipeToVotesMap.put(
(String) ((LinkedHashMap) row.get(recipeLabel))
.get(titleAttribute),
(Integer) row.get(countCondition));
}
System.out.println();
System.out.println("Recommendations from your Food Buddies:");
System.out.println();
System.out.println(" RECIPE #LIKES");
Set<String> recipes = recipeToVotesMap.keySet();
Integer currentMostVotes;
String currentBestRecipe = "";
while (!recipeToVotesMap.isEmpty()) {
currentMostVotes = new Integer(-1);
for (String thisRecipe : recipes) {
Integer thisNumberOfVotes = recipeToVotesMap
.get(thisRecipe);
if (thisNumberOfVotes.compareTo(currentMostVotes) > 0) {
currentMostVotes = thisNumberOfVotes;
currentBestRecipe = thisRecipe;
}
}
recipeToVotesMap.remove(currentBestRecipe);
System.out.printf("%-35s%d\n", currentBestRecipe,
currentMostVotes);
}
}
},
POPULATE_DB {
@Override
public void execute() {
System.out.println("Populating...");
System.out.println();
final ArrayList<User> users = new ArrayList<User>();
final ArrayList<Category> categories = new ArrayList<Category>();
final ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
final ArrayList<Review> reviews = new ArrayList<Review>();
final ArrayList<Recipe> recipes = new ArrayList<Recipe>();
final User nicole = this.addUser(users, "narruda");
final User cade = this.addUser(users, "csperlich");
final User krish = this.addUser(users, "knarayanan");
final User celeste = this.addUser(users, "carruda");
final User healthy = this.addUser(users, "health_nut", "4444");
final User dad = this.addUser(users, "dad_arruda");
nicole.addFoodBuddy(celeste);
nicole.addFoodBuddy(dad);
nicole.addFoodBuddy(cade);
nicole.addFoodBuddy(krish);
final Category starches = this.addCategory(categories, "Starches");
final Category dairy = this.addCategory(categories,
"Dairy products");
final Category seasonings = this.addCategory(categories,
"Herbs, spices, and seasonings");
final Category produce = this.addCategory(categories,
"Fruits and vegetables");
final Category protein = this.addCategory(categories, "Protein");
final Ingredient potatoes = this.addIngredient(ingredients,
starches, "Potatoes");
potatoes.addToCategory(produce);
final Ingredient butter = this.addIngredient(ingredients, dairy,
"Butter");
final Ingredient salt = this.addIngredient(ingredients, seasonings,
"Salt");
final Ingredient pepper = this.addIngredient(ingredients,
seasonings, "Black pepper");
final Ingredient milk = this.addIngredient(ingredients, dairy,
"Whole milk");
final Ingredient yogurt = this.addIngredient(ingredients, dairy,
"Yogurt");
yogurt.addToCategory(protein);
final Ingredient tomatoes = this.addIngredient(ingredients, produce,
"Tomatoes");
final Ingredient peas = this.addIngredient(ingredients, produce,
"Peas");
final Ingredient onion = this.addIngredient(ingredients, produce,
"Onion");
final Ingredient cumin = this.addIngredient(ingredients, seasonings,
"Cumin");
final Ingredient lemon = this.addIngredient(ingredients, produce,
"Lemon juice");
final Ingredient rice = this.addIngredient(ingredients, starches,
"Rice");
final Ingredient mushrooms = this.addIngredient(ingredients,
produce, "Mushrooms");
final Ingredient egg = this.addIngredient(ingredients, protein,
"Egg");
egg.addToCategory(dairy);
final Ingredient biBimBopSauce = this.addIngredient(ingredients,
seasonings, "Bi Bim Bop sauce");
final Ingredient zucchini = this.addIngredient(ingredients, produce,
"Zucchini");
final boolean LIKE = true;
final boolean DISLIKE = false;
final Review potatoReview1 = this.addReview(reviews, celeste,
"So light and fluffy! This is the best way to make mashed potatoes.",
LIKE);
final Review potatoReview2 = this.addReview(reviews, healthy,
"Ugh, I can feel my arteries clogging.", DISLIKE);
final Review potatoReview3 = addReview(reviews, cade,
"I love potatoes.", LIKE);
final Review yogurtReview1 = this.addReview(reviews, nicole,
"Who knew you could make new yogurt from old yogurt?",
LIKE);
final Review mattarPaneerReview1 = this.addReview(reviews, krish,
"Very authentic!", LIKE);
final Review mattarPaneerReview2 = this.addReview(reviews, healthy,
"I like that it's vegetarian.", LIKE);
final Review mattarPaneerReview3 = this.addReview(reviews, celeste,
"Too spicy for me.", DISLIKE);
final Review biBimBopReview1 = this.addReview(reviews, healthy,
"This is actually pretty good.", LIKE);
final Review biBimBopReview2 = this.addReview(reviews, nicole,
"Rice + egg = :)", LIKE);
final Review biBimBopReview3 = addReview(reviews, celeste, "Yum!",
LIKE);
this.addRecipe(recipes, nicole, "Mashed Potatoes",
Arrays.asList(potatoes, butter, salt, pepper, milk),
Arrays.asList(potatoReview1, potatoReview2, potatoReview3));
this.addRecipe(recipes, dad, "Homemade Yogurt",
Arrays.asList(yogurt, milk), Arrays.asList(yogurtReview1));
this.addRecipe(recipes, dad, "Mattar Paneer",
Arrays.asList(milk, lemon, tomatoes, onion, peas, cumin),
Arrays.asList(mattarPaneerReview1, mattarPaneerReview2,
mattarPaneerReview3));
this.addRecipe(recipes, cade, "Bi Bim Bop",
Arrays.asList(rice, mushrooms, egg, zucchini,
biBimBopSauce),
Arrays.asList(biBimBopReview1, biBimBopReview2,
biBimBopReview3));
final UserService userService = new UserService();
for (final User user : users) {
userService.createOrUpdate(user);
}
final CategoryService categoryService = new CategoryService();
for (final Category category : categories) {
categoryService.createOrUpdate(category);
}
final IngredientService ingredientService = new IngredientService();
for (final Ingredient ingredient : ingredients) {
ingredientService.createOrUpdate(ingredient);
}
final ReviewService reviewService = new ReviewService();
for (final Review review : reviews) {
reviewService.createOrUpdate(review);
}
final RecipeService recipeService = new RecipeService();
for (final Recipe recipe : recipes) {
recipeService.createOrUpdate(recipe);
}
System.out.println();
System.out.println("Database populated!");
}
private Recipe addRecipe(ArrayList<Recipe> recipes, User contributor,
String title, List<Ingredient> ingredients,
List<Review> reviews) {
final Recipe recipe = new Recipe();
recipe.setTitle(title);
recipe.setContributor(contributor);
recipe.setIngredients(ingredients);
recipe.setReviews(reviews);
recipes.add(recipe);
return recipe;
}
private Review addReview(ArrayList<Review> reviews, User user,
String comment, boolean likedIt) {
final Review review = new Review();
review.setComment(comment);
review.setReviewer(user);
review.setLikedIt(likedIt);
reviews.add(review);
return review;
}
private Ingredient addIngredient(ArrayList<Ingredient> ingredients,
Category category, String name) {
final Ingredient ingredient = new Ingredient();
ingredient.setName(name);
ingredient.addToCategory(category);
ingredients.add(ingredient);
return ingredient;
}
private Category addCategory(ArrayList<Category> categories,
String description) {
final Category category = new Category();
category.setDescription(description);
categories.add(category);
return category;
}
private User addUser(ArrayList<User> users, String... userInfo) {
final User user = new User();
user.setUsername(userInfo[0]);
if (userInfo.length == 2) {
user.setPassword(userInfo[1]);
} else {
user.setPassword("1234");
}
users.add(user);
return user;
}
},
DROP_ALL_DB {
@Override
public void execute() {
System.out.println("Emptying database...");
System.out.println();
final Session session = Neo4jSessionFactory.getInstance()
.getNeo4jSession();
session.query("MATCH (n) DETACH DELETE n",
Collections.<String, Object> emptyMap());
System.out.println();
System.out.println("Database empty.");
}
},
USER_LOGIN {
@Override
public void execute() {
final UserInput input = UserInput.singleton();
System.out.println("Enter a username");
final String username = input.getNextLine();
System.out.println("Enter password");
final String password = input.getNextLine();
final UserService service = new UserService();
final User user = service.login(username, password);
if (user == null) {
System.out.println("invalid username and/or password");
MenuSession.singleton().setFailFlag();
} else {
MenuSession.singleton().setUser(user);
System.out.println("Welcome " + user.getUsername());
}
}
},
USER_REGISTRATION {
@Override
public void execute() {
final UserInput input = UserInput.singleton();
System.out.println("Enter a username");
final String username = input.getNextLine();
System.out.println("Enter password");
final String password = input.getNextLine();
final UserService service = new UserService();
final User user = service.register(username, password);
if (user == null) {
System.out.println("username " + username + " is taken");
MenuSession.singleton().setFailFlag();
} else {
MenuSession.singleton().setUser(user);
System.out.println("Welcome " + user.getUsername());
}
}
};
} |
package org.apdplat.word.vector;
import org.apdplat.word.analysis.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
*
* @author
*/
public class Distance {
private static final Logger LOGGER = LoggerFactory.getLogger(Distance.class);
private TextSimilarity textSimilarity = null;
private Map<String, String> model = null;
private int limit = 15;
public Distance(TextSimilarity textSimilarity, String model) throws Exception {
this.textSimilarity = textSimilarity;
this.model = parseModel(model);
}
public void setTextSimilarity(TextSimilarity textSimilarity) {
LOGGER.info(""+textSimilarity.getClass().getName());
this.textSimilarity = textSimilarity;
}
public void setLimit(int limit) {
LOGGER.info(""+limit);
this.limit = limit;
}
private Map<String, String> parseModel(String model) throws Exception {
Map<String, String> map = new HashMap<>();
LOGGER.info("");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(model), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
String[] attr = line.split(" : ");
if (attr == null || attr.length != 2) {
LOGGER.error("" + line);
continue;
}
String key = attr[0];
String value = attr[1];
value = value.substring(1, value.length() - 1);
map.put(key, value);
}
}
LOGGER.info("");
return map;
}
private void tip(){
LOGGER.info("sa=cos");
LOGGER.info(" 1sa=cos");
LOGGER.info(" 2sa=edi");
LOGGER.info(" 3sa=euc");
LOGGER.info(" 4sa=sim");
LOGGER.info(" 5sa=jacJaccard");
LOGGER.info(" 6sa=man");
LOGGER.info(" 7sa=shhSimHash + ");
LOGGER.info("limit=15");
LOGGER.info("exit");
LOGGER.info("");
}
private void interact(String encoding) throws Exception{
tip();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){
String line = null;
while((line = reader.readLine()) != null){
if("exit".equals(line)){
System.exit(0);
}
if(line.startsWith("limit=")){
try{
setLimit(Integer.parseInt(line.replace("limit=", "").trim()));
}catch (Exception e){
LOGGER.error("");
}
continue;
}
if(line.startsWith("sa=")){
switch (line.substring(3)){
case "cos": setTextSimilarity(new CosineTextSimilarity());continue;
case "edi": setTextSimilarity(new EditDistanceTextSimilarity());continue;
case "euc": setTextSimilarity(new EuclideanDistanceTextSimilarity());continue;
case "sim": setTextSimilarity(new SimpleTextSimilarity());continue;
case "jac": setTextSimilarity(new JaccardTextSimilarity());continue;
case "man": setTextSimilarity(new ManhattanDistanceTextSimilarity());continue;
case "shh": setTextSimilarity(new SimHashPlusHammingDistanceTextSimilarity());continue;
}
continue;
}
String value = model.get(line);
if(value == null){
LOGGER.info(""+line);
}else{
LOGGER.info("" + value);
LOGGER.info("" + limit);
LOGGER.info(line+" "+textSimilarity.getClass().getSimpleName()+"");
LOGGER.info("
List<String> list = compute(value, limit);
AtomicInteger i = new AtomicInteger();
for(String element : list){
LOGGER.info("\t"+i.incrementAndGet()+""+element);
}
LOGGER.info("
}
tip();
}
}
}
public List<String> compute(String words, int limit){
Map<String, Float> wordVec = new HashMap<>();
String[] ws = words.split(", ");
for(String w : ws){
String[] attr = w.split(" ");
String k = attr[0];
float v = Float.parseFloat(attr[1]);
wordVec.put(k, v);
}
Map<String, Double> result = new HashMap<>();
for(String key : model.keySet()){
String value = model.get(key);
String[] elements = value.split(", ");
Map<String, Float> vec = new HashMap<>();
for(String element : elements){
String[] attr = element.split(" ");
String k = attr[0];
float v = Float.parseFloat(attr[1]);
vec.put(k, v);
}
if(vec.size()<10){
continue;
}
double score = textSimilarity.similarScore(wordVec, vec);
if(score > 0){
result.put(key, score);
}
}
if(result.isEmpty()){
LOGGER.info("");
return Collections.emptyList();
}
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("" + result.size());
}
List<Entry<String, Double>> list = result.entrySet().parallelStream().sorted((a,b)->b.getValue().compareTo(a.getValue())).collect(Collectors.toList());
if(limit > list.size()){
limit = list.size();
}
List<String> retValue = new ArrayList<>(limit);
for(int i=0; i< limit; i++){
retValue.add(list.get(i).getKey()+" "+list.get(i).getValue());
}
return retValue;
}
public static void main(String[] args) throws Exception{
String model = "data/vector.txt";
String encoding = "gbk";
if(args.length == 1){
model = args[0];
}
if(args.length == 2){
model = args[0];
encoding = args[1];
}
Distance distance = new Distance(new EditDistanceTextSimilarity(), model);
distance.interact(encoding);
}
} |
package org.cojen.tupl.repl;
import java.io.File;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Checksum;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
import org.cojen.tupl.io.CRC32C;
import org.cojen.tupl.io.Utils;
import org.cojen.tupl.util.Latch;
import org.cojen.tupl.util.Worker;
/**
* Standard StateLog implementation which stores data in file segments.
*
* @author Brian S O'Neill
*/
final class FileStateLog extends Latch implements StateLog {
/*
File naming:
<base>.md (metadata file)
<base>.<term>.<start index> (log files)
Metadata file stores little-endian fields at offset 0 and 4096, alternating.
0: Magic number (long)
8: Encoding version (int)
12: Metadata counter (int)
16: Start index (long)
24: Current term (long)
32: Highest log term (long)
40: Highest contiguous log index (exclusive) (long)
48: Commit log index (exclusive) (long)
56: CRC32C (int)
Example files with base of "mydata.repl":
mydata.repl
mydata.repl.0.0
mydata.repl.1.1000
mydata.repl.1.2000
mydata.repl.2.2500
*/
private static final long MAGIC_NUMBER = 5267718596810043313L;
private static final int ENCODING_VERSION = 20170812;
private static final int SECTION_POW = 12;
private static final int SECTION_SIZE = 1 << SECTION_POW;
private static final int METADATA_SIZE = 60;
private static final int METADATA_FILE_SIZE = SECTION_SIZE + METADATA_SIZE;
private static final int COUNTER_OFFSET = 12;
private static final int START_INDEX_OFFSET = 16;
private static final int CRC_OFFSET = METADATA_SIZE - 4;
private final File mBase;
private final Worker mWorker;
// Terms are keyed only by their start index.
private final ConcurrentSkipListSet<LKey<TermLog>> mTermLogs;
private final FileChannel mMetadataFile;
private final MappedByteBuffer mMetadataBuffer;
private final Checksum mMetadataCrc;
private final LogInfo mMetadataInfo;
private int mMetadataCounter;
private long mStartIndex;
private long mCurrentTerm;
private TermLog mHighestTermLog;
private TermLog mCommitTermLog;
private TermLog mContigTermLog;
private boolean mClosed;
FileStateLog(File base) throws IOException {
base = FileTermLog.checkBase(base);
mBase = base;
mWorker = Worker.make(10, 15, TimeUnit.SECONDS, null);
mTermLogs = new ConcurrentSkipListSet<>();
mMetadataFile = FileChannel.open
(new File(base.getPath() + ".md").toPath(),
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE,
StandardOpenOption.DSYNC);
boolean mdFileExists = mMetadataFile.size() != 0;
mMetadataBuffer = mMetadataFile.map(FileChannel.MapMode.READ_WRITE, 0, METADATA_FILE_SIZE);
mMetadataBuffer.order(ByteOrder.LITTLE_ENDIAN);
mMetadataCrc = CRC32C.newInstance();
mMetadataInfo = new LogInfo();
if (!mdFileExists) {
// Prepare a new metadata file.
cleanMetadata(0, 0);
cleanMetadata(SECTION_SIZE, 1);
}
// Ensure existing contents are durable following a process restart.
mMetadataBuffer.force();
long counter0 = verifyMetadata(0);
long counter1 = verifyMetadata(SECTION_SIZE);
// Select the higher counter from the valid sections.
int counter, offset;
select: {
if (counter0 < 0) {
if (counter1 < 0) {
if (counter0 == -1 || counter1 == -1) {
throw new IOException("Metadata magic number is wrong");
}
throw new IOException("Metadata CRC mismatch");
}
} else if (counter1 < 0 || (((int) counter0) - (int) counter1) > 0) {
counter = (int) counter0;
offset = 0;
break select;
}
counter = (int) counter1;
offset = SECTION_SIZE;
}
if (((counter & 1) << SECTION_POW) != offset) {
throw new IOException("Metadata sections are swapped");
}
mMetadataCounter = counter;
mMetadataBuffer.clear();
mMetadataBuffer.position(offset + START_INDEX_OFFSET);
long startIndex = mMetadataBuffer.getLong();
long currentTerm = mMetadataBuffer.getLong();
long highestTerm = mMetadataBuffer.getLong();
long highestIndex = mMetadataBuffer.getLong();
long commitIndex = mMetadataBuffer.getLong();
if (currentTerm < highestTerm) {
throw new IOException("Current term is lower than highest term");
}
if (highestIndex < commitIndex) {
throw new IOException("Highest index is lower than commit index");
}
if (startIndex > commitIndex) {
throw new IOException("Start index is higher than commit index");
}
mStartIndex = startIndex;
mCurrentTerm = currentTerm;
// Open all the existing terms.
TreeMap<Long, List<String>> mTermFileNames = new TreeMap<>();
String[] fileNames = mBase.getParentFile().list();
if (fileNames != null && fileNames.length != 0) {
Pattern p = Pattern.compile(base.getName() + "\\.(\\d*)\\.\\d*");
for (String name : fileNames) {
Matcher m = p.matcher(name);
if (m.matches()) {
Long term = Long.valueOf(m.group(1));
if (term <= 0) {
throw new IOException("Illegal term: " + term);
}
List<String> termNames = mTermFileNames.get(term);
if (termNames == null) {
termNames = new ArrayList<>();
mTermFileNames.put(term, termNames);
}
termNames.add(name);
}
}
}
long prevTerm = 0;
for (Map.Entry<Long, List<String>> e : mTermFileNames.entrySet()) {
long term = e.getKey();
TermLog termLog = FileTermLog.openTerm
(mWorker, mBase, prevTerm, term, -1, 0, highestIndex, e.getValue());
mTermLogs.add(termLog);
prevTerm = term;
}
TermLog highest = null;
if (!mTermLogs.isEmpty()) {
Iterator<LKey<TermLog>> it = mTermLogs.iterator();
TermLog termLog = (TermLog) it.next();
while (true) {
if (termLog.term() > highestTerm) {
// Delete all terms higher than the highest.
while (true) {
termLog.finishTerm(termLog.startIndex());
it.remove();
if (!it.hasNext()) {
break;
}
termLog = (TermLog) it.next();
}
break;
}
highest = termLog;
TermLog next;
if (it.hasNext()) {
next = (TermLog) it.next();
} else {
next = null;
}
if (next == null) {
break;
}
if (next.term() <= highestTerm) {
termLog.finishTerm(next.startIndex());
}
termLog = next;
}
}
if (commitIndex > 0) {
commit(commitIndex);
}
}
private void cleanMetadata(int offset, int counter) {
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset);
bb.limit(offset + METADATA_SIZE);
bb.putLong(MAGIC_NUMBER);
bb.putInt(ENCODING_VERSION);
bb.putInt(counter);
// Start index, current term, highest log term, highest log index, commit log index.
if (bb.position() != (offset + START_INDEX_OFFSET)) {
throw new AssertionError();
}
for (int i=0; i<5; i++) {
bb.putLong(0);
}
if (bb.position() != (offset + CRC_OFFSET)) {
throw new AssertionError();
}
bb.limit(bb.position());
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
bb.putInt((int) mMetadataCrc.getValue());
}
/**
* @return uint32 counter value, or -1 if wrong magic number, or -2 if CRC doesn't match
* @throws IOException if wrong magic number or encoding version
*/
private long verifyMetadata(int offset) throws IOException {
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset);
bb.limit(offset + CRC_OFFSET);
if (bb.getLong() != MAGIC_NUMBER) {
return -1;
}
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
int actual = bb.getInt();
if (actual != (int) mMetadataCrc.getValue()) {
return -2;
}
bb.clear();
bb.position(offset + 8);
bb.limit(offset + CRC_OFFSET);
int encoding = bb.getInt();
if (encoding != ENCODING_VERSION) {
throw new IOException("Metadata encoding version is unknown: " + encoding);
}
return bb.getInt() & 0xffffffffL;
}
@Override
public void captureHighest(LogInfo info) {
acquireShared();
TermLog highestLog = mHighestTermLog;
if (highestLog != null && highestLog == mTermLogs.last()) {
highestLog.captureHighest(info);
releaseShared();
} else {
doCaptureHighest(info, highestLog, true);
}
}
// Must be called with shared latch held.
private TermLog doCaptureHighest(LogInfo info, TermLog highestLog, boolean releaseLatch) {
int size = mTermLogs.size();
if (size == 0) {
info.mTerm = 0;
info.mHighestIndex = 0;
info.mCommitIndex = 0;
if (releaseLatch) {
releaseShared();
}
return null;
}
if (highestLog != null) {
// Search again, in case log instance has been orphaned.
highestLog = (TermLog) mTermLogs.ceiling(highestLog); // findGe
}
if (highestLog == null) {
highestLog = (TermLog) mTermLogs.first();
}
while (true) {
TermLog nextLog = (TermLog) mTermLogs.higher(highestLog); // findGt
highestLog.captureHighest(info);
if (nextLog == null || info.mHighestIndex < nextLog.startIndex()) {
if (tryUpgrade()) {
mHighestTermLog = highestLog;
if (releaseLatch) {
releaseExclusive();
} else {
downgrade();
}
} else {
if (releaseLatch) {
releaseShared();
}
}
return highestLog;
}
highestLog = nextLog;
}
}
@Override
public void commit(long commitIndex) {
acquireShared();
TermLog commitLog = mCommitTermLog;
if (commitLog != null && commitLog == mTermLogs.last()) {
commitLog.commit(commitIndex);
releaseShared();
return;
}
int size = mTermLogs.size();
if (size == 0) {
releaseShared();
return;
}
if (commitLog != null) {
// Search again, in case log instance has been orphaned.
commitLog = (TermLog) mTermLogs.ceiling(commitLog); // findGe
}
if (commitLog == null) {
commitLog = (TermLog) mTermLogs.first();
}
LogInfo info = new LogInfo();
while (true) {
commitLog.captureHighest(info);
if (info.mCommitIndex < commitLog.endIndex()) {
break;
}
commitLog = (TermLog) mTermLogs.higher(commitLog); // findGt
}
if (commitLog != mCommitTermLog && tryUpgrade()) {
mCommitTermLog = commitLog;
downgrade();
}
do {
commitLog.commit(commitIndex);
} while ((commitLog = (TermLog) mTermLogs.higher(commitLog)) != null);
releaseShared();
}
@Override
public long incrementCurrentTerm(int termIncrement) throws IOException {
if (termIncrement <= 0) {
throw new IllegalArgumentException();
}
synchronized (mMetadataInfo) {
mCurrentTerm += termIncrement;
doSync();
return mCurrentTerm;
}
}
@Override
public long checkCurrentTerm(long term) throws IOException {
synchronized (mMetadataInfo) {
if (term > mCurrentTerm) {
mCurrentTerm = term;
doSync();
}
return mCurrentTerm;
}
}
@Override
public void startIndex(long index) throws IOException {
acquireExclusive();
if (mStartIndex != 0) {
// FIXME: Allow changing the start index to a higher value, but not higher than the
// commit index. Sync metadata before deleting any segments.
releaseExclusive();
throw new IllegalStateException();
}
mStartIndex = index;
releaseExclusive();
}
@Override
public boolean defineTerm(long prevTerm, long term, long index) throws IOException {
return defineTermLog(prevTerm, term, index) != null;
}
@Override
public void queryTerms(long startIndex, long endIndex, TermQuery results) {
if (startIndex >= endIndex) {
return;
}
LKey<TermLog> startKey = new LKey.Finder<>(startIndex);
LKey<TermLog> endKey = new LKey.Finder<>(endIndex);
LKey<TermLog> prev = mTermLogs.floor(startKey); // findLe
if (prev != null && ((TermLog) prev).endIndex() > startIndex) {
startKey = prev;
}
for (Object key : mTermLogs.subSet(startKey, endKey)) {
TermLog termLog = (TermLog) key;
results.term(termLog.prevTerm(), termLog.term(), termLog.startIndex());
}
}
@Override
public long checkForMissingData(long contigIndex, IndexRange results) {
acquireShared();
TermLog termLog = mContigTermLog;
if (termLog != null && termLog == mTermLogs.last()) {
releaseShared();
return termLog.checkForMissingData(contigIndex, results);
}
int size = mTermLogs.size();
if (size == 0) {
releaseShared();
return 0;
}
if (termLog != null) {
// Search again, in case log instance has been orphaned.
termLog = (TermLog) mTermLogs.ceiling(termLog); // findGe
}
if (termLog == null) {
termLog = (TermLog) mTermLogs.first();
}
final long originalContigIndex = contigIndex;
TermLog nextLog;
while (true) {
nextLog = (TermLog) mTermLogs.higher(termLog); // findGt
contigIndex = termLog.checkForMissingData(contigIndex, results);
if (contigIndex < termLog.endIndex() || nextLog == null) {
break;
}
termLog = nextLog;
}
if (termLog != mContigTermLog && tryUpgrade()) {
mContigTermLog = termLog;
if (nextLog == null) {
releaseExclusive();
return contigIndex;
}
downgrade();
}
if (contigIndex == originalContigIndex) {
// Scan ahead into all remaining terms.
while (nextLog != null) {
nextLog.checkForMissingData(0, results);
nextLog = (TermLog) mTermLogs.higher(nextLog); // findGt
}
}
releaseShared();
return contigIndex;
}
@Override
public LogWriter openWriter(long prevTerm, long term, long index) throws IOException {
TermLog termLog = defineTermLog(prevTerm, term, index);
return termLog == null ? null : termLog.openWriter(index);
}
/**
* @return null if not defined due to term mismatch
*/
// package-private for testing
TermLog defineTermLog(long prevTerm, long term, long index) throws IOException {
final LKey<TermLog> key = new LKey.Finder<>(index);
boolean exclusive = false;
acquireShared();
try {
TermLog termLog;
defineTermLog: while (true) {
TermLog prevTermLog = (TermLog) mTermLogs.lower(key); // findLt
if (prevTermLog == null) {
if (index != mStartIndex) {
termLog = null;
break defineTermLog;
}
} else {
long actualPrevTerm = prevTermLog.term();
if (prevTerm != actualPrevTerm) {
termLog = null;
break defineTermLog;
}
if (term == actualPrevTerm && index < prevTermLog.endIndex()) {
termLog = prevTermLog;
break defineTermLog;
}
}
TermLog startTermLog = (TermLog) mTermLogs.floor(key); // findLe
if (startTermLog != null) {
long actualTerm = startTermLog.term();
if (term == actualTerm) {
termLog = startTermLog;
break defineTermLog;
}
if (term < actualTerm || (actualTerm > 0 && prevTermLog == null)) {
termLog = null;
break defineTermLog;
}
if (!exclusive) {
if (tryUpgrade()) {
exclusive = true;
} else {
releaseShared();
acquireExclusive();
exclusive = true;
continue;
}
}
prevTermLog = startTermLog;
prevTermLog.finishTerm(index);
// Truncate and remove all higher conflicting term logs. Iterator might
// start with the prevTermLog just finished, facilitating its
// removal. Finishing again at the same index is harmless.
Iterator<LKey<TermLog>> it = mTermLogs.tailSet(key).iterator(); // viewGe
while (it.hasNext()) {
TermLog logGe = (TermLog) it.next();
logGe.finishTerm(index);
it.remove();
}
}
if (mClosed) {
throw new IOException("Closed");
}
if (!exclusive) {
if (tryUpgrade()) {
exclusive = true;
} else {
releaseShared();
acquireExclusive();
exclusive = true;
continue;
}
}
long commitIndex;
if (prevTermLog == null) {
commitIndex = index;
} else {
prevTermLog.sync();
LogInfo info = new LogInfo();
prevTermLog.captureHighest(info);
commitIndex = info.mCommitIndex;
}
termLog = FileTermLog.newTerm(mWorker, mBase, prevTerm, term, index, commitIndex);
mTermLogs.add(termLog);
break defineTermLog;
}
return termLog;
} finally {
release(exclusive);
}
}
@Override
public LogReader openReader(long index) {
LKey<TermLog> key = new LKey.Finder<>(index);
boolean exclusive = false;
acquireShared();
try {
TermLog termLog;
findTerm: {
while (true) {
termLog = (TermLog) mTermLogs.floor(key); // findLe
if (termLog != null) {
break findTerm;
}
if (!mTermLogs.isEmpty()) {
throw new IllegalStateException
("Index is lower than start index: " + key.key() + " < " +
((TermLog) mTermLogs.first()).startIndex());
}
if (exclusive) {
break;
}
if (tryUpgrade()) {
exclusive = true;
break;
}
releaseShared();
acquireExclusive();
exclusive = true;
}
// Create a primordial term.
termLog = FileTermLog.newTerm(mWorker, mBase, 0, 0, mStartIndex, mStartIndex);
mTermLogs.add(termLog);
}
return termLog.openReader(index);
} finally {
release(exclusive);
}
}
@Override
public void sync() throws IOException {
synchronized (mMetadataInfo) {
doSync();
}
}
// Caller must be synchronized on mMetadataInfo.
private void doSync() throws IOException {
if (mClosed) {
return;
}
acquireShared();
try {
TermLog highestLog = mHighestTermLog;
if (highestLog != null && highestLog == mTermLogs.last()) {
highestLog.captureHighest(mMetadataInfo);
highestLog.sync();
} else {
highestLog = doCaptureHighest(mMetadataInfo, highestLog, false);
if (highestLog != null) {
highestLog.sync();
}
}
} finally {
releaseShared();
}
int counter = mMetadataCounter + 1;
int offset = (counter & 1) << SECTION_POW;
MappedByteBuffer bb = mMetadataBuffer;
bb.clear();
bb.position(offset + COUNTER_OFFSET);
bb.limit(offset + CRC_OFFSET);
bb.putInt(counter);
bb.putLong(mStartIndex);
bb.putLong(mCurrentTerm);
bb.putLong(mMetadataInfo.mTerm);
bb.putLong(mMetadataInfo.mHighestIndex);
bb.putLong(mMetadataInfo.mCommitIndex);
bb.position(offset);
mMetadataCrc.reset();
CRC32C.update(mMetadataCrc, bb);
bb.limit(offset + METADATA_SIZE);
bb.putInt((int) mMetadataCrc.getValue());
bb.force();
mMetadataCounter = counter;
}
@Override
public void close() throws IOException {
synchronized (mMetadataInfo) {
acquireExclusive();
try {
if (mClosed) {
return;
}
mClosed = true;
mMetadataFile.close();
Utils.delete(mMetadataBuffer);
for (Object key : mTermLogs) {
((TermLog) key).close();
}
} finally {
releaseExclusive();
}
}
mWorker.join(true);
}
} |
package org.fcrepo.binary;
import org.fcrepo.utils.FedoraJcrTypes;
import org.modeshape.jcr.value.binary.NamedHint;
import org.modeshape.jcr.value.binary.StrategyHint;
import org.slf4j.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import static org.fcrepo.utils.FedoraJcrTypes.FEDORA_CONTENTTYPE;
import static org.slf4j.LoggerFactory.getLogger;
public class MimeTypePolicy implements Policy {
private static final Logger logger = getLogger(MimeTypePolicy.class);
private final String mimeType;
private final StrategyHint hint;
public MimeTypePolicy(String mimeType, StrategyHint hint) {
this.mimeType = mimeType;
this.hint = hint;
}
public StrategyHint evaluatePolicy(Node n) {
logger.debug("Evaluating MimeTypePolicy for {} -> {}", mimeType, hint.toString());
try {
final String nodeMimeType = n.getProperty(FEDORA_CONTENTTYPE).getString();
logger.debug("Found mime type {}", nodeMimeType);
if(nodeMimeType.equals(mimeType)) {
return hint;
}
} catch (RepositoryException e) {
logger.warn("Got Exception evaluating policy: {}", e);
return null;
}
return null;
}
} |
package org.jtrfp.trcl.objects;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
public interface Velocible
{public void setVelocity(Vector3D vel);
public Vector3D getVelocity();
public void accellerate(Vector3D scalarMultiply);
} |
package org.kohsuke.github;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.CheckForNull;
import static org.kohsuke.github.internal.Previews.LYDIAN;
import static org.kohsuke.github.internal.Previews.SHADOW_CAT;
/**
* A pull request.
*
* @author Kohsuke Kawaguchi
* @see GHRepository#getPullRequest(int) GHRepository#getPullRequest(int)
*/
@SuppressWarnings({ "UnusedDeclaration" })
public class GHPullRequest extends GHIssue implements Refreshable {
private static final String COMMENTS_ACTION = "/comments";
private static final String REQUEST_REVIEWERS = "/requested_reviewers";
private String patch_url, diff_url, issue_url;
private GHCommitPointer base;
private String merged_at;
private GHCommitPointer head;
// details that are only available when obtained from ID
private GHUser merged_by;
private int review_comments, additions, commits;
private boolean merged, maintainer_can_modify;
// making these package private to all for testing
boolean draft;
private Boolean mergeable;
private int deletions;
private String mergeable_state;
private int changed_files;
private String merge_commit_sha;
private AutoMerge auto_merge;
// pull request reviewers
private GHUser[] requested_reviewers;
private GHTeam[] requested_teams;
GHPullRequest wrapUp(GHRepository owner) {
this.wrap(owner);
return this;
}
@Override
protected String getApiRoute() {
if (owner == null) {
// Issues returned from search to do not have an owner. Attempt to use url.
final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!");
return StringUtils.prependIfMissing(url.toString().replace(root().getApiUrl(), ""), "/");
}
return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number;
}
/**
* The status of auto merging a pull request.
*
* @return the {@linkplain AutoMerge} or {@code null} if no auto merge is set.
*/
public AutoMerge getAutoMerge() {
return auto_merge;
}
public URL getPatchUrl() {
return GitHubClient.parseURL(patch_url);
}
public URL getIssueUrl() {
return GitHubClient.parseURL(issue_url);
}
/**
* This points to where the change should be pulled into, but I'm not really sure what exactly it means.
*
* @return the base
*/
public GHCommitPointer getBase() {
return base;
}
/**
* The change that should be pulled. The tip of the commits to merge.
*
* @return the head
*/
public GHCommitPointer getHead() {
return head;
}
/**
* Gets issue updated at.
*
* @return the issue updated at
* @throws IOException
* the io exception
*/
@Deprecated
public Date getIssueUpdatedAt() throws IOException {
return super.getUpdatedAt();
}
public URL getDiffUrl() {
return GitHubClient.parseURL(diff_url);
}
/**
* Gets merged at.
*
* @return the merged at
*/
public Date getMergedAt() {
return GitHubClient.parseDate(merged_at);
}
@Override
public GHUser getClosedBy() {
return null;
}
@Override
public PullRequest getPullRequest() {
return null;
}
// details that are only available via get with ID
/**
* Gets merged by.
*
* @return the merged by
* @throws IOException
* the io exception
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior")
public GHUser getMergedBy() throws IOException {
populate();
return merged_by;
}
/**
* Gets review comments.
*
* @return the review comments
* @throws IOException
* the io exception
*/
public int getReviewComments() throws IOException {
populate();
return review_comments;
}
/**
* Gets additions.
*
* @return the additions
* @throws IOException
* the io exception
*/
public int getAdditions() throws IOException {
populate();
return additions;
}
/**
* Gets commits.
*
* @return the commits
* @throws IOException
* the io exception
*/
public int getCommits() throws IOException {
populate();
return commits;
}
/**
* Is merged boolean.
*
* @return the boolean
* @throws IOException
* the io exception
*/
public boolean isMerged() throws IOException {
populate();
return merged;
}
/**
* Can maintainer modify boolean.
*
* @return the boolean
* @throws IOException
* the io exception
*/
public boolean canMaintainerModify() throws IOException {
populate();
return maintainer_can_modify;
}
/**
* Is draft boolean.
*
* @return the boolean
* @throws IOException
* the io exception
*/
public boolean isDraft() throws IOException {
populate();
return draft;
}
/**
* Is this PR mergeable?
*
* @return null if the state has not been determined yet, for example when a PR is newly created. If this method is
* called on an instance whose mergeable state is not yet known, API call is made to retrieve the latest
* state.
* @throws IOException
* the io exception
*/
public Boolean getMergeable() throws IOException {
refresh(mergeable);
return mergeable;
}
/** for test purposes only */
@Deprecated
Boolean getMergeableNoRefresh() throws IOException {
return mergeable;
}
/**
* Gets deletions.
*
* @return the deletions
* @throws IOException
* the io exception
*/
public int getDeletions() throws IOException {
populate();
return deletions;
}
/**
* Gets mergeable state.
*
* @return the mergeable state
* @throws IOException
* the io exception
*/
public String getMergeableState() throws IOException {
populate();
return mergeable_state;
}
/**
* Gets changed files.
*
* @return the changed files
* @throws IOException
* the io exception
*/
public int getChangedFiles() throws IOException {
populate();
return changed_files;
}
public String getMergeCommitSha() throws IOException {
populate();
return merge_commit_sha;
}
/**
* Gets requested reviewers.
*
* @return the requested reviewers
* @throws IOException
* the io exception
*/
public List<GHUser> getRequestedReviewers() throws IOException {
refresh(requested_reviewers);
return Collections.unmodifiableList(Arrays.asList(requested_reviewers));
}
/**
* Gets requested teams.
*
* @return the requested teams
* @throws IOException
* the io exception
*/
public List<GHTeam> getRequestedTeams() throws IOException {
refresh(requested_teams);
return Collections.unmodifiableList(Arrays.asList(requested_teams));
}
/**
* Fully populate the data by retrieving missing data.
*
* <p>
* Depending on the original API call where this object is created, it may not contain everything.
*/
private void populate() throws IOException {
if (mergeable_state != null)
return; // already populated
refresh();
}
/** Repopulates this object. */
public void refresh() throws IOException {
if (isOffline()) {
return; // cannot populate, will have to live with what we have
}
URL url = getUrl();
if (url != null) {
root().createRequest().withPreview(SHADOW_CAT).setRawUrlPath(url.toString()).fetchInto(this).wrapUp(owner);
}
}
public PagedIterable<GHPullRequestFileDetail> listFiles() {
return root().createRequest()
.withUrlPath(String.format("%s/files", getApiRoute()))
.toIterable(GHPullRequestFileDetail[].class, null);
}
/**
* Retrieves all the reviews associated to this pull request.
*
* @return the paged iterable
*/
public PagedIterable<GHPullRequestReview> listReviews() {
return root().createRequest()
.withUrlPath(String.format("%s/reviews", getApiRoute()))
.toIterable(GHPullRequestReview[].class, item -> item.wrapUp(this));
}
/**
* Obtains all the review comments associated with this pull request.
*
* @return the paged iterable
* @throws IOException
* the io exception
*/
public PagedIterable<GHPullRequestReviewComment> listReviewComments() throws IOException {
return root().createRequest()
.withUrlPath(getApiRoute() + COMMENTS_ACTION)
.toIterable(GHPullRequestReviewComment[].class, item -> item.wrapUp(this));
}
/**
* Retrieves all the commits associated to this pull request.
*
* @return the paged iterable
*/
public PagedIterable<GHPullRequestCommitDetail> listCommits() {
return root().createRequest()
.withUrlPath(String.format("%s/commits", getApiRoute()))
.toIterable(GHPullRequestCommitDetail[].class, item -> item.wrapUp(this));
}
/**
* Create review gh pull request review.
*
* @param body
* the body
* @param event
* the event
* @param comments
* the comments
* @return the gh pull request review
* @throws IOException
* the io exception
* @deprecated Use {@link #createReview()}
*/
@Deprecated
public GHPullRequestReview createReview(String body,
@CheckForNull GHPullRequestReviewState event,
GHPullRequestReviewComment... comments) throws IOException {
return createReview(body, event, Arrays.asList(comments));
}
/**
* Create review gh pull request review.
*
* @param body
* the body
* @param event
* the event
* @param comments
* the comments
* @return the gh pull request review
* @throws IOException
* the io exception
* @deprecated Use {@link #createReview()}
*/
@Deprecated
public GHPullRequestReview createReview(String body,
@CheckForNull GHPullRequestReviewState event,
List<GHPullRequestReviewComment> comments) throws IOException {
GHPullRequestReviewBuilder b = createReview().body(body);
for (GHPullRequestReviewComment c : comments) {
b.comment(c.getBody(), c.getPath(), c.getPosition());
}
return b.create();
}
/**
* Create review gh pull request review builder.
*
* @return the gh pull request review builder
*/
public GHPullRequestReviewBuilder createReview() {
return new GHPullRequestReviewBuilder(this);
}
/**
* Create review comment gh pull request review comment.
*
* @param body
* the body
* @param sha
* the sha
* @param path
* the path
* @param position
* the position
* @return the gh pull request review comment
* @throws IOException
* the io exception
*/
public GHPullRequestReviewComment createReviewComment(String body, String sha, String path, int position)
throws IOException {
return root().createRequest()
.method("POST")
.with("body", body)
.with("commit_id", sha)
.with("path", path)
.with("position", position)
.withUrlPath(getApiRoute() + COMMENTS_ACTION)
.fetch(GHPullRequestReviewComment.class)
.wrapUp(this);
}
/**
* Request reviewers.
*
* @param reviewers
* the reviewers
* @throws IOException
* the io exception
*/
public void requestReviewers(List<GHUser> reviewers) throws IOException {
root().createRequest()
.method("POST")
.with("reviewers", getLogins(reviewers))
.withUrlPath(getApiRoute() + REQUEST_REVIEWERS)
.send();
}
/**
* Request team reviewers.
*
* @param teams
* the teams
* @throws IOException
* the io exception
*/
public void requestTeamReviewers(List<GHTeam> teams) throws IOException {
List<String> teamReviewers = new ArrayList<String>(teams.size());
for (GHTeam team : teams) {
teamReviewers.add(team.getSlug());
}
root().createRequest()
.method("POST")
.with("team_reviewers", teamReviewers)
.withUrlPath(getApiRoute() + REQUEST_REVIEWERS)
.send();
}
/**
* Set the base branch on the pull request
*
* @param newBaseBranch
* the name of the new base branch
* @throws IOException
* the io exception
* @return the updated pull request
*/
public GHPullRequest setBaseBranch(String newBaseBranch) throws IOException {
return root().createRequest()
.method("PATCH")
.with("base", newBaseBranch)
.withUrlPath(getApiRoute())
.fetch(GHPullRequest.class);
}
/**
* Updates the branch. The same as pressing the button in the web GUI.
*
* @throws IOException
* the io exception
*/
@Preview(LYDIAN)
public void updateBranch() throws IOException {
root().createRequest()
.withPreview(LYDIAN)
.method("PUT")
.with("expected_head_sha", head.getSha())
.withUrlPath(getApiRoute() + "/update-branch")
.send();
}
/**
* Merge this pull request.
*
* <p>
* The equivalent of the big green "Merge pull request" button.
*
* @param msg
* Commit message. If null, the default one will be used.
* @throws IOException
* the io exception
*/
public void merge(String msg) throws IOException {
merge(msg, null);
}
/**
* Merge this pull request.
*
* <p>
* The equivalent of the big green "Merge pull request" button.
*
* @param msg
* Commit message. If null, the default one will be used.
* @param sha
* SHA that pull request head must match to allow merge.
* @throws IOException
* the io exception
*/
public void merge(String msg, String sha) throws IOException {
merge(msg, sha, null);
}
/**
* Merge this pull request, using the specified merge method.
*
* <p>
* The equivalent of the big green "Merge pull request" button.
*
* @param msg
* Commit message. If null, the default one will be used.
* @param sha
* the sha
* @param method
* SHA that pull request head must match to allow merge.
* @throws IOException
* the io exception
*/
public void merge(String msg, String sha, MergeMethod method) throws IOException {
root().createRequest()
.method("PUT")
.with("commit_message", msg)
.with("sha", sha)
.with("merge_method", method)
.withUrlPath(getApiRoute() + "/merge")
.send();
}
/** The enum MergeMethod. */
public enum MergeMethod {
MERGE, SQUASH, REBASE
}
/**
* The status of auto merging a {@linkplain GHPullRequest}.
*
*/
@SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Field comes from JSON deserialization")
public static class AutoMerge {
private GHUser enabled_by;
private MergeMethod merge_method;
private String commit_title;
private String commit_message;
/**
* The user who enabled the auto merge of the pull request.
*
* @return the {@linkplain GHUser}
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior")
public GHUser getEnabledBy() {
return enabled_by;
}
/**
* The merge method of the auto merge.
*
* @return the {@linkplain MergeMethod}
*/
public MergeMethod getMergeMethod() {
return merge_method;
}
/**
* the title of the commit, if e.g. {@linkplain MergeMethod#SQUASH} is used for the auto merge.
*
* @return the title of the commit
*/
public String getCommitTitle() {
return commit_title;
}
/**
* the message of the commit, if e.g. {@linkplain MergeMethod#SQUASH} is used for the auto merge.
*
* @return the message of the commit
*/
public String getCommitMessage() {
return commit_message;
}
}
} |
package org.lantern.natty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.io.File;
import java.net.URI;
import java.util.concurrent.ThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* UDT client for sending a file.
*/
public class SendFileClient {
private final Logger log = LoggerFactory.getLogger(getClass());
private final File file;
private final URI local;
private final URI remote;
public SendFileClient(final URI localAddress, final URI remoteAddress,
final File file) {
this.local = localAddress;
this.remote = remoteAddress;
this.file = file;
}
public void run() throws Exception {
log.debug("Starting send file client... from {} to {}", local, remote);
// Configure the client.
final ThreadFactory connectFactory = new UtilThreadFactory("connect");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.BYTE_PROVIDER);
try {
final Bootstrap boot = new Bootstrap();
boot.group(connectGroup)
.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new SendFileClientHandler(file));
}
});
// Start the client.
log.debug("Binding to port {}", this.local.getPort());
boot.bind(this.local.getHost(), this.local.getPort());
final ChannelFuture f =
boot.connect(this.remote.getHost(), this.remote.getPort()).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
connectGroup.shutdownGracefully();
}
}
} |
package org.magellan.faleiro;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.ByteString;
import org.apache.mesos.Protos;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.BitSet;
import static org.magellan.faleiro.JsonTags.TaskData;
import static org.magellan.faleiro.JsonTags.VerboseStatus;
import static org.magellan.faleiro.JsonTags.SimpleStatus;
public class MagellanJob {
private static final Logger log = Logger.getLogger(MagellanJob.class.getName());
// These constants are used to tell the framework how much of each
private final double NUM_CPU;
private final double NUM_MEM;
private final double NUM_NET_MBPS;
private final double NUM_DISK;
private final int NUM_PORTS;
private final long jobID;
private final String jobName;
private final long jobStartingTime;
// How long each task runs for
private int jobTaskTime;
// The current best solution as determined by all the running tasks
private String jobCurrentBestSolution = "";
// The energy of the current best solution. In our system, a lower energy translates to a better solution
private double jobBestEnergy = Double.MAX_VALUE;
private String jobTaskName;
// Additional parameters passed in from the user
private JSONObject jobAdditionalParam = null;
// A list of the best energies found by every task run by this job.
private ConcurrentLinkedDeque<Double> energyHistory = new ConcurrentLinkedDeque<>();
// This list stores tasks that are ready to be scheduled. This list is then consumed by the
// MagellanFramework when it is ready to accept new tasks.
private BlockingQueue<MagellanTaskRequest> pendingTasks = new LinkedBlockingQueue<>();
// The number of tasks sent out. This number will be combined with the jobId to create a unique
// identifier for each task
//private int numTasksSent = 0;
//private int numFinishedTasks = 0;
// Each job is limited to sending out a certain number of tasks at a time. Currently, this is
// hardcoded to 10 but in time, this number should dynamically change depending on the number
// of jobs running in the system.
private JobState state = JobState.INITIALIZED;
private Protos.ExecutorInfo taskExecutor;
/* lock to wait for division task to complete */
private Object division_lock = new Object();
private Boolean division_is_done = false;
/* task ID of division, waiting until this is returned to make more tasks */
private String divisionTaskId;
/* json array of returned division. iterated through to make new tasks */
private JSONArray returnedResult;
private BitSet finishedTasks;
private int currentTask;
/**
*
* @param id Unique Job id
* @param jName Name of job
* @param taskName Name of the task we want to execute on the executor side
* @param jso Additional Job param
*/
public MagellanJob(long id,
String jName,
int taskTime,
String taskName,
JSONObject jso)
{
jobID = id;
jobName = jName;
jobTaskTime = taskTime;
jobTaskName = taskName;
jobAdditionalParam = jso;
taskExecutor = registerExecutor(System.getenv("EXECUTOR_PATH"));
jobStartingTime = System.currentTimeMillis();
NUM_CPU = 1;
NUM_MEM = 32;
NUM_NET_MBPS = 0;
NUM_DISK = 0;
NUM_PORTS = 0;
log.log(Level.CONFIG, "New Job created. ID is " + jobID);
}
/**
*
* @param j : JSONObject from zookeeper used for creating a new job on this framework based on
* the state of a job from another, deceased framework
*/
public MagellanJob(JSONObject j){
//Reload constants
NUM_CPU = j.getDouble(VerboseStatus.NUM_CPU);
NUM_MEM = j.getDouble(VerboseStatus.NUM_MEM);
NUM_NET_MBPS = j.getDouble(VerboseStatus.NUM_NET_MBPS);
NUM_DISK = j.getDouble(VerboseStatus.NUM_DISK);
NUM_PORTS = j.getInt(VerboseStatus.NUM_PORTS);
finishedTasks = (BitSet)j.get(VerboseStatus.BITFIELD_FINISHED);
jobID = j.getInt(SimpleStatus.JOB_ID);
jobStartingTime = j.getLong(SimpleStatus.JOB_STARTING_TIME);
jobName = j.getString(SimpleStatus.JOB_NAME);
jobTaskTime = j.getInt(SimpleStatus.TASK_SECONDS);
jobTaskName = j.getString(SimpleStatus.TASK_NAME);
jobCurrentBestSolution = j.getString(SimpleStatus.BEST_LOCATION);
jobBestEnergy = j.getDouble(SimpleStatus.BEST_ENERGY);
energyHistory = (new Gson()).fromJson(j.getString(SimpleStatus.ENERGY_HISTORY), new TypeToken<ConcurrentLinkedDeque<Double>>(){}.getType());
jobAdditionalParam = j.getJSONObject(SimpleStatus.ADDITIONAL_PARAMS);
state = (new Gson()).fromJson(j.getString(SimpleStatus.CURRENT_STATE), JobState.class);
taskExecutor = registerExecutor("/usr/local/bin/enrique");
log.log(Level.CONFIG, "Reviving job from zookeeper. State is " + state + " . Id is " + jobID);
}
/**
* Creates an executor object. This object will eventually be run on an agent when it get schedules
* @param pathToExecutor
* @return
*/
public Protos.ExecutorInfo registerExecutor(String pathToExecutor){
return Protos.ExecutorInfo.newBuilder()
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("default"))
.setCommand(Protos.CommandInfo.newBuilder().setValue(pathToExecutor))
.setName("SA Job Executor")
.setSource("java_test")
.build();
}
/**
* Runs the main loop in a separate thread
*/
public void start() {
state = JobState.RUNNING;
new Thread(() -> {
run();
}).start();
}
/**
* This functions creates tasks that are passed to the magellan framework using an annealing approach.
* We determine the starting location of each task using a temperature cooling mechanism where early on
* in the execution of this job, more risks are taken and more tasks run in random locations in an attempt
* to explore more of the search space. As time increases and the temperature of the job decreases, tasks
* are given starting locations much closer to the global, best solution for this job so that the neighbors
* of the best solution are evaluated thoroughly in the hopes that they lie close to the global maximum.
*/
private void run() {
/* first create the splitter task */
if(state == JobState.STOP) {
return;
}
while(state==JobState.PAUSED){
Thread.yield();
// wait while job is paused
}
try {
// To keep the task ids unique throughout the global job space, use the job ID to
// ensure uniqueness
String newTaskId = "" + jobID + "_" + "div";
// Choose the magellan specific parameters for the new task
//ByteString data = pickNewTaskStartingLocation(jobTaskTime, jobTaskName, newTaskId, jobAdditionalParam);
int divisions = 0;
JSONObject jsonTaskData = new JSONObject();
jsonTaskData.put(TaskData.UID, newTaskId);
jsonTaskData.put(TaskData.TASK_NAME, jobTaskName);
jsonTaskData.put(TaskData.TASK_COMMAND, TaskData.RESPONSE_DIVISIONS);
jsonTaskData.put(TaskData.JOB_DATA, jobAdditionalParam);
jsonTaskData.put(TaskData.TASK_DIVISIONS, divisions);
MagellanTaskRequest newTask = new MagellanTaskRequest(
newTaskId,
jobName,
NUM_CPU,
NUM_MEM,
NUM_NET_MBPS,
NUM_DISK,
NUM_PORTS,
ByteString.copyFromUtf8(jsonTaskData.toString()));
// Add the task to the pending queue until the framework requests it
pendingTasks.put(newTask);
divisionTaskId = newTaskId;
} catch (InterruptedException e) {
e.printStackTrace();
}
/* lock until notified that division has returned */
synchronized (division_lock) {
try {
while (!division_is_done) {
log.log(Level.INFO, "Waiting until leader elected");
division_lock.wait();
}
} catch (InterruptedException e) {
log.log(Level.SEVERE, e.getMessage());
}
}
/* got result of division task */
finishedTasks = new BitSet(returnedResult.length()); // initialize list of isFinished bits for each task. Persisted across crash.
for (currentTask = 0; currentTask < returnedResult.length(); currentTask++) {
while(state==JobState.PAUSED){
Thread.yield();
// wait while job is paused
}
if(state == JobState.STOP) {
return;
}
// check if this index was already completed in a previous run, if so skip it
if(!finishedTasks.get(currentTask)){
/* got a list of all the partitions, create a task for each */
try {
String newTaskId = "" + jobID + "_" + currentTask;
MagellanTaskRequest newTask = new MagellanTaskRequest(
newTaskId,
jobName,
NUM_CPU,
NUM_MEM,
NUM_NET_MBPS,
NUM_DISK,
NUM_PORTS,
packTaskData(newTaskId, jobTaskName, "anneal", jobTaskTime, jobAdditionalParam, returnedResult.get(currentTask))
);
// Add the task to the pending queue until the framework requests it
pendingTasks.put(newTask);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
log.log(Level.INFO, "Finished sending tasks. Waiting now. Tasks sent = " + returnedResult.length());
while(state != JobState.STOP && (returnedResult.length() != finishedTasks.cardinality())) {
// wait for all tasks to finish
Thread.yield();
}
state = JobState.DONE;
log.log(Level.INFO, "[Job " + jobID + "]" + " done. Best fitness (" + jobBestEnergy + ") achieved at location " + jobCurrentBestSolution);
}
/**
* Called by the magellan framework to get a list of tasks that this job wants scheduled.
* @return
*/
public ArrayList<MagellanTaskRequest> getPendingTasks(){
ArrayList<MagellanTaskRequest> pt = new ArrayList<>();
pendingTasks.drainTo(pt);
return pt;
}
/**
* Job is done if it terminates naturally or if it receives an explicit signal to stop
* @return
*/
public boolean isDone(){
return state == JobState.DONE || state == JobState.STOP;
}
/**
* Called by magellan framework when a message from the executor is sent to this job. This message
* could indicate that the task was successful, or failed.
* @param state : Indicates the status of the task. Could be TASK_FINISHED, TASK_ERROR, TASK_FAILED,
* TASK_LOST
* @param taskId : Id of the task
* @param data : Data of the task
*/
public void processIncomingMessages(Protos.TaskState state, String taskId, String data) {
log.log(Level.INFO, "processIncomingMessages: state: " + state + " , taskId: " + taskId + " , data: " + data);
switch (state) {
case TASK_ERROR:
case TASK_FAILED:
case TASK_LOST:
// TODO: recschedule this task
}
if(data == null){
return;
}
// Retrieve the data sent by the executor
JSONObject js = new JSONObject(data);
String returnedTaskId = js.getString(TaskData.UID);
if(returnedTaskId.equals(divisionTaskId)) {
synchronized (division_lock) {
/* parse out the result to get list of tasks */
returnedResult = js.getJSONArray(TaskData.RESPONSE_DIVISIONS);
division_is_done = true;
division_lock.notify();
}
return;
}
double fitness_score = js.getDouble(TaskData.FITNESS_SCORE);
String best_location = js.getString(TaskData.BEST_LOCATION);
String[] parts = returnedTaskId.split("_");
String strReturnedJobId = parts[0];
long returnedJobId = Integer.parseInt(strReturnedJobId);
String strReturnedTaskNum = parts[1];
int returnedTaskNum = Integer.parseInt(strReturnedTaskNum);
// check that task result is for me, should always be true
if(returnedJobId != this.jobID){
log.log(Level.SEVERE, "Job: " + getJobID() + " got task result meant for Job: " + returnedJobId);
System.exit(-1);
}
finishedTasks.set(returnedTaskNum); // mark task as finished. needed for zookeeper state revival
energyHistory.add(fitness_score);
// If a better score was discovered, make this our global, best location
if(fitness_score < jobBestEnergy) {
jobCurrentBestSolution = best_location;
jobBestEnergy = fitness_score;
}
log.log(Level.FINE, "Job: " + getJobID() + " processed finished task");
}
public void stop() {
log.log(Level.INFO, "Job: " + getJobID() + " asked to stop");
state = JobState.STOP;
}
public void pause() {
if(!isDone()) {
log.log(Level.INFO, "Job: " + getJobID() + " asked to pause");
state = JobState.PAUSED;
}
}
public void resume(){
if(!isDone()) {
log.log(Level.INFO, "Job: " + getJobID() + " asked to resume");
state = JobState.RUNNING;
}
}
/**
* Called by the zookeeper service to transfer a snapshot of the current state of the job to save in
* case this node goes down. This contains information from getSimpleStatus() as well as
* additional, internal information
*
* @return A snapshot of all the important information in this job
*/
public JSONObject getStateSnapshot() {
JSONObject jsonObj = getSimpleStatus();
// Store constants
jsonObj.put(VerboseStatus.NUM_CPU, NUM_CPU);
jsonObj.put(VerboseStatus.NUM_MEM, NUM_MEM);
jsonObj.put(VerboseStatus.NUM_NET_MBPS, NUM_NET_MBPS);
jsonObj.put(VerboseStatus.NUM_DISK, NUM_DISK);
jsonObj.put(VerboseStatus.NUM_PORTS, NUM_PORTS);
jsonObj.put(VerboseStatus.BITFIELD_FINISHED, finishedTasks);
return jsonObj;
}
/**
* This method returns information that the client wants to know about the job
* @return
*/
public JSONObject getSimpleStatus() {
JSONObject jsonObj = new JSONObject();
jsonObj.put(SimpleStatus.JOB_ID, getJobID());
jsonObj.put(SimpleStatus.JOB_NAME, getJobName());
jsonObj.put(SimpleStatus.JOB_STARTING_TIME, getStartingTime());
jsonObj.put(SimpleStatus.TASK_SECONDS, getTaskTime());
jsonObj.put(SimpleStatus.TASK_NAME, getJobTaskName());
jsonObj.put(SimpleStatus.BEST_LOCATION, getBestLocation());
jsonObj.put(SimpleStatus.BEST_ENERGY, getBestEnergy());
jsonObj.put(SimpleStatus.ENERGY_HISTORY, new JSONArray(getEnergyHistory()));
jsonObj.put(SimpleStatus.NUM_FINISHED_TASKS, getNumFinishedTasks());
jsonObj.put(SimpleStatus.NUM_TOTAL_TASKS, getNumTotalTasks());
jsonObj.put(SimpleStatus.ADDITIONAL_PARAMS, getJobAdditionalParam());
jsonObj.put(SimpleStatus.CURRENT_STATE, getState());
return jsonObj;
}
/**
* Takes the given parameters and packages it into a json formatted Bytestring which can be
* packaged into a TaskInfo object by the magellan framework
* @param newTaskId
* @param jobTaskName
* @param command
* @param jobAdditionalParam
* @param taskData
* @return
*/
private ByteString packTaskData(String newTaskId, String jobTaskName, String command, int taskTime, JSONObject jobAdditionalParam, Object taskData){
JSONObject jsonTaskData = new JSONObject();
jsonTaskData.put(TaskData.UID, newTaskId);
jsonTaskData.put(TaskData.TASK_NAME, jobTaskName);
jsonTaskData.put(TaskData.TASK_COMMAND, command);
jsonTaskData.put(TaskData.MINUTES_PER_DIVISION, taskTime);
jsonTaskData.put(TaskData.JOB_DATA, jobAdditionalParam);
jsonTaskData.put(TaskData.TASK_DATA, taskData);
return ByteString.copyFromUtf8(jsonTaskData.toString());
}
enum JobState{
INITIALIZED, RUNNING, PAUSED, STOP, DONE;
}
/* List of getter methods that will be called to store the state of this job*/
public JobState getState(){return state;}
public long getJobID() {return jobID;}
public String getJobName() {return jobName;}
public double getTaskTime(){ return jobTaskTime; }
public String getJobTaskName() {return jobTaskName;}
public JSONObject getJobAdditionalParam(){ return jobAdditionalParam; }
public String getBestLocation() { return jobCurrentBestSolution; }
public double getBestEnergy() { return jobBestEnergy; }
public Long getStartingTime() { return jobStartingTime; }
public Queue<Double> getEnergyHistory() { return energyHistory; }
public Protos.ExecutorInfo getTaskExecutor() { return taskExecutor; }
public int getNumFinishedTasks(){
if(division_is_done){
return finishedTasks.cardinality();
}else{
return 0;
}
}
public int getNumTasksSent(){ return currentTask;}
public int getNumTotalTasks() {
if(division_is_done){
return returnedResult.length();
}else{
return -1; // number of total tasks is unknown, job has not been divided into tasks yet
}
}
} |
package org.oscii.neural;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.oscii.concordance.SentenceExample;
import org.oscii.lex.Lexicon;
import org.oscii.lex.Order;
import org.oscii.math.VectorMath;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Manages a collection of language-specific word2vec models.
*
* @author Sasa Hasan
* @author Spence Green
*/
public class Word2VecManager {
private final static Logger logger = LogManager.getLogger(Word2VecManager.class);
private static final int MIN_SEG_LEN = 25; // minimum segment length to activate reduction
private static final int MIN_TOK_LEN = 5; // minimum token length to denote a candidate
private static final int MAX_RES_LEN = 50; // maximum length of resulting reduced output
private final Map<String, EmbeddingContainer> models;
/**
* Constructor.
*/
public Word2VecManager() {
this.models = new HashMap<>();
}
/**
* Adds a word2vec model from a binary model file for given language.
*
* @param lang
* @param file
* @return true if model was added successfully, else false
*/
public boolean add(String lang, File file) throws IOException {
logger.info("Loading {} embeddings from {}", lang, file);
EmbeddingContainer model = EmbeddingContainer.fromBinFile(file);
put(lang, model);
return true;
}
private void put(String lang, EmbeddingContainer model) {
models.put(lang, model);
}
public boolean hasModels() {
return !models.isEmpty();
}
public boolean supports(String lang) {
return models.containsKey(lang);
}
/**
* Checks whether the query is part of model for given language.
*
* @param lang
* @param query
*/
public boolean containsQuery(String lang, String query) {
return supports(lang) && models.get(lang).contains(query);
}
/**
* Checks whether the degraded query (e.g. lowercased) is part of
* model for given language.
*
* @param lang
* @param query
*/
public boolean containsDegradedQuery(String lang, String query) {
return supports(lang) && models.get(lang).contains(Lexicon.degrade(query));
}
/**
* Returns the query or degraded query if it is part of the model
* for a given language. Throws UnknownWordException if not.
*
* @param lang
* @param query
*/
public String getMatchingQuery(String lang, String query) {
if (containsQuery(lang, query)) {
return query;
} else if (containsDegradedQuery(lang, query)) {
return Lexicon.degrade(query);
} else {
return null;
}
}
/**
* Ranks a list of concordance entries by calculating the similarity of each
* example's mean vector to the mean vector of the context. The
* result is sorted according to distance/similarity. In order to
* reduce computation time, the candidates are reduced in size by
* filtering out short entries (likely stop words) and truncating
* the result to a maximum number of entries.
*
* @param lang
* @param context
* @param concordances
*/
public boolean rankConcordances(String lang, String context, List<SentenceExample> concordances) {
if (!supports(lang) || context.length() == 0 || concordances.size() == 0) {
return false;
}
final EmbeddingContainer model = models.get(lang);
// retrieve and score context; replaceAll() strips all punctuation
String[] contextTokens = reduceTokens(context.replaceAll("\\p{P}", "").split("\\s+"), MIN_SEG_LEN, MIN_TOK_LEN, MAX_RES_LEN);
float[] contextMean = model.getMean(contextTokens);
logger.info("context={} ({})", contextTokens, contextTokens.length);
// iterate over concordance results
concordances.forEach(ex -> {
String[] tokens = reduceTokens(ex.sentence.tokens, MIN_SEG_LEN, MIN_TOK_LEN, MAX_RES_LEN);
float[] tokensMean = model.getMean(tokens);
logger.debug("means: tokens=[{},{},{},...] context=[{},{},{},...]",
tokensMean[0], tokensMean[1], tokensMean[2],
contextMean[0], contextMean[1], contextMean[2]);
try {
double sim = VectorMath.cosineSimilarity(tokensMean, contextMean);
if (Double.isNaN(sim)) {
sim = -2.0; // Give it a low score.
}
ex.similarity = sim;
} catch(Exception e) {
logger.warn("Zero vector for concordance ranking");
ex.similarity = -2.0; // Give it a low score.
}
logger.debug("distance: {}", ex.similarity);
});
// rerank according to word2vec similarities
Collections.sort(concordances, Order.bySimilarity);
logger.info("top similarity: {}", concordances.get(0).similarity);
return true;
}
/**
* Returns the averaged raw word vector (n-dimensional array of
* doubles) for given query and language. Applies tokenization
* through punctuation removal and reducing into a bag of words.
*
* @param lang
* @param query
*/
public float[] getRawVector(String lang, String query) throws UnsupportedLanguageException {
if (!supports(lang)) throw new UnsupportedLanguageException(lang);
String[] bagOfWords = getBagOfWords(query.replaceAll("\\p{P}", "").split("\\s+"));
logger.debug("BOW: {}", Arrays.toString(bagOfWords));
return models.get(lang).getMean(bagOfWords);
}
/**
* Get the mean vector for
* @param lang
* @param query
* @return
* @throws UnsupportedLanguageException
*/
public float[] getMeanVector(String lang, String[] query) throws UnsupportedLanguageException {
if (!supports(lang)) throw new UnsupportedLanguageException(lang);
return models.get(lang).getMean(query);
}
/**
* Returns the similarity (cosine distance) between two strings for
* the given language. If query2 is of length 0, the method expects
* a '|||'-delimited query pair in query1, e.g. "dog|||cat", or
* throws a MalformedQueryException else. The query is degraded if
* needed (see {@link Lexicon.degrade}).
*
* @param lang
* @param query1
* @param query2
*/
public double getSimilarity(String lang, String query1, String query2) throws
UnsupportedLanguageException, MalformedQueryException {
if (!supports(lang)) throw new UnsupportedLanguageException(lang);
if (query2.length() == 0) {
String[] splitQuery = query1.trim().split("\\|\\|\\|");
if (splitQuery.length == 2) {
query1 = getMatchingQuery(lang, splitQuery[0].trim());
query2 = getMatchingQuery(lang, splitQuery[1].trim());
} else {
throw new MalformedQueryException(query1);
}
}
if (query1 == null || query2 == null) return -1.0;
float[] v1 = getRawVector(lang, query1);
float[] v2 = getRawVector(lang, query2);
return VectorMath.cosineSimilarity(v1, v2);
}
/**
* Heuristically reduce the array of tokens to "content" words,
* limiting the result in size.
*
* - Filters short tokens (tokens of length < minTokLength).
* - Limits the result to maxSegLength entries.
* - Filters duplicates.
*
* @param tokens
* @param minSegLength
* @param minTokLength
* @param maxSegLength
*/
public static String[] reduceTokens(String[] tokens, int minSegLength, int minTokLength, int maxSegLength) {
if (tokens.length < minSegLength) {
return tokens.clone();
}
Set<String> tokset = new HashSet<>();
for (int i = 0; i < tokens.length; ++i) {
if (tokens[i].length() >= minTokLength) {
tokset.add(tokens[i]);
}
if (tokset.size() >= maxSegLength) {
break;
}
}
if (tokset.size() == 0) {
return tokens.clone();
} else {
return tokset.toArray(new String[tokset.size()]);
}
}
/**
* Returns bag-of-words for given token sequence.
*
* @param tokens
*/
public static String[] getBagOfWords(String[] tokens) {
Set<String> tokset = new HashSet<>();
for (String token : tokens) {
tokset.add(token);
}
return tokset.toArray(new String[tokset.size()]);
}
/**
* Exception when a language is not supported.
*/
public static class UnsupportedLanguageException extends Exception {
private static final long serialVersionUID = -5764353544971858767L;
public UnsupportedLanguageException(String lang) {
super(String.format("Unsupported language '%s'", lang));
}
}
/**
* Exception when a query is malformed.
*/
public static class MalformedQueryException extends Exception {
private static final long serialVersionUID = 8933002861674016549L;
public MalformedQueryException(String query) {
super(String.format("Malformed query '%s'", query));
}
}
} |
package org.scijava.io.handle;
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.scijava.io.location.Location;
import org.scijava.plugin.WrapperPlugin;
/**
* A <em>data handle</em> is a plugin which provides both streaming and random
* access to bytes at a {@link Location} (e.g., files or arrays).
*
* @author Curtis Rueden
* @see DataHandleInputStream
* @see DataHandleOutputStream
*/
public interface DataHandle<L extends Location> extends WrapperPlugin<L>,
DataInput, DataOutput, Closeable
{
/** Default block size to use when searching through the stream. */
int DEFAULT_BLOCK_SIZE = 256 * 1024; // 256 KB
/** Default bound on bytes to search when searching through the stream. */
int MAX_SEARCH_SIZE = 512 * 1024 * 1024; // 512 MB
/** Returns the current offset in the stream. */
long offset() throws IOException;
/**
* Sets the stream offset, measured from the beginning of the stream, at which
* the next read or write occurs.
*/
void seek(long pos) throws IOException;
/** Returns the length of the stream. */
long length() throws IOException;
/**
* Sets the new length of the handle.
*
* @param length New length.
* @throws IOException If there is an error changing the handle's length.
*/
void setLength(long length) throws IOException;
/**
* Verifies that the handle has sufficient bytes available to read, returning
* the actual number of bytes which will be possible to read, which might
* be less than the requested value.
*
* @param count Number of bytes to read.
* @return The actual number of bytes available to be read.
* @throws IOException If something goes wrong with the check.
*/
default long available(final long count) throws IOException {
final long remain = length() - offset();
return remain < count ? remain : count;
}
/**
* Ensures that the handle has sufficient bytes available to read.
*
* @param count Number of bytes to read.
* @see #available(long)
* @throws EOFException If there are insufficient bytes available.
* @throws IOException If something goes wrong with the check.
*/
default void ensureReadable(final long count) throws IOException {
if (available(count) < count) throw new EOFException();
}
/**
* Ensures that the handle has the correct length to be written to and extends
* it as required.
*
* @param count Number of bytes to write.
* @return {@code true} if the handle's length was sufficient, or
* {@code false} if the handle's length required an extension.
* @throws IOException If something goes wrong with the check, or there is an
* error changing the handle's length.
*/
default boolean ensureWritable(final long count) throws IOException {
final long minLength = offset() + count;
if (length() < minLength) {
setLength(minLength);
return false;
}
return true;
}
/** Returns the byte order of the stream. */
ByteOrder getOrder();
/**
* Sets the byte order of the stream.
*
* @param order Order to set.
*/
void setOrder(ByteOrder order);
/**
* Returns true iff the stream's order is {@link ByteOrder#BIG_ENDIAN}.
*
* @see #getOrder()
*/
default boolean isBigEndian() {
return getOrder() == ByteOrder.BIG_ENDIAN;
}
/**
* Returns true iff the stream's order is {@link ByteOrder#LITTLE_ENDIAN}.
*
* @see #getOrder()
*/
default boolean isLittleEndian() {
return getOrder() == ByteOrder.LITTLE_ENDIAN;
}
/**
* Sets the endianness of the stream.
*
* @param little If true, sets the order to {@link ByteOrder#LITTLE_ENDIAN};
* otherwise, sets the order to {@link ByteOrder#BIG_ENDIAN}.
* @see #setOrder(ByteOrder)
*/
default void setLittleEndian(final boolean little) {
setOrder(little ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
}
/** Gets the native encoding of the stream. */
String getEncoding();
/** Sets the native encoding of the stream. */
void setEncoding(String encoding);
/**
* Reads up to {@code buf.remaining()} bytes of data from the stream into a
* {@link ByteBuffer}.
*/
default int read(final ByteBuffer buf) throws IOException {
return read(buf, buf.remaining());
}
/**
* Reads up to {@code len} bytes of data from the stream into a
* {@link ByteBuffer}.
*
* @return the total number of bytes read into the buffer.
*/
default int read(final ByteBuffer buf, final int len) throws IOException {
final int n;
if (buf.hasArray()) {
// read directly into the array
n = read(buf.array(), buf.arrayOffset(), len);
}
else {
// read into a temporary array, then copy
final byte[] b = new byte[len];
n = read(b);
buf.put(b, 0, n);
}
return n;
}
/**
* Writes up to {@code buf.remaining()} bytes of data from the given
* {@link ByteBuffer} to the stream.
*/
default void write(final ByteBuffer buf) throws IOException {
write(buf, buf.remaining());
}
/**
* Writes up to len bytes of data from the given ByteBuffer to the stream.
*/
default void write(final ByteBuffer buf, final int len)
throws IOException
{
if (buf.hasArray()) {
// write directly from the buffer's array
write(buf.array(), buf.arrayOffset(), len);
}
else {
// copy into a temporary array, then write
final byte[] b = new byte[len];
buf.get(b);
write(b);
}
}
/** Reads a string of arbitrary length, terminated by a null char. */
default String readCString() throws IOException {
final String line = findString("\0");
return line.length() == 0 ? null : line;
}
/** Reads a string of up to length n. */
default String readString(final int n) throws IOException {
final int r = (int) available(n);
final byte[] b = new byte[r];
readFully(b);
return new String(b, getEncoding());
}
/**
* Reads a string ending with one of the characters in the given string.
*
* @see #findString(String...)
*/
default String readString(final String lastChars) throws IOException {
if (lastChars.length() == 1) return findString(lastChars);
final String[] terminators = new String[lastChars.length()];
for (int i = 0; i < terminators.length; i++) {
terminators[i] = lastChars.substring(i, i + 1);
}
return findString(terminators);
}
/**
* Reads a string ending with one of the given terminating substrings.
*
* @param terminators The strings for which to search.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
default String findString(final String... terminators) throws IOException {
return findString(true, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads or skips a string ending with one of the given terminating
* substrings.
*
* @param saveString Whether to collect the string from the current offset to
* the terminating bytes, and return it. If false, returns null.
* @param terminators The strings for which to search.
* @throws IOException If saveString flag is set and the maximum search length
* (512 MB) is exceeded.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
default String findString(final boolean saveString,
final String... terminators) throws IOException
{
return findString(saveString, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads a string ending with one of the given terminating substrings, using
* the specified block size for buffering.
*
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
default String findString(final int blockSize, final String... terminators)
throws IOException
{
return findString(true, blockSize, terminators);
}
/**
* Reads or skips a string ending with one of the given terminating
* substrings, using the specified block size for buffering.
*
* @param saveString Whether to collect the string from the current offset
* to the terminating bytes, and return it. If false, returns null.
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
* @throws IOException If saveString flag is set and the maximum search length
* (512 MB) is exceeded.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
default String findString(final boolean saveString, final int blockSize,
final String... terminators) throws IOException
{
final StringBuilder out = new StringBuilder();
final long startPos = offset();
long bytesDropped = 0;
final long inputLen = length();
long maxLen = inputLen - startPos;
final boolean tooLong = saveString && maxLen > MAX_SEARCH_SIZE;
if (tooLong) maxLen = MAX_SEARCH_SIZE;
boolean match = false;
int maxTermLen = 0;
for (final String term : terminators) {
final int len = term.length();
if (len > maxTermLen) maxTermLen = len;
}
@SuppressWarnings("resource")
final InputStreamReader in =
new InputStreamReader(new DataHandleInputStream<>(this), getEncoding());
final char[] buf = new char[blockSize];
long loc = 0;
while (loc < maxLen && offset() < length() - 1) {
// if we're not saving the string, drop any old, unnecessary output
if (!saveString) {
final int outLen = out.length();
if (outLen >= maxTermLen) {
final int dropIndex = outLen - maxTermLen + 1;
final String last = out.substring(dropIndex, outLen);
out.setLength(0);
out.append(last);
bytesDropped += dropIndex;
}
}
// read block from stream
final int r = in.read(buf, 0, blockSize);
if (r <= 0) throw new IOException("Cannot read from stream: " + r);
// append block to output
out.append(buf, 0, r);
// check output, returning smallest possible string
int min = Integer.MAX_VALUE, tagLen = 0;
for (final String t : terminators) {
final int len = t.length();
final int start = (int) (loc - bytesDropped - len);
final int value = out.indexOf(t, start < 0 ? 0 : start);
if (value >= 0 && value < min) {
match = true;
min = value;
tagLen = len;
}
}
if (match) {
// reset stream to proper location
seek(startPos + bytesDropped + min + tagLen);
// trim output string
if (saveString) {
out.setLength(min + tagLen);
return out.toString();
}
return null;
}
loc += r;
}
// no match
if (tooLong) throw new IOException("Maximum search length reached.");
return saveString ? out.toString() : null;
}
// -- InputStream look-alikes --
/**
* Reads the next byte of data from the stream.
*
* @return the next byte of data, or -1 if the end of the stream is reached.
* @throws IOException - if an I/O error occurs.
*/
default int read() throws IOException {
return offset() < length() ? readByte() & 0xff : -1;
}
/**
* Reads up to b.length bytes of data from the stream into an array of bytes.
*
* @return the total number of bytes read into the buffer.
*/
default int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Reads up to len bytes of data from the stream into an array of bytes.
*
* @return the total number of bytes read into the buffer.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Skips over and discards {@code n} bytes of data from the stream. The
* {@code skip} method may, for a variety of reasons, end up skipping over
* some smaller number of bytes, possibly {@code 0}. This may result from any
* of a number of conditions; reaching end of file before {@code n} bytes have
* been skipped is only one possibility. The actual number of bytes skipped is
* returned. If {@code n} is negative, no bytes are skipped.
*
* @param n - the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @throws IOException - if an I/O error occurs.
*/
default long skip(final long n) throws IOException {
final long skip = available(n);
if (skip <= 0) return 0;
seek(offset() + skip);
return skip;
}
// -- DataInput methods --
@Override
default void readFully(final byte[] b) throws IOException {
readFully(b, 0, b.length);
}
@Override
default void readFully(final byte[] b, final int off, final int len)
throws IOException
{
// NB: Adapted from java.io.DataInputStream.readFully(byte[], int, int).
if (len < 0) throw new IndexOutOfBoundsException();
int n = 0;
while (n < len) {
int count = read(b, off + n, len - n);
if (count < 0) throw new EOFException();
n += count;
}
}
@Override
default int skipBytes(final int n) throws IOException {
// NB: Cast here is safe since the value of n bounds the result to an int.
final int skip = (int) available(n);
if (skip < 0) return 0;
seek(offset() + skip);
return skip;
}
@Override
default boolean readBoolean() throws IOException {
return readByte() != 0;
}
@Override
default int readUnsignedByte() throws IOException {
return readByte() & 0xff;
}
@Override
default short readShort() throws IOException {
final int ch1 = read();
final int ch2 = read();
if ((ch1 | ch2) < 0) throw new EOFException();
return (short) ((ch1 << 8) + (ch2 << 0));
}
@Override
default int readUnsignedShort() throws IOException {
return readShort() & 0xffff;
}
@Override
default char readChar() throws IOException {
return (char) readShort();
}
@Override
default int readInt() throws IOException {
int ch1 = read();
int ch2 = read();
int ch3 = read();
int ch4 = read();
if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
@Override
default long readLong() throws IOException {
int ch1 = read();
int ch2 = read();
int ch3 = read();
int ch4 = read();
int ch5 = read();
int ch6 = read();
int ch7 = read();
int ch8 = read();
if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) {
throw new EOFException();
}
// TODO: Double check this inconsistent code.
return ((long) ch1 << 56) +
((long) (ch2 & 255) << 48) +
((long) (ch3 & 255) << 40) +
((long) (ch4 & 255) << 32) +
((long) (ch5 & 255) << 24) +
((ch6 & 255) << 16) +
((ch7 & 255) << 8) +
((ch8 & 255) << 0);
}
@Override
default float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
@Override
default double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
@Override
default String readLine() throws IOException {
// NB: Adapted from java.io.RandomAccessFile.readLine().
final StringBuffer input = new StringBuffer();
int c = -1;
boolean eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = offset();
if (read() != '\n') seek(cur);
break;
default:
input.append((char)c);
break;
}
}
if (c == -1 && input.length() == 0) {
return null;
}
return input.toString();
}
@Override
default String readUTF() throws IOException {
final int length = readUnsignedShort();
final byte[] b = new byte[length];
read(b);
return new String(b, "UTF-8");
}
// -- DataOutput methods --
@Override
default void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
default void writeBoolean(final boolean v) throws IOException {
write(v ? 1 : 0);
}
@Override
default void writeByte(final int v) throws IOException {
write(v);
}
@Override
default void writeChar(final int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
@Override
default void writeInt(final int v) throws IOException {
write((v >>> 24) & 0xFF);
write((v >>> 16) & 0xFF);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
@Override
default void writeLong(final long v) throws IOException {
write((byte) (v >>> 56));
write((byte) (v >>> 48));
write((byte) (v >>> 40));
write((byte) (v >>> 32));
write((byte) (v >>> 24));
write((byte) (v >>> 16));
write((byte) (v >>> 8));
write((byte) (v >>> 0));
}
@Override
default void writeFloat(final float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
@Override
default void writeDouble(final double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
@Override
default void writeBytes(final String s) throws IOException {
write(s.getBytes("UTF-8"));
}
@Override
default void writeUTF(final String str) throws IOException {
final byte[] b = str.getBytes("UTF-8");
writeShort(b.length);
write(b);
}
} |
package org.twuni.common.net.http;
import org.twuni.common.Filter;
import org.twuni.common.net.http.responder.RequestMapping;
import org.twuni.common.net.http.responder.Responder;
import org.twuni.common.net.http.response.Response;
import org.twuni.common.net.http.response.filter.DateFilter;
public class Server extends org.twuni.common.net.Server {
public Server( int port, Filter<Response> filter, Class<?>... annotatedClasses ) {
this( port, new RequestMapping( annotatedClasses ), filter );
}
public Server( int port, Class<?>... annotatedClasses ) {
this( port, new RequestMapping( annotatedClasses ) );
}
public Server( int port, Responder responder ) {
this( port, responder, new DateFilter() );
}
public Server( int port, Responder responder, Filter<Response> filter ) {
super( port, new WorkerFactory( responder, filter ) );
}
} |
package pl.mjasion.springdata.model;
import org.joda.time.DateTime;
import pl.mjasion.springdata.model.entity.AbstractEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
/**
* @author Marcin Jasion <marcin.jasion@gmail.com>
*/
@Entity
public class Post extends AbstractEntity {
private String title;
@Column(columnDefinition = "text")
private String text;
private DateTime dateAdded = DateTime.now();
@ManyToOne
private User author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public DateTime getDateAdded() {
return dateAdded;
}
public void setDateAdded(DateTime dateAdded) {
this.dateAdded = dateAdded;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
} |
package redis.clients.jedis;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
public class ShardedJedis extends BinaryShardedJedis implements JedisCommands {
public ShardedJedis(List<JedisShardInfo> shards) {
super(shards);
}
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
super(shards, algo);
}
public ShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
super(shards, keyTagPattern);
}
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) {
super(shards, algo, keyTagPattern);
}
public String set(String key, String value) {
Jedis j = getShard(key);
return j.set(key, value);
}
@Override
public String set(String key, String value, String nxxx,
String expx, long time) {
Jedis j = getShard(key);
return j.set(key, value, nxxx, expx, time);
}
public String get(String key) {
Jedis j = getShard(key);
return j.get(key);
}
public String echo(String string) {
Jedis j = getShard(string);
return j.echo(string);
}
public Boolean exists(String key) {
Jedis j = getShard(key);
return j.exists(key);
}
public String type(String key) {
Jedis j = getShard(key);
return j.type(key);
}
public Long expire(String key, int seconds) {
Jedis j = getShard(key);
return j.expire(key, seconds);
}
public Long expireAt(String key, long unixTime) {
Jedis j = getShard(key);
return j.expireAt(key, unixTime);
}
public Long ttl(String key) {
Jedis j = getShard(key);
return j.ttl(key);
}
public Boolean setbit(String key, long offset, boolean value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean setbit(String key, long offset, String value) {
Jedis j = getShard(key);
return j.setbit(key, offset, value);
}
public Boolean getbit(String key, long offset) {
Jedis j = getShard(key);
return j.getbit(key, offset);
}
public Long setrange(String key, long offset, String value) {
Jedis j = getShard(key);
return j.setrange(key, offset, value);
}
public String getrange(String key, long startOffset, long endOffset) {
Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset);
}
public String getSet(String key, String value) {
Jedis j = getShard(key);
return j.getSet(key, value);
}
public Long setnx(String key, String value) {
Jedis j = getShard(key);
return j.setnx(key, value);
}
public String setex(String key, int seconds, String value) {
Jedis j = getShard(key);
return j.setex(key, seconds, value);
}
public List<String> blpop(String arg) {
Jedis j = getShard(arg);
return j.blpop(arg);
}
public List<String> brpop(String arg) {
Jedis j = getShard(arg);
return j.brpop(arg);
}
public Long decrBy(String key, long integer) {
Jedis j = getShard(key);
return j.decrBy(key, integer);
}
public Long decr(String key) {
Jedis j = getShard(key);
return j.decr(key);
}
public Long incrBy(String key, long integer) {
Jedis j = getShard(key);
return j.incrBy(key, integer);
}
public Long incr(String key) {
Jedis j = getShard(key);
return j.incr(key);
}
public Long append(String key, String value) {
Jedis j = getShard(key);
return j.append(key, value);
}
public String substr(String key, int start, int end) {
Jedis j = getShard(key);
return j.substr(key, start, end);
}
public Long hset(String key, String field, String value) {
Jedis j = getShard(key);
return j.hset(key, field, value);
}
public String hget(String key, String field) {
Jedis j = getShard(key);
return j.hget(key, field);
}
public Long hsetnx(String key, String field, String value) {
Jedis j = getShard(key);
return j.hsetnx(key, field, value);
}
public String hmset(String key, Map<String, String> hash) {
Jedis j = getShard(key);
return j.hmset(key, hash);
}
public List<String> hmget(String key, String... fields) {
Jedis j = getShard(key);
return j.hmget(key, fields);
}
public Long hincrBy(String key, String field, long value) {
Jedis j = getShard(key);
return j.hincrBy(key, field, value);
}
public Boolean hexists(String key, String field) {
Jedis j = getShard(key);
return j.hexists(key, field);
}
public Long del(String key) {
Jedis j = getShard(key);
return j.del(key);
}
public Long hdel(String key, String... fields) {
Jedis j = getShard(key);
return j.hdel(key, fields);
}
public Long hlen(String key) {
Jedis j = getShard(key);
return j.hlen(key);
}
public Set<String> hkeys(String key) {
Jedis j = getShard(key);
return j.hkeys(key);
}
public List<String> hvals(String key) {
Jedis j = getShard(key);
return j.hvals(key);
}
public Map<String, String> hgetAll(String key) {
Jedis j = getShard(key);
return j.hgetAll(key);
}
public Long rpush(String key, String... strings) {
Jedis j = getShard(key);
return j.rpush(key, strings);
}
public Long lpush(String key, String... strings) {
Jedis j = getShard(key);
return j.lpush(key, strings);
}
public Long lpushx(String key, String... string) {
Jedis j = getShard(key);
return j.lpushx(key, string);
}
public Long strlen(final String key) {
Jedis j = getShard(key);
return j.strlen(key);
}
public Long move(String key, int dbIndex) {
Jedis j = getShard(key);
return j.move(key, dbIndex);
}
public Long rpushx(String key, String... string) {
Jedis j = getShard(key);
return j.rpushx(key, string);
}
public Long persist(final String key) {
Jedis j = getShard(key);
return j.persist(key);
}
public Long llen(String key) {
Jedis j = getShard(key);
return j.llen(key);
}
public List<String> lrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.lrange(key, start, end);
}
public String ltrim(String key, long start, long end) {
Jedis j = getShard(key);
return j.ltrim(key, start, end);
}
public String lindex(String key, long index) {
Jedis j = getShard(key);
return j.lindex(key, index);
}
public String lset(String key, long index, String value) {
Jedis j = getShard(key);
return j.lset(key, index, value);
}
public Long lrem(String key, long count, String value) {
Jedis j = getShard(key);
return j.lrem(key, count, value);
}
public String lpop(String key) {
Jedis j = getShard(key);
return j.lpop(key);
}
public String rpop(String key) {
Jedis j = getShard(key);
return j.rpop(key);
}
public Long sadd(String key, String... members) {
Jedis j = getShard(key);
return j.sadd(key, members);
}
public Set<String> smembers(String key) {
Jedis j = getShard(key);
return j.smembers(key);
}
public Long srem(String key, String... members) {
Jedis j = getShard(key);
return j.srem(key, members);
}
public String spop(String key) {
Jedis j = getShard(key);
return j.spop(key);
}
public Long scard(String key) {
Jedis j = getShard(key);
return j.scard(key);
}
public Boolean sismember(String key, String member) {
Jedis j = getShard(key);
return j.sismember(key, member);
}
public String srandmember(String key) {
Jedis j = getShard(key);
return j.srandmember(key);
}
public Long zadd(String key, double score, String member) {
Jedis j = getShard(key);
return j.zadd(key, score, member);
}
public Long zadd(String key, Map<String, Double> scoreMembers) {
Jedis j = getShard(key);
return j.zadd(key, scoreMembers);
}
public Set<String> zrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrange(key, start, end);
}
public Long zrem(String key, String... members) {
Jedis j = getShard(key);
return j.zrem(key, members);
}
public Double zincrby(String key, double score, String member) {
Jedis j = getShard(key);
return j.zincrby(key, score, member);
}
public Long zrank(String key, String member) {
Jedis j = getShard(key);
return j.zrank(key, member);
}
public Long zrevrank(String key, String member) {
Jedis j = getShard(key);
return j.zrevrank(key, member);
}
public Set<String> zrevrange(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrange(key, start, end);
}
public Set<Tuple> zrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end);
}
public Set<Tuple> zrevrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end);
}
public Long zcard(String key) {
Jedis j = getShard(key);
return j.zcard(key);
}
public Double zscore(String key, String member) {
Jedis j = getShard(key);
return j.zscore(key, member);
}
public List<String> sort(String key) {
Jedis j = getShard(key);
return j.sort(key);
}
public List<String> sort(String key, SortingParams sortingParameters) {
Jedis j = getShard(key);
return j.sort(key, sortingParameters);
}
public Long zcount(String key, double min, double max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Long zcount(String key, String min, String max) {
Jedis j = getShard(key);
return j.zcount(key, min, max);
}
public Set<String> zrangeByScore(String key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<String> zrevrangeByScore(String key, double max, double min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<String> zrangeByScore(String key, double min, double max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<String> zrevrangeByScore(String key, double max, double min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrangeByScoreWithScores(String key, double min, double max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrangeByScoreWithScores(String key, double min,
double max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Set<String> zrangeByScore(String key, String min, String max) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max);
}
public Set<String> zrevrangeByScore(String key, String max, String min) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min);
}
public Set<String> zrangeByScore(String key, String min, String max,
int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
}
public Set<String> zrevrangeByScore(String key, String max, String min,
int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count);
}
public Set<Tuple> zrangeByScoreWithScores(String key, String min, String max) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min);
}
public Set<Tuple> zrangeByScoreWithScores(String key, String min,
String max, int offset, int count) {
Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count);
}
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min, int offset, int count) {
Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
public Long zremrangeByRank(String key, long start, long end) {
Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end);
}
public Long zremrangeByScore(String key, double start, double end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
public Long zremrangeByScore(String key, String start, String end) {
Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end);
}
public Long linsert(String key, LIST_POSITION where, String pivot,
String value) {
Jedis j = getShard(key);
return j.linsert(key, where, pivot, value);
}
public Long bitcount(final String key) {
Jedis j = getShard(key);
return j.bitcount(key);
}
public Long bitcount(final String key, long start, long end) {
Jedis j = getShard(key);
return j.bitcount(key, start, end);
}
@Deprecated
public ScanResult<Entry<String, String>> hscan(String key, int cursor) {
Jedis j = getShard(key);
return j.hscan(key, cursor);
}
@Deprecated
public ScanResult<String> sscan(String key, int cursor) {
Jedis j = getShard(key);
return j.sscan(key, cursor);
}
@Deprecated
public ScanResult<Tuple> zscan(String key, int cursor) {
Jedis j = getShard(key);
return j.zscan(key, cursor);
}
public ScanResult<Entry<String, String>> hscan(String key, final String cursor) {
Jedis j = getShard(key);
return j.hscan(key, cursor);
}
public ScanResult<String> sscan(String key, final String cursor) {
Jedis j = getShard(key);
return j.sscan(key, cursor);
}
public ScanResult<Tuple> zscan(String key, final String cursor) {
Jedis j = getShard(key);
return j.zscan(key, cursor);
}
} |
package refinedstorage.proxy;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import refinedstorage.RefinedStorage;
import refinedstorage.RefinedStorageBlocks;
import refinedstorage.RefinedStorageItems;
import refinedstorage.block.BlockBase;
import refinedstorage.block.EnumControllerType;
import refinedstorage.block.EnumGridType;
import refinedstorage.block.EnumStorageType;
import refinedstorage.gui.GuiHandler;
import refinedstorage.item.*;
import refinedstorage.network.*;
import refinedstorage.storage.NBTStorage;
import refinedstorage.tile.*;
import refinedstorage.tile.grid.TileGrid;
import refinedstorage.tile.solderer.*;
import static refinedstorage.RefinedStorage.ID;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent e) {
RefinedStorage.NETWORK.registerMessage(MessageTileUpdate.class, MessageTileUpdate.class, 0, Side.CLIENT);
RefinedStorage.NETWORK.registerMessage(MessageTileContainerUpdate.class, MessageTileContainerUpdate.class, 15, Side.CLIENT);
RefinedStorage.NETWORK.registerMessage(MessageRedstoneModeUpdate.class, MessageRedstoneModeUpdate.class, 1, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridStoragePush.class, MessageGridStoragePush.class, 2, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridStoragePull.class, MessageGridStoragePull.class, 3, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageCompareUpdate.class, MessageCompareUpdate.class, 4, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageModeToggle.class, MessageModeToggle.class, 5, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageDetectorModeUpdate.class, MessageDetectorModeUpdate.class, 6, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageDetectorAmountUpdate.class, MessageDetectorAmountUpdate.class, 7, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridCraftingClear.class, MessageGridCraftingClear.class, 9, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessagePriorityUpdate.class, MessagePriorityUpdate.class, 10, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridSettingsUpdate.class, MessageGridSettingsUpdate.class, 11, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridCraftingPush.class, MessageGridCraftingPush.class, 12, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageGridCraftingTransfer.class, MessageGridCraftingTransfer.class, 13, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageWirelessGridSettingsUpdate.class, MessageWirelessGridSettingsUpdate.class, 14, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageWirelessGridItems.class, MessageWirelessGridItems.class, 16, Side.CLIENT);
RefinedStorage.NETWORK.registerMessage(MessageWirelessGridStoragePush.class, MessageWirelessGridStoragePush.class, 17, Side.SERVER);
RefinedStorage.NETWORK.registerMessage(MessageWirelessGridStoragePull.class, MessageWirelessGridStoragePull.class, 18, Side.SERVER);
NetworkRegistry.INSTANCE.registerGuiHandler(RefinedStorage.INSTANCE, new GuiHandler());
GameRegistry.registerTileEntity(TileController.class, ID + ":controller");
GameRegistry.registerTileEntity(TileGrid.class, ID + ":grid");
GameRegistry.registerTileEntity(TileDiskDrive.class, ID + ":disk_drive");
GameRegistry.registerTileEntity(TileExternalStorage.class, ID + ":external_storage");
GameRegistry.registerTileEntity(TileImporter.class, ID + ":importer");
GameRegistry.registerTileEntity(TileExporter.class, ID + ":exporter");
GameRegistry.registerTileEntity(TileDetector.class, ID + ":detector");
GameRegistry.registerTileEntity(TileSolderer.class, ID + ":solderer");
GameRegistry.registerTileEntity(TileDestructor.class, ID + ":destructor");
GameRegistry.registerTileEntity(TileConstructor.class, ID + ":constructor");
GameRegistry.registerTileEntity(TileStorage.class, ID + ":storage");
GameRegistry.registerTileEntity(TileRelay.class, ID + ":relay");
GameRegistry.registerTileEntity(TileInterface.class, ID + ":interface");
registerBlock(RefinedStorageBlocks.CONTROLLER);
registerBlock(RefinedStorageBlocks.CABLE);
registerBlock(RefinedStorageBlocks.GRID);
registerBlock(RefinedStorageBlocks.DISK_DRIVE);
registerBlock(RefinedStorageBlocks.EXTERNAL_STORAGE);
registerBlock(RefinedStorageBlocks.IMPORTER);
registerBlock(RefinedStorageBlocks.EXPORTER);
registerBlock(RefinedStorageBlocks.DETECTOR);
registerBlock(RefinedStorageBlocks.MACHINE_CASING);
registerBlock(RefinedStorageBlocks.SOLDERER);
registerBlock(RefinedStorageBlocks.DESTRUCTOR);
registerBlock(RefinedStorageBlocks.CONSTRUCTOR);
registerBlock(RefinedStorageBlocks.STORAGE);
registerBlock(RefinedStorageBlocks.RELAY);
registerBlock(RefinedStorageBlocks.INTERFACE);
registerItem(RefinedStorageItems.STORAGE_DISK);
registerItem(RefinedStorageItems.WIRELESS_GRID);
registerItem(RefinedStorageItems.QUARTZ_ENRICHED_IRON);
registerItem(RefinedStorageItems.CORE);
registerItem(RefinedStorageItems.SILICON);
registerItem(RefinedStorageItems.PROCESSOR);
registerItem(RefinedStorageItems.STORAGE_PART);
registerItem(RefinedStorageItems.PATTERN);
// Processors
SoldererRegistry.addRecipe(new SoldererRecipePrintedProcessor(ItemProcessor.TYPE_PRINTED_BASIC));
SoldererRegistry.addRecipe(new SoldererRecipePrintedProcessor(ItemProcessor.TYPE_PRINTED_IMPROVED));
SoldererRegistry.addRecipe(new SoldererRecipePrintedProcessor(ItemProcessor.TYPE_PRINTED_ADVANCED));
SoldererRegistry.addRecipe(new SoldererRecipePrintedProcessor(ItemProcessor.TYPE_PRINTED_SILICON));
SoldererRegistry.addRecipe(new SoldererRecipeProcessor(ItemProcessor.TYPE_BASIC));
SoldererRegistry.addRecipe(new SoldererRecipeProcessor(ItemProcessor.TYPE_IMPROVED));
SoldererRegistry.addRecipe(new SoldererRecipeProcessor(ItemProcessor.TYPE_ADVANCED));
// Silicon
GameRegistry.addSmelting(Items.quartz, new ItemStack(RefinedStorageItems.SILICON), 0.5f);
// Quartz Enriched Iron
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON, 4),
"II",
"IQ",
'I', new ItemStack(Items.iron_ingot),
'Q', new ItemStack(Items.quartz)
);
// Machine Casing
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
"EEE",
"E E",
"EEE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
// Construction Core
GameRegistry.addShapelessRecipe(new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_CONSTRUCTION),
new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC),
new ItemStack(Items.glowstone_dust)
);
// Destruction Core
GameRegistry.addShapelessRecipe(new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_DESTRUCTION),
new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC),
new ItemStack(Items.quartz)
);
// Relay
GameRegistry.addShapelessRecipe(new ItemStack(RefinedStorageBlocks.RELAY),
new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC),
new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
new ItemStack(RefinedStorageBlocks.CABLE)
);
// Controller
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.CONTROLLER, 1, EnumControllerType.NORMAL.getId()),
"EDE",
"SRS",
"ESE",
'D', new ItemStack(Items.diamond),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'R', new ItemStack(Items.redstone),
'S', new ItemStack(RefinedStorageItems.SILICON)
);
// Solderer
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.SOLDERER),
"ESE",
"E E",
"ESE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'S', new ItemStack(Blocks.sticky_piston)
);
// Disk Drive
SoldererRegistry.addRecipe(new SoldererRecipeDiskDrive());
// Cable
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.CABLE, 6),
"EEE",
"GRG",
"EEE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone)
);
// Grid
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.GRID, 1, EnumGridType.NORMAL.getId()),
"ECE",
"PMP",
"EDE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED),
'C', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_CONSTRUCTION),
'D', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_DESTRUCTION),
'M', new ItemStack(RefinedStorageBlocks.MACHINE_CASING)
);
// Crafting Grid
SoldererRegistry.addRecipe(new SoldererRecipeCraftingGrid());
// Wireless Grid
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.WIRELESS_GRID, 1, ItemWirelessGrid.TYPE_NORMAL),
" P ",
"ERE",
"EEE",
'P', new ItemStack(Items.ender_pearl),
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
// External Storage
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.EXTERNAL_STORAGE),
"CED",
"HMH",
"EPE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'H', new ItemStack(Blocks.chest),
'C', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_CONSTRUCTION),
'D', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_DESTRUCTION),
'M', new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED)
);
// Importer
GameRegistry.addShapelessRecipe(new ItemStack(RefinedStorageBlocks.IMPORTER),
new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_CONSTRUCTION),
new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC)
);
// Exporter
GameRegistry.addShapelessRecipe(new ItemStack(RefinedStorageBlocks.EXPORTER),
new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_DESTRUCTION),
new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC)
);
// Destructor
GameRegistry.addShapedRecipe(new ItemStack(RefinedStorageBlocks.DESTRUCTOR),
"EDE",
"RMR",
"EIE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'D', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_DESTRUCTION),
'R', new ItemStack(Items.redstone),
'M', new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
'I', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED)
);
// Constructor
GameRegistry.addShapedRecipe(new ItemStack(RefinedStorageBlocks.CONSTRUCTOR),
"ECE",
"RMR",
"EIE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'C', new ItemStack(RefinedStorageItems.CORE, 1, ItemCore.TYPE_CONSTRUCTION),
'R', new ItemStack(Items.redstone),
'M', new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
'I', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED)
);
// Detector
GameRegistry.addRecipe(new ItemStack(RefinedStorageBlocks.DETECTOR),
"ECE",
"RMR",
"EPE",
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'R', new ItemStack(Items.redstone),
'C', new ItemStack(Items.comparator),
'M', new ItemStack(RefinedStorageBlocks.MACHINE_CASING),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED)
);
// Storage Parts
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_1K),
"EPE",
"SRS",
"ESE",
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'P', new ItemStack(RefinedStorageItems.SILICON),
'S', new ItemStack(Blocks.glass)
);
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_4K),
"EPE",
"SRS",
"ESE",
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_BASIC),
'S', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_1K)
);
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_16K),
"EPE",
"SRS",
"ESE",
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_IMPROVED),
'S', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_4K)
);
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_64K),
"EPE",
"SRS",
"ESE",
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON),
'P', new ItemStack(RefinedStorageItems.PROCESSOR, 1, ItemProcessor.TYPE_ADVANCED),
'S', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_16K)
);
// Storage Disks
GameRegistry.addRecipe(NBTStorage.initNBT(new ItemStack(RefinedStorageItems.STORAGE_DISK, 1, ItemStorageDisk.TYPE_1K)),
"GRG",
"RPR",
"EEE",
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone),
'P', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_1K),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
GameRegistry.addRecipe(NBTStorage.initNBT(new ItemStack(RefinedStorageItems.STORAGE_DISK, 1, ItemStorageDisk.TYPE_4K)),
"GRG",
"RPR",
"EEE",
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone),
'P', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_4K),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
GameRegistry.addRecipe(NBTStorage.initNBT(new ItemStack(RefinedStorageItems.STORAGE_DISK, 1, ItemStorageDisk.TYPE_16K)),
"GRG",
"RPR",
"EEE",
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone),
'P', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_16K),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
GameRegistry.addRecipe(NBTStorage.initNBT(new ItemStack(RefinedStorageItems.STORAGE_DISK, 1, ItemStorageDisk.TYPE_64K)),
"GRG",
"RPR",
"EEE",
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone),
'P', new ItemStack(RefinedStorageItems.STORAGE_PART, 1, ItemStoragePart.TYPE_64K),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
// Pattern
GameRegistry.addRecipe(new ItemStack(RefinedStorageItems.PATTERN),
"GRG",
"RGR",
"EEE",
'G', new ItemStack(Blocks.glass),
'R', new ItemStack(Items.redstone),
'E', new ItemStack(RefinedStorageItems.QUARTZ_ENRICHED_IRON)
);
// Storage Blocks
SoldererRegistry.addRecipe(new SoldererRecipeStorage(EnumStorageType.TYPE_1K, ItemStoragePart.TYPE_1K));
SoldererRegistry.addRecipe(new SoldererRecipeStorage(EnumStorageType.TYPE_4K, ItemStoragePart.TYPE_4K));
SoldererRegistry.addRecipe(new SoldererRecipeStorage(EnumStorageType.TYPE_16K, ItemStoragePart.TYPE_16K));
SoldererRegistry.addRecipe(new SoldererRecipeStorage(EnumStorageType.TYPE_64K, ItemStoragePart.TYPE_64K));
// Interface
SoldererRegistry.addRecipe(new SoldererRecipeInterface());
}
public void init(FMLInitializationEvent e) {
}
public void postInit(FMLPostInitializationEvent e) {
}
private void registerBlock(BlockBase block) {
GameRegistry.<Block>register(block);
GameRegistry.register(block.createItemForBlock());
}
private void registerItem(Item item) {
GameRegistry.register(item);
}
} |
package seedu.flexitrack.model.task;
import java.util.Objects;
import seedu.flexitrack.commons.exceptions.IllegalValueException;
import seedu.flexitrack.commons.util.CollectionUtil;
/**
* Represents a Person in the address book. Guarantees: details are present and
* not null, field values are validated.
*/
public class Task implements ReadOnlyTask{
private Name name;
private DateTimeInfo dueDate;
private DateTimeInfo startTime;
private DateTimeInfo endTime;
private boolean isEvent;
private boolean isTask;
private boolean isDone = false;
private boolean isBlock = false;
/**
* Every field must be present and not null.
*/
public Task(Name name, DateTimeInfo dueDate, DateTimeInfo startTime, DateTimeInfo endTime) {
assert !CollectionUtil.isAnyNull(name);
this.name = name;
this.dueDate = dueDate;
this.startTime = startTime;
this.endTime = endTime;
this.isTask = dueDate.isDateNull() ? false : true;
this.isEvent = startTime.isDateNull() ? false : true;
this.isDone = name.getIsDone();
this.isBlock = name.getIsDone();
if (isTask){
this.dueDate.formatStartOrDueDateTime();
} else {
this.startTime.formatStartOrDueDateTime();
this.endTime.formatEndTime(this.startTime);
}
}
/**
* Copy constructor.
*/
public Task(ReadOnlyTask source) {
this(source.getName(), source.getDueDate(), source.getStartTime(), source.getEndTime());
}
@Override
public Name getName() {
return name;
}
@Override
public boolean getIsTask() {
return isTask;
}
@Override
public boolean getIsEvent() {
return isEvent;
}
@Override
public boolean getIsDone() {
return name.getIsDone();
}
@Override
public boolean getIsBlock() {
return name.getIsBlock();
}
public void setIsBlock() {
name.setBlock();
}
@Override
public DateTimeInfo getDueDate() {
return dueDate;
}
@Override
public DateTimeInfo getStartTime() {
return startTime;
}
@Override
public DateTimeInfo getEndTime() {
return endTime;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyTask // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyTask) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing
// your own
return Objects.hash(name, dueDate, startTime, endTime, isTask, isEvent);
}
@Override
public String toString() {
return getAsText();
}
//@@author A0138455Y
private void setIsDone(boolean isDone) {
if (isDone && !this.isDone) {
name.setAsMark();
} else if (!isDone && this.isDone) {
name.setAsUnmark();
}
}
public void markTask(boolean isDone) throws IllegalValueException {
this.isDone = this.name.getIsDone();
if (this.isDone && isDone) {
throw new IllegalValueException("Task already marked!");
} else if (!this.isDone && !isDone) {
throw new IllegalValueException("Task already unmarked!");
} else {
setIsDone(isDone);
}
}
//@@author
public void setName(String name) {
this.name.setName(name);
}
public void setDueDate(String dueDate) throws IllegalValueException {
this.dueDate = new DateTimeInfo(dueDate);
}
public void setStartTime(String startTime) throws IllegalValueException {
this.startTime = new DateTimeInfo(startTime);
}
public void setEndTime(String endTime) throws IllegalValueException {
this.endTime = new DateTimeInfo(endTime);
}
public void setIsTask(Boolean bool) {
this.isTask = bool;
}
public void setIsEvent(Boolean bool) {
this.isEvent = bool;
}
public String getStartingTimeInString(){
return this.startTime.toString();
}
public String getEndingTimeInString(){
return this.endTime.toString();
}
public String getDueDateInString(){
return this.dueDate.toString();
}
} |
//@@author A0139772U
package seedu.whatnow.model;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import seedu.whatnow.commons.core.ComponentManager;
import seedu.whatnow.commons.core.Config;
import seedu.whatnow.commons.core.LogsCenter;
import seedu.whatnow.commons.core.UnmodifiableObservableList;
import seedu.whatnow.commons.events.model.AddTaskEvent;
import seedu.whatnow.commons.events.model.ConfigChangedEvent;
import seedu.whatnow.commons.events.model.UpdateTaskEvent;
import seedu.whatnow.commons.events.model.WhatNowChangedEvent;
import seedu.whatnow.commons.exceptions.DataConversionException;
import seedu.whatnow.commons.util.StringUtil;
import seedu.whatnow.logic.commands.Command;
import seedu.whatnow.model.freetime.FreePeriod;
import seedu.whatnow.model.freetime.Period;
import seedu.whatnow.model.task.ReadOnlyTask;
import seedu.whatnow.model.task.Task;
import seedu.whatnow.model.task.UniqueTaskList;
import seedu.whatnow.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.whatnow.model.task.UniqueTaskList.TaskNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
/**
* Represents the in-memory model of the WhatNow data. All changes to any model
* should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private static final String TASK_TYPE_FLOATING = "floating";
private static final String TASK_TYPE_NOT_FLOATING = "not_floating";
private static final String TASK_STATUS_COMPLETED = "completed";
private static final String TASK_STATUS_INCOMPLETE = "incomplete";
private static final String DEFAULT_START_TIME = "12:00am";
private static final String DEFAULT_END_TIME = "11:59pm";
private static final String TWELVE_HOUR_WITH_MINUTES_COLON_FORMAT = "h:mma";
private static final String DATE_NUM_SLASH_WITH_YEAR_FORMAT = "dd/MM/yyyy";
private static final String DEFAULT_DATE = "01/01/2001";
private static final String DEFAULT_TIME = "12:00am";
private final WhatNow whatNow;
private final FilteredList<Task> filteredTasks;
private FilteredList<Task> filteredSchedules;
private final FilteredList<Task> filteredOverdue;
private final Stack<String> stackOfUndo;
private final Stack<String> stackOfRedo;
private final Stack<ReadOnlyTask> stackOfOldTask;
private final Stack<ReadOnlyTask> stackOfNewTask;
private final Stack<ReadOnlyWhatNow> stackOfWhatNow;
private final Stack<ReadOnlyTask> stackOfDeletedTasks;
private final Stack<Integer> stackOfDeletedTaskIndex;
private final Stack<ReadOnlyTask> stackOfDeletedTasksRedo;
private final Stack<Integer> stackOfDeletedTaskIndexRedo;
private final Stack<ReadOnlyTask> stackOfDeletedTasksAdd;
private final Stack<ReadOnlyTask> stackOfDeletedTasksAddRedo;
private final Stack<ReadOnlyTask> stackOfMarkDone;
private final Stack<ReadOnlyTask> stackOfMarkDoneRedo;
private final Stack<ReadOnlyTask> stackOfMarkUndone;
private final Stack<ReadOnlyTask> stackOfMarkUndoneRedo;
private final Stack<String> stackOfListTypes;
private final Stack<String> stackOfListTypesRedo;
private final Stack<String> stackOfChangeFileLocationOld;
private final Stack<String> stackOfChangeFileLocationNew;
private final HashMap<String, FreePeriod> freeTimes;
//@@author A0139128A
/**
* Initializes a ModelManager with the given WhatNow WhatNow and its
* variables should not be null
*/
public ModelManager(WhatNow src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with WhatNow: " + src + " and user prefs " + userPrefs);
whatNow = new WhatNow(src);
new Config();
filteredTasks = new FilteredList<>(whatNow.getTasks());
filteredSchedules = new FilteredList<>(whatNow.getTasks());
filteredOverdue = new FilteredList<>(whatNow.getTasks());
stackOfUndo = new Stack<>();
stackOfRedo = new Stack<>();
stackOfOldTask = new Stack<>();
stackOfNewTask = new Stack<>();
stackOfWhatNow = new Stack<>();
stackOfDeletedTasks = new Stack<>();
stackOfDeletedTaskIndex = new Stack<>();
stackOfDeletedTasksRedo = new Stack<>();
stackOfDeletedTaskIndexRedo = new Stack<>();
stackOfDeletedTasksAdd = new Stack<>();
stackOfDeletedTasksAddRedo = new Stack<>();
stackOfMarkDone = new Stack<>();
stackOfMarkDoneRedo = new Stack<>();
stackOfMarkUndone = new Stack<>();
stackOfMarkUndoneRedo = new Stack<>();
stackOfListTypes = new Stack<>();
stackOfListTypesRedo = new Stack<>();
stackOfChangeFileLocationOld = new Stack<>();
stackOfChangeFileLocationNew = new Stack<>();
freeTimes = new HashMap<String, FreePeriod>();
initialiseFreeTime();
}
//@@author A0141021H-reused
public ModelManager() {
this(new WhatNow(), new UserPrefs());
}
//@@author A0139128A
public ModelManager(ReadOnlyWhatNow initialData, UserPrefs userPrefs) {
whatNow = new WhatNow(initialData);
new Config();
filteredTasks = new FilteredList<>(whatNow.getTasks());
filteredSchedules = new FilteredList<>(whatNow.getTasks());
filteredOverdue = new FilteredList<>(whatNow.getTasks());
stackOfUndo = new Stack<>();
stackOfRedo = new Stack<>();
stackOfOldTask = new Stack<>();
stackOfNewTask = new Stack<>();
stackOfWhatNow = new Stack<>();
stackOfDeletedTasks = new Stack<>();
stackOfDeletedTaskIndex = new Stack<>();
stackOfDeletedTasksRedo = new Stack<>();
stackOfDeletedTaskIndexRedo = new Stack<>();
stackOfDeletedTasksAdd = new Stack<>();
stackOfDeletedTasksAddRedo = new Stack<>();
stackOfMarkDone = new Stack<>();
stackOfMarkDoneRedo = new Stack<>();
stackOfMarkUndone = new Stack<>();
stackOfMarkUndoneRedo = new Stack<>();
stackOfListTypes = new Stack<>();
stackOfListTypesRedo = new Stack<>();
stackOfChangeFileLocationOld = new Stack<>();
stackOfChangeFileLocationNew = new Stack<>();
freeTimes = new HashMap<String, FreePeriod>();
initialiseFreeTime();
}
//@@author A0139772U
private void initialiseFreeTime() {
freeTimes.clear();
for (int i = 0; i < filteredSchedules.size(); i++) {
blockFreeTime(filteredSchedules.get(i));
}
}
//@@author A0139128A
@Override
public void resetData(ReadOnlyWhatNow newData) {
stackOfWhatNow.push(new WhatNow(whatNow));
whatNow.resetData(newData);
initialiseFreeTime();
indicateWhatNowChanged();
}
@Override
public synchronized void revertData() {
whatNow.revertEmptyWhatNow(stackOfWhatNow.pop());
indicateWhatNowChanged();
}
//@@author A0139128A-reused
@Override
public ReadOnlyWhatNow getWhatNow() {
return whatNow;
}
//@@author A0139772U-reused
/** Raises an event to indicate the model has changed */
private void indicateWhatNowChanged() {
raise(new WhatNowChangedEvent(whatNow));
}
//@@author A0141021H
/** Raises an event to indicate the config has changed */
private void indicateConfigChanged(Path destination, Config config) {
raise(new ConfigChangedEvent(destination, config));
}
//@@author A0141021H-reused
/** Raises an event to indicate that a task was added */
private void indicateAddTask(Task task, boolean isUndo) {
raise(new AddTaskEvent(task, isUndo));
}
//@@author A0141021H-reused
/** Raises an event to indicate that a task was updated */
private void indicateUpdateTask(Task task) {
raise(new UpdateTaskEvent(task));
}
//@@author A0141021H
@Override
public synchronized void changeLocation(Path destination, Config config) throws DataConversionException {
indicateWhatNowChanged();
indicateConfigChanged(destination, config);
indicateWhatNowChanged();
}
//@@author A0139128A-reused
@Override
public synchronized int deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
int indexRemoved = whatNow.removeTask(target);
unblockFreeTime();
indicateWhatNowChanged();
return indexRemoved;
}
//@@author A0126240W-reused
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
whatNow.addTask(task);
blockFreeTime(task);
updateFilteredListToShowAllIncomplete();
indicateAddTask(task, false);
indicateWhatNowChanged();
}
//@@author A0139128A
public synchronized void addTaskSpecific(Task task, int idx) throws UniqueTaskList.DuplicateTaskException {
whatNow.addTaskSpecific(task, idx);
updateFilteredListToShowAllIncomplete();
indicateAddTask(task, true);
indicateWhatNowChanged();
}
//@@author A0126240W
@Override
public synchronized void updateTask(ReadOnlyTask old, Task toUpdate)
throws TaskNotFoundException, DuplicateTaskException {
whatNow.updateTask(old, toUpdate);
indicateUpdateTask(toUpdate);
unblockFreeTime();
indicateWhatNowChanged();
}
//@@author A0139772U
@Override
public synchronized void markTask(ReadOnlyTask target) throws TaskNotFoundException {
whatNow.markTask(target);
indicateWhatNowChanged();
}
//@@author A0141021H
@Override
public synchronized void unMarkTask(ReadOnlyTask target) throws TaskNotFoundException {
whatNow.unMarkTask(target);
indicateWhatNowChanged();
}
//@@author A0139128A
@Override
public Stack<String> getUndoStack() {
return stackOfUndo;
}
//@@author A0139128A
@Override
public Stack<String> getRedoStack() {
return stackOfRedo;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getOldTask() {
return stackOfOldTask;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getNewTask() {
return stackOfNewTask;
}
//@@author A0139772U
@Override
public UnmodifiableObservableList<ReadOnlyTask> getAllTaskTypeList() {
filteredTasks.setPredicate(null);
return new UnmodifiableObservableList<>(filteredTasks);
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasks() {
return stackOfDeletedTasks;
}
//@@author A0139128A
public Stack<Integer> getDeletedStackOfTasksIndex() {
return stackOfDeletedTaskIndex;
}
//@@author A0139128A
public Stack<Integer> getDeletedStackOfTasksIndexRedo() {
return stackOfDeletedTaskIndexRedo;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasksRedo() {
return stackOfDeletedTasksRedo;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasksAdd() {
return stackOfDeletedTasksAdd;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasksAddRedo() {
return stackOfDeletedTasksAddRedo;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getStackOfMarkDoneTask() {
return stackOfMarkDone;
}
//@@author A0139128A
@Override
public Stack<ReadOnlyTask> getStackOfMarkDoneTaskRedo() {
return stackOfMarkDoneRedo;
}
//@@author A0141021H
@Override
public Stack<ReadOnlyTask> getStackOfMarkUndoneTask() {
return stackOfMarkUndone;
}
//@@author A0139128A
public Stack<ReadOnlyTask> getStackOfMarkUndoneTaskRedo() {
return stackOfMarkUndoneRedo;
}
//@@author A0139128A
@Override
public Stack<String> getStackOfListTypes() {
return stackOfListTypes;
}
//@@author A0139128A
@Override
public Stack<String> getStackOfListTypesRedo() {
return stackOfListTypesRedo;
}
//@@author A0141021H
@Override
public Stack<String> getStackOfChangeFileLocationOld() {
return stackOfChangeFileLocationOld;
}
//@@author A0141021H
@Override
public Stack<String> getStackOfChangeFileLocationNew() {
return stackOfChangeFileLocationNew;
}
//@@author A0139772U
@Override
public FreePeriod getFreeTime(String date) {
if (freeTimes.get(date) == null) {
freeTimes.put(date, new FreePeriod());
}
freeTimes.get(date).getList().sort(new Period());
return freeTimes.get(date);
}
//@@author A0139772U
/**
* Remove from the freetime block the period that coincides with the task
* duration
*/
private void blockFreeTime(Task task) {
String date = task.getTaskDate();
String startDate = task.getStartDate();
String endDate = task.getEndDate();
String startTime = task.getStartTime();
String endTime = task.getEndTime();
if (date != null && startTime != null && endTime != null) {
blockTaskWithOneDateTwoTime(date, startTime, endTime);
} else if (date == null && startTime != null && endTime != null) {
blockTaskWithTwoDateTwoTime(startDate, endDate, startTime, endTime);
}
}
/**
* Remove from the freetime block the period that coincides with the task
* duration, for task with one date and two time
*/
private void blockTaskWithOneDateTwoTime(String date, String startTime, String endTime) {
if (freeTimes.get(date) == null) {
FreePeriod newFreePeriod = new FreePeriod();
newFreePeriod.block(startTime, endTime);
freeTimes.put(date, newFreePeriod);
} else {
freeTimes.get(date).block(startTime, endTime);
}
}
/**
* Remove from the freetime block the period that coincides with the task
* duration, for task with two date and two time
*/
private void blockTaskWithTwoDateTwoTime(String startDate, String endDate, String startTime, String endTime) {
if (freeTimes.get(startDate) == null) {
FreePeriod newFreePeriod = new FreePeriod();
newFreePeriod.block(startTime, DEFAULT_END_TIME);
freeTimes.put(startDate, newFreePeriod);
} else {
freeTimes.get(startDate).block(startTime, DEFAULT_END_TIME);
}
if (freeTimes.get(endDate) == null) {
FreePeriod newFreePeriod = new FreePeriod();
newFreePeriod.block(DEFAULT_START_TIME, endTime);
freeTimes.put(endDate, newFreePeriod);
} else {
freeTimes.get(endDate).block(DEFAULT_START_TIME, endTime);
}
blockDatesInBetween(startDate, endDate);
}
/**
* Remove from the freetime block the period that coincides with the task
* duration, between startdate and end date
*/
private void blockDatesInBetween(String start, String end) {
Calendar cal = Calendar.getInstance();
DateFormat df = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
try {
Date startDate = df.parse(start);
Date endDate = df.parse(end);
cal.setTime(startDate);
while (cal.getTime().before(endDate)) {
cal.add(Calendar.DATE, 1);
if (cal.getTime().equals(endDate)) {
break;
}
if (freeTimes.get(cal.getTime()) == null) {
FreePeriod newFreePeriod = new FreePeriod();
newFreePeriod.getList().clear();
freeTimes.put(df.format(cal.getTime()), newFreePeriod);
} else {
freeTimes.get(cal.getTime()).getList().clear();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
private void unblockFreeTime() {
freeTimes.clear();
initialiseFreeTime();
}
//@@author A0139772U
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
updateFilteredListToShowAllIncomplete();
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getCurrentFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList(Set<String> keyword) {
updateFilteredTaskList(keyword);
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
String[] taskType = { TASK_TYPE_FLOATING };
Set<String> keyword = new HashSet<>(Arrays.asList(taskType));
FXCollections.sort(filteredTasks.getSource());
updateFilteredTaskList(new PredicateExpression(new TaskTypeQualifier(keyword)));
}
@Override
public void updateFilteredListToShowAllIncomplete() {
FXCollections.sort(filteredTasks.getSource());
filteredTasks.setPredicate(p -> {
if ((p.getTaskType().equals((TASK_TYPE_FLOATING)) && (p.getStatus().equals(TASK_STATUS_INCOMPLETE)))) {
return true;
} else {
return false;
}
});
}
@Override
public void updateFilteredListToShowAllCompleted() {
FXCollections.sort(filteredTasks.getSource());
filteredTasks.setPredicate(p -> {
if ((p.getTaskType().equals((TASK_TYPE_FLOATING)) && (p.getStatus().equals(TASK_STATUS_COMPLETED)))) {
return true;
} else {
return false;
}
});
}
@Override
public void updateFilteredListToShowAllByStatus(Set<String> keyword) {
updateFilteredTaskList(new PredicateExpression(new TaskStatusQualifier(keyword)));
}
@Override
public void updateFilteredTaskList(Set<String> keywords) {
filteredTasks.setPredicate(p -> {
if ((keywords.stream().filter(key -> StringUtil.containsIgnoreCase(p.getName().fullName, key)).findAny()
.isPresent()) && p.getTaskType().equals(TASK_TYPE_FLOATING)) {
return true;
} else {
return false;
}
});
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
//@@author A0139772U
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredScheduleList(boolean isUndo) {
if (!isUndo) {
updateFilteredScheduleListToShowAllIncomplete();
}
return new UnmodifiableObservableList<>(filteredSchedules);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getCurrentFilteredScheduleList() {
return new UnmodifiableObservableList<>(filteredSchedules);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredScheduleList(Set<String> keyword) {
updateFilteredScheduleList(keyword);
return new UnmodifiableObservableList<>(filteredSchedules);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getOverdueScheduleList() {
updateFilteredScheduleListToShowAllOverdue();
return new UnmodifiableObservableList<>(filteredOverdue);
}
@Override
public void updateFilteredScheduleListToShowAll() {
String[] taskType = { TASK_TYPE_NOT_FLOATING };
Set<String> keyword = new HashSet<>(Arrays.asList(taskType));
FXCollections.sort(filteredSchedules.getSource());
updateFilteredScheduleList(new PredicateExpression(new TaskTypeQualifier(keyword)));
}
@Override
public void updateFilteredScheduleListToShowAllIncomplete() {
FXCollections.sort(filteredSchedules.getSource());
filteredSchedules.setPredicate(p -> {
if ((p.getTaskType().equals((TASK_TYPE_NOT_FLOATING)) && (p.getStatus().equals(TASK_STATUS_INCOMPLETE)))) {
return true;
} else {
return false;
}
});
}
@Override
public void updateFilteredScheduleListToShowAllCompleted() {
FXCollections.sort(filteredSchedules.getSource());
filteredSchedules.setPredicate(p -> {
if ((p.getTaskType().equals((TASK_TYPE_NOT_FLOATING)) && (p.getStatus().equals(TASK_STATUS_COMPLETED)))) {
return true;
} else {
return false;
}
});
}
@Override
public void updateFilteredScheduleListToShowAllByStatus(Set<String> keyword) {
updateFilteredScheduleList(new PredicateExpression(new TaskStatusQualifier(keyword)));
}
@Override
public void updateFilteredScheduleList(Set<String> keywords) {
filteredSchedules.setPredicate(p -> {
if ((keywords.stream().filter(key -> StringUtil.containsIgnoreCase(p.getName().fullName, key)).findAny()
.isPresent()) && p.getTaskType().equals(TASK_TYPE_NOT_FLOATING)) {
return true;
} else {
return false;
}
});
}
@Override
public void updateFilteredScheduleListToShowAllOverdue() {
DateFormat df = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
DateFormat tf = new SimpleDateFormat(TWELVE_HOUR_WITH_MINUTES_COLON_FORMAT);
Calendar cal = Calendar.getInstance();
FXCollections.sort(filteredOverdue.getSource());
filteredOverdue.setPredicate(p -> {
try {
Date today = df.parse(df.format(cal.getTime()));
Date currentTime = tf.parse(tf.format(cal.getTime()));
String dateString = getDate(p);
String timeString = getTime(p);
Date date = df.parse(dateString);
Date time = df.parse(timeString);
if ((p.getTaskType().equals((TASK_TYPE_NOT_FLOATING)) && (p.getStatus().equals(TASK_STATUS_INCOMPLETE)
&& date.before(today)
&& time.before(currentTime)))) {
return true;
} else {
return false;
}
} catch (ParseException e) {
logger.warning("ParseException at ModelManager's updateFilteredScheduleListToShowAllOver method: \n"
+ e.getMessage());
return false;
}
});
}
private String getDate(Task task) {
String newDate = task.getTaskDate();
if (newDate == null) {
newDate = task.getEndDate();
}
if (newDate == null) {
newDate = DEFAULT_DATE;
}
return newDate;
}
private String getTime(Task task) {
String newTime = task.getTaskTime();
if (newTime == null) {
newTime = task.getEndTime();
}
if (newTime == null) {
newTime = DEFAULT_TIME;
}
return newTime;
}
private void updateFilteredScheduleList(Expression expression) {
filteredSchedules.setPredicate(expression::satisfies);
}
//@@author A0141021H
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
//@@author A0139772U
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword)).findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
//@@author A0139772U
private class TaskStatusQualifier implements Qualifier {
private Set<String> status;
TaskStatusQualifier(Set<String> status) {
this.status = status;
}
@Override
public boolean run(ReadOnlyTask task) {
return status.stream().filter(keyword -> StringUtil.containsIgnoreCase(task.getStatus(), keyword)).findAny()
.isPresent();
}
@Override
public String toString() {
return "Status=" + String.join(", ", status);
}
}
//@@author A0139772U
private class TaskTypeQualifier implements Qualifier {
private Set<String> taskType;
TaskTypeQualifier(Set<String> taskType) {
this.taskType = taskType;
}
@Override
public boolean run(ReadOnlyTask task) {
return taskType.stream().filter(keyword -> StringUtil.containsIgnoreCase(task.getTaskType(), keyword))
.findAny().isPresent();
}
@Override
public String toString() {
return "TaskType=" + String.join(", ", taskType);
}
}
} |
package xml.commands;
import utility.Command;
import xml.Element;
public class SetAttributeCommand extends ElementCommand implements Command {
private String attName;
private String attVal;
private String oldVal;
private final String NAME = "Set Attribute";
public SetAttributeCommand(Element element, String key, String val) {
this(element, key, val, element.getAttribute(key));
}
public SetAttributeCommand(Element element, String key, String val,
String oldVal) {
super(element);
attName = key;
attVal = val;
this.oldVal = oldVal;
}
@Override
public void perform() {
element.setAttribute(attName, attVal);
}
@Override
public void undo() {
if (oldVal != null) {
element.setAttribute(attName, oldVal);
} else {
element.removeAttribute(attName);
}
}
public String getName() {
return NAME;
}
public String getAttributeName() {
return attName;
}
public String getAttributeValue() {
return attVal;
}
public String getOldAttributeValue() {
return oldVal;
}
@Override
public boolean canCombine(Command cmd) {
if (cmd.getClass() != getClass()) {
return false;
}
SetAttributeCommand setAttributeCommand = (SetAttributeCommand) cmd;
boolean attributeMatch;
attributeMatch = setAttributeCommand.getAttributeName() == attName;
return attributeMatch;
}
@Override
public Command combine(Command cmd) {
if (cmd.getClass() != getClass()) {
return null;
}
SetAttributeCommand chainCommand = (SetAttributeCommand) cmd;
if (chainCommand.getAttributeName() != attName) {
return null;
}
String combinedValue = attVal + chainCommand.getAttributeValue();
SetAttributeCommand combinedCommand;
combinedCommand = new SetAttributeCommand(element, attName, combinedValue, oldVal);
return combinedCommand;
}
} |
package yanagishima.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yanagishima.config.YanagishimaConfig;
@Singleton
public class QueryServlet extends HttpServlet {
private static Logger LOGGER = LoggerFactory.getLogger(QueryServlet.class);
private static final long serialVersionUID = 1L;
private YanagishimaConfig yanagishimaConfig;
private static final int LIMIT = 100;
@Inject
public QueryServlet(YanagishimaConfig yanagishimaConfig) {
this.yanagishimaConfig = yanagishimaConfig;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String prestoCoordinatorServer = yanagishimaConfig
.getPrestoCoordinatorServer();
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
String originalJson = Request.Get(prestoCoordinatorServer + "/v1/query")
.execute().returnContent().asString(StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
List<Map> list = mapper.readValue(originalJson, List.class);
if(list.size() > LIMIT) {
list.sort((a,b)-> String.class.cast(b.get("queryId")).compareTo(String.class.cast(a.get("queryId"))));
String json = mapper.writeValueAsString(list.subList(0, LIMIT));
writer.println(json);
} else {
writer.println(originalJson);
}
}
} |
package org.deidentifier.arx;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.deidentifier.arx.ARXLattice.ARXNode;
import org.deidentifier.arx.framework.check.INodeChecker;
import org.deidentifier.arx.framework.check.NodeChecker;
import org.deidentifier.arx.framework.data.Data;
import org.deidentifier.arx.framework.data.DataManager;
import org.deidentifier.arx.framework.data.Dictionary;
import org.deidentifier.arx.framework.data.GeneralizationHierarchy;
import org.deidentifier.arx.framework.lattice.Lattice;
import org.deidentifier.arx.framework.lattice.Node;
import org.deidentifier.arx.metric.Metric;
/**
* An implementation of the class DataHandle and the ARXResult interface for
* output data.
*
* @author Prasser, Kohlmayer
*/
public class DataHandleOutput extends DataHandle implements ARXResult {
/**
* The class ResultIterator.
*
* @author Prasser, Kohlmayer
*/
public class ResultIterator implements Iterator<String[]> {
/** The current row. */
private int row = -1;
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return row < dataQI.getArray().length;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
@Override
public String[] next() {
String[] result = null;
/* write header */
if (row == -1) {
result = header;
/* write a normal row */
} else {
// Create row
result = new String[header.length];
for (int i = 0; i < result.length; i++) {
result[i] = getValueInternal(row, i);
}
}
row++;
return result;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/** The global optimum. */
private ARXNode optimalNode;
/** The current node */
private ARXNode currentNode;
/** The last node */
private ARXNode lastNode;
/** The lattice. */
private ARXLattice lattice;
/** The names of the quasiIdentifer. */
private String[] quasiIdentifiers;
/** Wall clock. */
private long duration;
/** The data. */
private Data dataSE;
/** The data. */
private Data dataIS;
/** The data. */
private Data dataQI;
/** The generalization hierarchies. */
private int[][][] map;
/** The string to insert. */
private String suppressionString;
/** An inverse map for column indices. */
private int[] inverseMap;
/** An inverse map to data arrays. */
private int[][][] inverseData;
/** An inverse map to dictionaries. */
private Dictionary[] inverseDictionaries;
/** The node checker. */
private INodeChecker checker;
/** Should we remove outliers */
private boolean removeOutliers;
/** The configuration */
private ARXConfiguration config;
/**
* Internal constructor for deserialization
*/
public DataHandleOutput(final DataHandle handle,
final DataDefinition definition,
final ARXLattice lattice,
final boolean removeOutliers,
final String suppressionString,
final int historySize,
final double snapshotSizeSnapshot,
final double snapshotSizeDataset,
final Metric<?> metric,
final ARXConfiguration config,
final ARXNode optimum,
final long time) {
// Set optimum in lattice
lattice.access().setOptimum(optimum);
// Extract data
final String[] header = ((DataHandleInput) handle).header;
final int[][] dataArray = ((DataHandleInput) handle).data;
final Dictionary dictionary = ((DataHandleInput) handle).dictionary;
final DataManager manager = new DataManager(header,
dataArray,
dictionary,
handle.getDefinition(),
config.getCriteria());
// Initialize the metric
metric.initialize(manager.getDataQI(), manager.getHierarchies(), config);
// Create a node checker
final INodeChecker checker = new NodeChecker(manager,
metric,
config,
historySize,
snapshotSizeDataset,
snapshotSizeSnapshot);
// Initialize the result
init(manager,
checker,
time,
suppressionString,
definition,
lattice,
removeOutliers,
config);
}
/**
* Instantiates a new ARX result.
*
* @param metric
* @param manager
* @param checker
* @param time
* @param suppressionString
* @param defintion
* @param lattice
* @param practicalMonotonicity
* @param removeOutliers
* @param maximumAbsoluteOutliers
* @param config
*/
public DataHandleOutput(final Metric<?> metric,
final DataManager manager,
final INodeChecker checker,
final long time,
final String suppressionString,
final DataDefinition defintion,
final Lattice lattice,
final boolean removeOutliers,
final ARXConfiguration config) {
final boolean practicalMonotonicity = config.isPracticalMonotonicity();
final int maximumAbsoluteOutliers = config.getAbsoluteMaxOutliers();
final ARXLattice flattice = new ARXLattice(lattice,
manager.getDataQI()
.getHeader(),
metric,
practicalMonotonicity,
maximumAbsoluteOutliers);
init(manager,
checker,
time,
suppressionString,
defintion,
flattice,
removeOutliers,
config);
}
/**
* Associates this handle with an input data handle.
*
* @param inHandle
* the in handle
*/
protected void associate(final DataHandleInput inHandle) {
other = inHandle;
}
/**
* A negative integer, zero, or a positive integer as the first argument is
* less than, equal to, or greater than the second. It uses the specified
* data types for comparison if no generalization was applied, otherwise it
* uses string comparison.
*
* @param row1
* the row1
* @param row2
* the row2
* @param columns
* the columns
* @param ascending
* the ascending
* @return the int
*/
@Override
protected int compare(final int row1,
final int row2,
final int[] columns,
final boolean ascending) {
getHandle(currentNode);
for (final int index : columns) {
final int attributeType = inverseMap[index] >>> AttributeType.SHIFT;
final int indexMap = inverseMap[index] & AttributeType.MASK;
int cmp = 0;
try {
cmp = dataTypes[attributeType][indexMap].compare(getValueInternal(row1,
index),
getValueInternal(row2,
index));
} catch (final Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (cmp != 0) {
if (ascending) {
return -cmp;
} else {
return cmp;
}
}
}
return 0;
}
/**
* Creates the data type array.
*/
@Override
protected void createDataTypeArray() {
dataTypes = new DataType[3][];
dataTypes[AttributeType.ATTR_TYPE_IS] = new DataType[dataIS.getHeader().length];
dataTypes[AttributeType.ATTR_TYPE_SE] = new DataType[dataSE.getHeader().length];
dataTypes[AttributeType.ATTR_TYPE_QI] = new DataType[dataQI.getHeader().length];
for (int i = 0; i < dataTypes.length; i++) {
final DataType[] type = dataTypes[i];
String[] headers = null;
switch (i) {
case AttributeType.ATTR_TYPE_IS:
headers = dataIS.getHeader();
break;
case AttributeType.ATTR_TYPE_QI:
headers = dataQI.getHeader();
break;
case AttributeType.ATTR_TYPE_SE:
headers = dataSE.getHeader();
break;
}
for (int j = 0; j < type.length; j++) {
dataTypes[i][j] = definition.getDataType(headers[j]);
if ((i == AttributeType.ATTR_TYPE_QI) &&
(currentNode.getTransformation()[j] > 0)) {
dataTypes[i][j] = DataType.STRING;
}
}
}
}
/**
* Gets the attribute name.
*
* @param col
* the col
* @return the attribute name
*/
@Override
public String getAttributeName(final int col) {
checkColumn(col);
return header[col];
}
@Override
public ARXConfiguration getConfiguration() {
return config;
}
/**
* Gets the distinct values.
*
* @param col
* the col
* @return the distinct values
*/
@Override
public String[] getDistinctValues(final int col) {
getHandle(currentNode);
// Check
checkColumn(col);
// TODO: Inefficient
final Set<String> vals = new HashSet<String>();
for (int i = 0; i < getNumRows(); i++) {
vals.add(getValue(i, col));
}
return vals.toArray(new String[vals.size()]);
}
@Override
public int getGeneralization(final String attribute) {
return currentNode.getGeneralization(attribute);
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.ARXResult#getGlobalOptimum()
*/
/**
* Gets the global optimalARXNode.
*
* @return the global optimalARXNode
*/
@Override
public ARXNode getGlobalOptimum() {
return optimalNode;
}
@Override
public int getGroupCount() {
getHandle(currentNode);
return checker.getGroupCount();
}
@Override
public int getGroupOutliersCount() {
getHandle(currentNode);
return checker.getGroupOutliersCount();
}
@Override
public DataHandle getHandle() {
if (optimalNode == null) { return null; }
return getHandle(optimalNode);
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.ARXResult#getHandle()
*/
/**
* Gets the handle.
*
* @return the handle
*/
@Override
public DataHandle getHandle(final ARXNode fnode) {
currentNode = fnode;
// Dont transform twice
if ((currentNode != null) && (currentNode == lastNode)) { return this; }
// Prepare
lastNode = currentNode;
final Node node = new Node(0);
node.setTransformation(fnode.getTransformation(), 0);
if (currentNode.isChecked()) {
node.setChecked();
}
// Suppress
checker.transformAndMarkOutliers(node);
// Store
if (!currentNode.isChecked()) {
currentNode.access().setChecked(true);
if (node.isAnonymous()) {
currentNode.access().setAnonymous();
} else {
currentNode.access().setNotAnonymous();
}
currentNode.access()
.setMaximumInformationLoss(node.getInformationLoss());
currentNode.access()
.setMinimumInformationLoss(node.getInformationLoss());
lattice.estimateInformationLoss();
}
// Create datatype array
createDataTypeArray();
return this;
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.ARXResult#getLattice()
*/
/**
* Gets the lattice.
*
* @return the lattice
*/
@Override
public ARXLattice getLattice() {
return lattice;
}
/**
* Gets the num columns.
*
* @return the num columns
*/
@Override
public int getNumColumns() {
return header.length;
}
/**
* Gets the num rows.
*
* @return the num rows
*/
@Override
public int getNumRows() {
return dataQI.getDataLength();
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.ARXResult#getTime()
*/
/**
* Gets the time.
*
* @return the time
*/
@Override
public long getTime() {
return duration;
}
@Override
public int getTupleOutliersCount() {
getHandle(currentNode);
return checker.getTupleOutliersCount();
}
/**
* Gets the value.
*
* @param row
* the row
* @param col
* the col
* @return the value
*/
@Override
public String getValue(final int row, final int col) {
// Check
getHandle(currentNode);
checkColumn(col);
checkRow(row, dataQI.getDataLength());
// Perform
return getValueInternal(row, col);
}
/**
* Gets the value internal.
*
* @param row
* the row
* @param col
* the col
* @return the value internal
*/
@Override
protected String getValueInternal(final int row, final int col) {
// Return the according values
final int type = inverseMap[col] >>> AttributeType.SHIFT;
switch (type) {
case AttributeType.ATTR_TYPE_ID:
return suppressionString;
default:
final int index = inverseMap[col] & AttributeType.MASK;
final int[][] data = inverseData[type];
if (removeOutliers &&
((dataQI.getArray()[row][0] & Data.OUTLIER_MASK) != 0)) { return suppressionString; }
final int value = data[row][index] & Data.REMOVE_OUTLIER_MASK;
final String[][] dictionary = inverseDictionaries[type].getMapping();
return dictionary[index][value];
}
}
private void init(final DataManager manager,
final INodeChecker checker,
final long time,
final String suppressionString,
final DataDefinition defintion,
final ARXLattice lattice,
final boolean removeOutliers,
final ARXConfiguration config) {
this.config = config;
this.removeOutliers = removeOutliers;
this.lattice = lattice;
optimalNode = this.lattice.getOptimum();
duration = time;
currentNode = optimalNode;
lastNode = null;
this.suppressionString = suppressionString;
this.checker = checker;
definition = defintion;
// Extract data
dataQI = checker.getBuffer();
dataSE = manager.getDataSE();
dataIS = manager.getDataIS();
super.header = manager.getHeader();
// Init quasi identifiers and hierarchies
final GeneralizationHierarchy[] hierarchies = manager.getHierarchies();
quasiIdentifiers = new String[hierarchies.length];
map = new int[hierarchies.length][][];
for (int i = 0; i < hierarchies.length; i++) {
quasiIdentifiers[i] = hierarchies[i].getName();
map[i] = hierarchies[i].getArray();
}
// Build map inverse
inverseMap = new int[header.length];
for (int i = 0; i < inverseMap.length; i++) {
inverseMap[i] = (AttributeType.ATTR_TYPE_ID << AttributeType.SHIFT);
}
for (int i = 0; i < dataQI.getMap().length; i++) {
inverseMap[dataQI.getMap()[i]] = i |
(AttributeType.ATTR_TYPE_QI << AttributeType.SHIFT);
}
for (int i = 0; i < dataSE.getMap().length; i++) {
inverseMap[dataSE.getMap()[i]] = i |
(AttributeType.ATTR_TYPE_SE << AttributeType.SHIFT);
}
for (int i = 0; i < dataIS.getMap().length; i++) {
inverseMap[dataIS.getMap()[i]] = i |
(AttributeType.ATTR_TYPE_IS << AttributeType.SHIFT);
}
// Build inverse data array
inverseData = new int[3][][];
inverseData[AttributeType.ATTR_TYPE_IS] = dataIS.getArray();
inverseData[AttributeType.ATTR_TYPE_SE] = dataSE.getArray();
inverseData[AttributeType.ATTR_TYPE_QI] = dataQI.getArray();
// Build inverse dictionary array
inverseDictionaries = new Dictionary[3];
inverseDictionaries[AttributeType.ATTR_TYPE_IS] = dataIS.getDictionary();
inverseDictionaries[AttributeType.ATTR_TYPE_SE] = dataSE.getDictionary();
inverseDictionaries[AttributeType.ATTR_TYPE_QI] = dataQI.getDictionary();
}
@Override
protected boolean isOutlierInternal(final int row) {
return ((dataQI.getArray()[row][0] & Data.OUTLIER_MASK) != 0);
}
/**
* Checks if is result available.
*
* @return true, if is result available
*/
@Override
public boolean isResultAvailable() {
return optimalNode != null;
}
/**
* Iterator.
*
* @return the iterator
*/
@Override
public Iterator<String[]> iterator() {
getHandle(currentNode);
return new ResultIterator();
}
/**
* Swap.
*
* @param row1
* the row1
* @param row2
* the row2
*/
@Override
public void swap(final int row1, final int row2) {
// Check
checkRow(row1, dataQI.getDataLength());
checkRow(row2, dataQI.getDataLength());
// Swap input data
if (other != null) {
other.swapInternal(row1, row2);
}
// Swap
swapInternal(row1, row2);
}
/**
* Swap internal.
*
* @param row1
* the row1
* @param row2
* the row2
*/
@Override
protected void swapInternal(final int row1, final int row2) {
// Now swap
getHandle(currentNode);
int[] temp = dataQI.getArray()[row1];
dataQI.getArray()[row1] = dataQI.getArray()[row2];
dataQI.getArray()[row2] = temp;
temp = dataSE.getArray()[row1];
dataSE.getArray()[row1] = dataSE.getArray()[row2];
dataSE.getArray()[row2] = temp;
temp = dataIS.getArray()[row1];
dataIS.getArray()[row1] = dataIS.getArray()[row2];
dataIS.getArray()[row2] = temp;
}
} |
package cgeo.geocaching;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cgeo.calendar.CalendarAddon;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.AbstractActivity.ActivitySharingInterface;
import cgeo.geocaching.activity.AbstractViewPagerActivity;
import cgeo.geocaching.activity.INavigationSource;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.apps.cache.navi.NavigationSelectionActionProvider;
import cgeo.geocaching.apps.cachelist.MapsWithMeCacheListApp;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.GCConnector;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.IGeoData;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.AbstractCachingPageViewCreator;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.CoordinatesFormatSwitcher;
import cgeo.geocaching.ui.DecryptTextClickListener;
import cgeo.geocaching.ui.EditNoteDialog;
import cgeo.geocaching.ui.EditNoteDialog.EditNoteDialogListener;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.IndexOutOfBoundsAvoidingTextView;
import cgeo.geocaching.ui.LoggingUI;
import cgeo.geocaching.ui.NavigationActionProvider;
import cgeo.geocaching.ui.OwnerActionsClickListener;
import cgeo.geocaching.ui.WeakReferenceHandler;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.ui.logs.CacheLogsViewCreator;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MatcherWrapper;
import cgeo.geocaching.utils.RxUtils;
import cgeo.geocaching.utils.SimpleCancellableHandler;
import cgeo.geocaching.utils.SimpleHandler;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.Subscription;
import rx.android.observables.AndroidObservable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;
import android.R.color;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.view.ActionMode;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* Activity to handle all single-cache-stuff.
*
* e.g. details, description, logs, waypoints, inventory...
*/
public class CacheDetailActivity extends AbstractViewPagerActivity<CacheDetailActivity.Page>
implements CacheMenuHandler.ActivityInterface, INavigationSource, ActivitySharingInterface, EditNoteDialogListener {
private static final int MESSAGE_FAILED = -1;
private static final int MESSAGE_SUCCEEDED = 1;
private static final Pattern[] DARK_COLOR_PATTERNS = {
Pattern.compile("((?<!bg)color)=\"#" + "(0[0-9]){3}" + "\"", Pattern.CASE_INSENSITIVE),
Pattern.compile("((?<!bg)color)=\"" + "black" + "\"", Pattern.CASE_INSENSITIVE),
Pattern.compile("((?<!bg)color)=\"#" + "000080" + "\"", Pattern.CASE_INSENSITIVE) };
private static final Pattern[] LIGHT_COLOR_PATTERNS = {
Pattern.compile("((?<!bg)color)=\"#" + "([F][6-9A-F]){3}" + "\"", Pattern.CASE_INSENSITIVE),
Pattern.compile("((?<!bg)color)=\"" + "white" + "\"", Pattern.CASE_INSENSITIVE) };
public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex";
private Geocache cache;
private final Progress progress = new Progress();
private SearchResult search;
private GeoDirHandler locationUpdater;
private CharSequence clickedItemText = null;
/**
* If another activity is called and can modify the data of this activity, we refresh it on resume.
*/
private boolean refreshOnResume = false;
// some views that must be available from everywhere // TODO: Reference can block GC?
private TextView cacheDistanceView;
protected ImagesList imagesList;
private CompositeSubscription createSubscriptions;
/**
* waypoint selected in context menu. This variable will be gone when the waypoint context menu is a fragment.
*/
private Waypoint selectedWaypoint;
private boolean requireGeodata;
private Subscription geoDataSubscription = Subscriptions.empty();
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.cachedetail_activity);
createSubscriptions = new CompositeSubscription();
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = getIntent().getData();
// try to get data from extras
String name = null;
String geocode = null;
String guid = null;
if (extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
}
// When clicking a cache in MapsWithMe, we get back a PendingIntent
if (StringUtils.isEmpty(geocode)) {
geocode = MapsWithMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
final String uriHost = uri.getHost().toLowerCase(Locale.US);
final String uriPath = uri.getPath().toLowerCase(Locale.US);
final String uriQuery = uri.getQuery();
if (uriQuery != null) {
Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
} else {
Log.i("Opening URI: " + uriHost + uriPath);
}
if (uriHost.contains("geocaching.com")) {
if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
} else {
geocode = uri.getQueryParameter("wp");
guid = uri.getQueryParameter("guid");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
} else if (uriHost.contains("coord.info")) {
if (StringUtils.startsWith(uriPath, "/gc")) {
geocode = uriPath.substring(1).toUpperCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
} else if (uriHost.contains("opencaching.de") || uriHost.contains("opencaching.fr")) {
if (StringUtils.startsWith(uriPath, "/oc")) {
geocode = uriPath.substring(1).toUpperCase(Locale.US);
} else {
geocode = uri.getQueryParameter("wp");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
} else {
showToast(res.getString(R.string.err_detail_open));
finish();
return;
}
}
// no given data
if (geocode == null && guid == null) {
showToast(res.getString(R.string.err_detail_cache));
finish();
return;
}
// If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
setCacheTitleBar(geocode, name, null);
final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);
try {
String title = res.getString(R.string.cache);
if (StringUtils.isNotBlank(name)) {
title = name;
} else if (null != geocode && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
title = geocode;
}
progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage());
} catch (final RuntimeException ignored) {
// nothing, we lost the window
}
final int pageToOpen = savedInstanceState != null ?
savedInstanceState.getInt(STATE_PAGE_INDEX, 0) :
Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
createViewPager(pageToOpen, new OnPageSelectedListener() {
@Override
public void onPageSelected(final int position) {
if (Settings.isOpenLastDetailsPage()) {
Settings.setLastDetailsPage(position);
}
// lazy loading of cache images
if (getPage(position) == Page.IMAGES) {
loadCacheImages();
}
requireGeodata = getPage(position) == Page.DETAILS;
startOrStopGeoDataListener();
}
});
requireGeodata = pageToOpen == 1;
final String realGeocode = geocode;
final String realGuid = guid;
RxUtils.networkScheduler.createWorker().schedule(new Action0() {
@Override
public void call() {
search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null, 0, false, loadCacheHandler);
loadCacheHandler.sendMessage(Message.obtain());
}
});
locationUpdater = new CacheDetailsGeoDirHandler(this);
// If we have a newer Android device setup Android Beam for easy cache sharing
initializeAndroidBeam(this);
}
@Override
public String getAndroidBeamUri() {
return cache != null ? cache.getCgeoUrl() : null;
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_PAGE_INDEX, getCurrentItem());
}
private void startOrStopGeoDataListener() {
geoDataSubscription.unsubscribe();
if (requireGeodata) {
geoDataSubscription = locationUpdater.start(GeoDirHandler.UPDATE_GEODATA);
}
}
@Override
public void onResume() {
super.onResume();
startOrStopGeoDataListener();
if (refreshOnResume) {
notifyDataSetChanged();
refreshOnResume = false;
}
}
@Override
public void onPause() {
geoDataSubscription.unsubscribe();
super.onPause();
}
@Override
public void onDestroy() {
createSubscriptions.unsubscribe();
super.onDestroy();
}
@Override
public void onStop() {
if (cache != null) {
cache.setChangeNotificationHandler(null);
}
super.onStop();
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
switch (viewId) {
case R.id.waypoint:
menu.setHeaderTitle(selectedWaypoint.getName() + " (" + res.getString(R.string.waypoint) + ")");
getMenuInflater().inflate(R.menu.waypoint_options, menu);
final boolean isOriginalWaypoint = selectedWaypoint.getWaypointType().equals(WaypointType.ORIGINAL);
menu.findItem(R.id.menu_waypoint_reset_cache_coords).setVisible(isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_edit).setVisible(!isOriginalWaypoint);
menu.findItem(R.id.menu_waypoint_duplicate).setVisible(!isOriginalWaypoint);
final boolean userDefined = selectedWaypoint.isUserDefined() && !selectedWaypoint.getWaypointType().equals(WaypointType.ORIGINAL);
menu.findItem(R.id.menu_waypoint_delete).setVisible(userDefined);
final boolean hasCoords = selectedWaypoint.getCoords() != null;
final MenuItem defaultNavigationMenu = menu.findItem(R.id.menu_waypoint_navigate_default);
defaultNavigationMenu.setVisible(hasCoords);
defaultNavigationMenu.setTitle(NavigationAppFactory.getDefaultNavigationApplication().getName());
menu.findItem(R.id.menu_waypoint_navigate).setVisible(hasCoords);
menu.findItem(R.id.menu_waypoint_caches_around).setVisible(hasCoords);
break;
default:
if (imagesList != null) {
imagesList.onCreateContextMenu(menu, view);
}
break;
}
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
// waypoints
case R.id.menu_waypoint_edit:
if (selectedWaypoint != null) {
ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(this, cache, selectedWaypoint.getId());
refreshOnResume = true;
}
return true;
case R.id.menu_waypoint_duplicate:
ensureSaved();
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
if (cache.duplicateWaypoint(selectedWaypoint)) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
}
}
}.execute();
return true;
case R.id.menu_waypoint_delete:
ensureSaved();
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(final Void... params) {
if (cache.deleteWaypoint(selectedWaypoint)) {
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return true;
}
return false;
}
@Override
protected void onPostExecute(final Boolean result) {
if (result) {
notifyDataSetChanged();
}
}
}.execute();
return true;
case R.id.menu_waypoint_navigate_default:
if (selectedWaypoint != null) {
NavigationAppFactory.startDefaultNavigationApplication(1, this, selectedWaypoint);
}
return true;
case R.id.menu_waypoint_navigate:
if (selectedWaypoint != null) {
NavigationAppFactory.showNavigationMenu(this, null, selectedWaypoint, null);
}
return true;
case R.id.menu_waypoint_caches_around:
if (selectedWaypoint != null) {
CacheListActivity.startActivityCoordinates(this, selectedWaypoint.getCoords());
}
return true;
case R.id.menu_waypoint_reset_cache_coords:
ensureSaved();
if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) {
createResetCacheCoordinatesDialog(cache, selectedWaypoint).show();
} else {
final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false);
new ResetCoordsThread(cache, handler, selectedWaypoint, true, false, progressDialog).start();
}
return true;
case R.id.menu_calendar:
CalendarAddon.addToCalendarWithIntent(this, cache);
return true;
default:
break;
}
if (imagesList != null && imagesList.onContextItemSelected(item)) {
return true;
}
return onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
CacheMenuHandler.addMenuItems(this, menu, cache);
MenuItem menuItem = menu.findItem(R.id.menu_default_navigation);
final NavigationActionProvider navAction = (NavigationActionProvider) MenuItemCompat.getActionProvider(menuItem);
if (navAction != null) {
navAction.setNavigationSource(this);
}
menuItem = menu.findItem(R.id.menu_navigate);
NavigationSelectionActionProvider.initialize(menuItem, cache);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
CacheMenuHandler.onPrepareOptionsMenu(menu, cache);
LoggingUI.onPrepareOptionsMenu(menu, cache);
menu.findItem(R.id.menu_store).setVisible(cache != null && !cache.isOffline());
menu.findItem(R.id.menu_delete).setVisible(cache != null && cache.isOffline());
menu.findItem(R.id.menu_refresh).setVisible(cache != null && cache.isOffline());
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (CacheMenuHandler.onMenuItemSelected(item, this, cache)) {
return true;
}
final int menuItem = item.getItemId();
switch (menuItem) {
case R.id.menu_delete:
dropCache();
return true;
case R.id.menu_store:
storeCache();
return true;
case R.id.menu_refresh:
refreshCache();
return true;
default:
if (NavigationAppFactory.onMenuItemSelected(item, this, cache)) {
return true;
}
if (LoggingUI.onMenuItemSelected(item, this, cache)) {
refreshOnResume = true;
return true;
}
}
return super.onOptionsItemSelected(item);
}
private static final class CacheDetailsGeoDirHandler extends GeoDirHandler {
private final WeakReference<CacheDetailActivity> activityRef;
public CacheDetailsGeoDirHandler(final CacheDetailActivity activity) {
this.activityRef = new WeakReference<>(activity);
}
@Override
public void updateGeoData(final IGeoData geo) {
final CacheDetailActivity activity = activityRef.get();
if (activity == null) {
return;
}
if (activity.cacheDistanceView == null) {
return;
}
if (geo.getCoords() != null && activity.cache != null && activity.cache.getCoords() != null) {
activity.cacheDistanceView.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(activity.cache.getCoords())));
activity.cacheDistanceView.bringToFront();
}
}
}
private final static class LoadCacheHandler extends SimpleCancellableHandler {
public LoadCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
final CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get());
if (activity == null) {
return;
}
if (activity.search == null) {
showToast(R.string.err_dwld_details_failed);
dismissProgress();
finishActivity();
return;
}
if (activity.search.getError() != null) {
activity.showToast(activity.getResources().getString(R.string.err_dwld_details_failed) + " " + activity.search.getError().getErrorString(activity.getResources()) + ".");
dismissProgress();
finishActivity();
return;
}
updateStatusMsg(activity.getResources().getString(R.string.cache_dialog_loading_details_status_render));
// Data loaded, we're ready to show it!
activity.notifyDataSetChanged();
}
}
private void updateStatusMsg(final String msg) {
final CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get());
if (activity == null) {
return;
}
setProgressMessage(activity.getResources().getString(R.string.cache_dialog_loading_details)
+ "\n\n"
+ msg);
}
@Override
public void handleCancel(final Object extra) {
finishActivity();
}
}
private void notifyDataSetChanged() {
// This might get called asynchronically when the activity is shut down
if (isFinishing()) {
return;
}
if (search == null) {
return;
}
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY);
if (cache == null) {
progress.dismiss();
showToast(res.getString(R.string.err_detail_cache_find_some));
finish();
return;
}
// allow cache to notify CacheDetailActivity when it changes so it can be reloaded
cache.setChangeNotificationHandler(new ChangeNotificationHandler(this, progress));
setCacheTitleBar(cache);
// reset imagesList so Images view page will be redrawn
imagesList = null;
reinitializeViewPager();
// rendering done! remove progress popup if any there
invalidateOptionsMenuCompatible();
progress.dismiss();
Settings.addCacheToHistory(cache.getGeocode());
}
/**
* Tries to navigate to the {@link Geocache} of this activity using the default navigation tool.
*/
@Override
public void startDefaultNavigation() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, cache);
}
/**
* Tries to navigate to the {@link Geocache} of this activity using the second default navigation tool.
*/
@Override
public void startDefaultNavigation2() {
NavigationAppFactory.startDefaultNavigationApplication(2, this, cache);
}
/**
* Wrapper for the referenced method in the xml-layout.
*/
public void goDefaultNavigation(@SuppressWarnings("unused") final View view) {
startDefaultNavigation();
}
/**
* referenced from XML view
*/
public void showNavigationMenu(@SuppressWarnings("unused") final View view) {
NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true);
}
private void loadCacheImages() {
if (imagesList != null) {
return;
}
final PageViewCreator creator = getViewCreator(Page.IMAGES);
if (creator == null) {
return;
}
final View imageView = creator.getView(null);
if (imageView == null) {
return;
}
imagesList = new ImagesList(this, cache.getGeocode());
createSubscriptions.add(imagesList.loadImages(imageView, cache.getImages(), false));
}
public static void startActivity(final Context context, final String geocode) {
final Intent detailIntent = new Intent(context, CacheDetailActivity.class);
detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
context.startActivity(detailIntent);
}
/**
* Enum of all possible pages with methods to get the view and a title.
*/
public enum Page {
DETAILS(R.string.detail),
DESCRIPTION(R.string.cache_description),
LOGS(R.string.cache_logs),
LOGSFRIENDS(R.string.cache_logs_friends_and_own),
WAYPOINTS(R.string.cache_waypoints),
INVENTORY(R.string.cache_inventory),
IMAGES(R.string.cache_images);
final private int titleStringId;
Page(final int titleStringId) {
this.titleStringId = titleStringId;
}
}
private class AttributeViewBuilder {
private ViewGroup attributeIconsLayout; // layout for attribute icons
private ViewGroup attributeDescriptionsLayout; // layout for attribute descriptions
private boolean attributesShowAsIcons = true; // default: show icons
/**
* If the cache is from a non GC source, it might be without icons. Disable switching in those cases.
*/
private boolean noAttributeIconsFound = false;
private int attributeBoxMaxWidth;
public void fillView(final LinearLayout attributeBox) {
// first ensure that the view is empty
attributeBox.removeAllViews();
// maximum width for attribute icons is screen width - paddings of parents
attributeBoxMaxWidth = Compatibility.getDisplayWidth();
ViewParent child = attributeBox;
do {
if (child instanceof View) {
attributeBoxMaxWidth -= ((View) child).getPaddingLeft() + ((View) child).getPaddingRight();
}
child = child.getParent();
} while (child != null);
// delete views holding description / icons
attributeDescriptionsLayout = null;
attributeIconsLayout = null;
attributeBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
// toggle between attribute icons and descriptions
toggleAttributeDisplay(attributeBox, attributeBoxMaxWidth);
}
});
// icons or text?
// also show icons when noAttributeImagesFound == true. Explanation:
// 1. no icons could be found in the first invocation of this method
// 2. user refreshes cache from web
// 3. now this method is called again
// 4. attributeShowAsIcons is false but noAttributeImagesFound is true
// => try to show them now
if (attributesShowAsIcons || noAttributeIconsFound) {
showAttributeIcons(attributeBox, attributeBoxMaxWidth);
} else {
showAttributeDescriptions(attributeBox);
}
}
/**
* lazy-creates the layout holding the icons of the caches attributes
* and makes it visible
*/
private void showAttributeIcons(final LinearLayout attribBox, final int parentWidth) {
if (attributeIconsLayout == null) {
attributeIconsLayout = createAttributeIconsLayout(parentWidth);
// no matching icons found? show text
if (noAttributeIconsFound) {
showAttributeDescriptions(attribBox);
return;
}
}
attribBox.removeAllViews();
attribBox.addView(attributeIconsLayout);
attributesShowAsIcons = true;
}
/**
* lazy-creates the layout holding the descriptions of the caches attributes
* and makes it visible
*/
private void showAttributeDescriptions(final LinearLayout attribBox) {
if (attributeDescriptionsLayout == null) {
attributeDescriptionsLayout = createAttributeDescriptionsLayout(attribBox);
}
attribBox.removeAllViews();
attribBox.addView(attributeDescriptionsLayout);
attributesShowAsIcons = false;
}
/**
* toggle attribute descriptions and icons
*/
private void toggleAttributeDisplay(final LinearLayout attribBox, final int parentWidth) {
// Don't toggle when there are no icons to show.
if (noAttributeIconsFound) {
return;
}
// toggle
if (attributesShowAsIcons) {
showAttributeDescriptions(attribBox);
} else {
showAttributeIcons(attribBox, parentWidth);
}
}
private ViewGroup createAttributeIconsLayout(final int parentWidth) {
final LinearLayout rows = new LinearLayout(CacheDetailActivity.this);
rows.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
rows.setOrientation(LinearLayout.VERTICAL);
LinearLayout attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
noAttributeIconsFound = true;
for (final String attributeName : cache.getAttributes()) {
// check if another attribute icon fits in this row
attributeRow.measure(0, 0);
final int rowWidth = attributeRow.getMeasuredWidth();
final FrameLayout fl = (FrameLayout) getLayoutInflater().inflate(R.layout.attribute_image, attributeRow, false);
final ImageView iv = (ImageView) fl.getChildAt(0);
if ((parentWidth - rowWidth) < iv.getLayoutParams().width) {
// make a new row
attributeRow = newAttributeIconsRow();
rows.addView(attributeRow);
}
final boolean strikeThrough = !CacheAttribute.isEnabled(attributeName);
final CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib != null) {
noAttributeIconsFound = false;
Drawable d = res.getDrawable(attrib.drawableId);
iv.setImageDrawable(d);
// strike through?
if (strikeThrough) {
// generate strike through image with same properties as attribute image
final ImageView strikeThroughImage = new ImageView(CacheDetailActivity.this);
strikeThroughImage.setLayoutParams(iv.getLayoutParams());
d = res.getDrawable(R.drawable.attribute__strikethru);
strikeThroughImage.setImageDrawable(d);
fl.addView(strikeThroughImage);
}
} else {
final Drawable d = res.getDrawable(R.drawable.attribute_unknown);
iv.setImageDrawable(d);
}
attributeRow.addView(fl);
}
return rows;
}
private LinearLayout newAttributeIconsRow() {
final LinearLayout rowLayout = new LinearLayout(CacheDetailActivity.this);
rowLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
return rowLayout;
}
private ViewGroup createAttributeDescriptionsLayout(final LinearLayout parentView) {
final LinearLayout descriptions = (LinearLayout) getLayoutInflater().inflate(
R.layout.attribute_descriptions, parentView, false);
final TextView attribView = (TextView) descriptions.getChildAt(0);
final StringBuilder buffer = new StringBuilder();
for (String attributeName : cache.getAttributes()) {
final boolean enabled = CacheAttribute.isEnabled(attributeName);
// search for a translation of the attribute
final CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName));
if (attrib != null) {
attributeName = attrib.getL10n(enabled);
}
if (buffer.length() > 0) {
buffer.append('\n');
}
buffer.append(attributeName);
}
attribView.setText(buffer);
return descriptions;
}
}
private void refreshCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isNetworkConnected(getApplicationContext())) {
showToast(getString(R.string.err_server));
return;
}
final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler(this, progress);
progress.show(this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage());
cache.refresh(refreshCacheHandler, RxUtils.networkScheduler);
}
private void dropCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
progress.show(this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
cache.drop(new ChangeNotificationHandler(this, progress), RxUtils.networkScheduler);
}
private void storeCache() {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForListSelection(R.string.list_title,
new Action1<Integer>() {
@Override
public void call(final Integer selectedListId) {
storeCache(selectedListId, new StoreCacheHandler(CacheDetailActivity.this, progress));
}
}, true, StoredList.TEMPORARY_LIST.id);
} else {
storeCache(StoredList.TEMPORARY_LIST.id, new StoreCacheHandler(this, progress));
}
}
/**
* Creator for details-view.
*/
private class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
/**
* Reference to the details list, so that the helper-method can access it without an additional argument
*/
private LinearLayout detailsList;
private Thread watchlistThread;
@Override
public ScrollView getDispatchedView(final ViewGroup parentView) {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cachedetail_details_page, parentView, false);
// Start loading preview map
AndroidObservable.bindActivity(CacheDetailActivity.this, previewMap).subscribeOn(RxUtils.networkScheduler)
.subscribe(new Action1<BitmapDrawable>() {
@Override
public void call(final BitmapDrawable image) {
final Bitmap bitmap = image.getBitmap();
if (bitmap != null && bitmap.getWidth() > 10) {
final ImageView imageView = ButterKnife.findById(view, R.id.map_preview);
imageView.setImageDrawable(image);
view.findViewById(R.id.map_preview_box).setVisibility(View.VISIBLE);
}
}
});
detailsList = ButterKnife.findById(view, R.id.details_list);
final CacheDetailsCreator details = new CacheDetailsCreator(CacheDetailActivity.this, detailsList);
// cache name (full name)
final Spannable span = (new Spannable.Factory()).newSpannable(cache.getName());
if (cache.isDisabled() || cache.isArchived()) { // strike
span.setSpan(new StrikethroughSpan(), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (cache.isArchived()) {
span.setSpan(new ForegroundColorSpan(res.getColor(R.color.archived_cache_color)), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
addContextMenu(details.add(R.string.cache_name, span));
details.add(R.string.cache_type, cache.getType().getL10n());
details.addSize(cache);
addContextMenu(details.add(R.string.cache_geocode, cache.getGeocode()));
details.addCacheState(cache);
details.addDistance(cache, cacheDistanceView);
cacheDistanceView = details.getValueView();
details.addDifficulty(cache);
details.addTerrain(cache);
details.addRating(cache);
// favorite count
if (cache.getFavoritePoints() > 0) {
details.add(R.string.cache_favorite, cache.getFavoritePoints() + "×");
}
// own rating
if (cache.getMyVote() > 0) {
details.addStars(R.string.cache_own_rating, cache.getMyVote());
}
// cache author
if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) {
final TextView ownerView = details.add(R.string.cache_owner, "");
if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) {
ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE);
} else { // OwnerReal guaranteed to be not blank based on above
ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE);
}
ownerView.setOnClickListener(new OwnerActionsClickListener(cache));
}
// hidden or event date
final TextView hiddenView = details.addHiddenDate(cache);
if (hiddenView != null) {
addContextMenu(hiddenView);
}
// cache location
if (StringUtils.isNotBlank(cache.getLocation())) {
details.add(R.string.cache_location, cache.getLocation());
}
// cache coordinates
if (cache.getCoords() != null) {
final TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString());
valueView.setOnClickListener(new CoordinatesFormatSwitcher(cache.getCoords()));
addContextMenu(valueView);
}
// cache attributes
if (!cache.getAttributes().isEmpty()) {
final LinearLayout innerLayout = ButterKnife.findById(view, R.id.attributes_innerbox);
new AttributeViewBuilder().fillView(innerLayout);
view.findViewById(R.id.attributes_box).setVisibility(View.VISIBLE);
}
updateOfflineBox(view, cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener());
// watchlist
final Button buttonWatchlistAdd = ButterKnife.findById(view, R.id.add_to_watchlist);
final Button buttonWatchlistRemove = ButterKnife.findById(view, R.id.remove_from_watchlist);
buttonWatchlistAdd.setOnClickListener(new AddToWatchlistClickListener());
buttonWatchlistRemove.setOnClickListener(new RemoveFromWatchlistClickListener());
updateWatchlistBox();
// favorite points
final Button buttonFavPointAdd = ButterKnife.findById(view, R.id.add_to_favpoint);
final Button buttonFavPointRemove = ButterKnife.findById(view, R.id.remove_from_favpoint);
buttonFavPointAdd.setOnClickListener(new FavoriteAddClickListener());
buttonFavPointRemove.setOnClickListener(new FavoriteRemoveClickListener());
updateFavPointBox();
// list
final Button buttonChangeList = ButterKnife.findById(view, R.id.change_list);
buttonChangeList.setOnClickListener(new ChangeListClickListener());
updateListBox();
final IConnector connector = ConnectorFactory.getConnector(cache);
final String license = connector.getLicenseText(cache);
if (StringUtils.isNotBlank(license)) {
view.findViewById(R.id.license_box).setVisibility(View.VISIBLE);
final TextView licenseView = (ButterKnife.findById(view, R.id.license));
licenseView.setText(Html.fromHtml(license), BufferType.SPANNABLE);
licenseView.setClickable(true);
licenseView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
} else {
view.findViewById(R.id.license_box).setVisibility(View.GONE);
}
return view;
}
private class StoreCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
storeCache();
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
refreshCache();
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
dropCache();
}
}
/**
* Abstract Listener for add / remove buttons for watchlist
*/
private abstract class AbstractWatchlistClickListener implements View.OnClickListener {
public void doExecute(final int titleId, final int messageId, final Thread thread) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_watchlist_still_managing));
return;
}
progress.show(CacheDetailActivity.this, res.getString(titleId), res.getString(messageId), true, null);
if (watchlistThread != null) {
watchlistThread.interrupt();
}
watchlistThread = thread;
watchlistThread.start();
}
}
/**
* Listener for "add to watchlist" button
*/
private class AddToWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_add_title,
R.string.cache_dialog_watchlist_add_message,
new WatchlistAddThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress)));
}
}
/**
* Listener for "remove from watchlist" button
*/
private class RemoveFromWatchlistClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_watchlist_remove_title,
R.string.cache_dialog_watchlist_remove_message,
new WatchlistRemoveThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress)));
}
}
/** Thread to add this cache to the watchlist of the user */
private class WatchlistAddThread extends Thread {
private final Handler handler;
public WatchlistAddThread(final Handler handler) {
this.handler = handler;
}
@Override
public void run() {
watchlistThread = null;
Message msg;
if (ConnectorFactory.getConnector(cache).addToWatchlist(cache)) {
msg = Message.obtain(handler, MESSAGE_SUCCEEDED);
} else {
msg = Message.obtain(handler, MESSAGE_FAILED);
final Bundle bundle = new Bundle();
bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_watchlist_failed));
msg.setData(bundle);
}
handler.sendMessage(msg);
}
}
/** Thread to remove this cache from the watchlist of the user */
private class WatchlistRemoveThread extends Thread {
private final Handler handler;
public WatchlistRemoveThread(final Handler handler) {
this.handler = handler;
}
@Override
public void run() {
watchlistThread = null;
Message msg;
if (ConnectorFactory.getConnector(cache).removeFromWatchlist(cache)) {
msg = Message.obtain(handler, MESSAGE_SUCCEEDED);
} else {
msg = Message.obtain(handler, MESSAGE_FAILED);
final Bundle bundle = new Bundle();
bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_watchlist_failed));
msg.setData(bundle);
}
handler.sendMessage(msg);
}
}
/** Thread to add this cache to the favorite list of the user */
private class FavoriteAddThread extends Thread {
private final Handler handler;
public FavoriteAddThread(final Handler handler) {
this.handler = handler;
}
@Override
public void run() {
watchlistThread = null;
Message msg;
if (GCConnector.addToFavorites(cache)) {
msg = Message.obtain(handler, MESSAGE_SUCCEEDED);
} else {
msg = Message.obtain(handler, MESSAGE_FAILED);
final Bundle bundle = new Bundle();
bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_favorite_failed));
msg.setData(bundle);
}
handler.sendMessage(msg);
}
}
/** Thread to remove this cache to the favorite list of the user */
private class FavoriteRemoveThread extends Thread {
private final Handler handler;
public FavoriteRemoveThread(final Handler handler) {
this.handler = handler;
}
@Override
public void run() {
watchlistThread = null;
Message msg;
if (GCConnector.removeFromFavorites(cache)) {
msg = Message.obtain(handler, MESSAGE_SUCCEEDED);
} else {
msg = Message.obtain(handler, MESSAGE_FAILED);
final Bundle bundle = new Bundle();
bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_favorite_failed));
msg.setData(bundle);
}
handler.sendMessage(msg);
}
}
/**
* Listener for "add to favorites" button
*/
private class FavoriteAddClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_add_title,
R.string.cache_dialog_favorite_add_message,
new FavoriteAddThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress)));
}
}
/**
* Listener for "remove from favorites" button
*/
private class FavoriteRemoveClickListener extends AbstractWatchlistClickListener {
@Override
public void onClick(final View arg0) {
doExecute(R.string.cache_dialog_favorite_remove_title,
R.string.cache_dialog_favorite_remove_message,
new FavoriteRemoveThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress)));
}
}
/**
* Listener for "change list" button
*/
private class ChangeListClickListener implements View.OnClickListener {
@Override
public void onClick(final View view) {
new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title,
new Action1<Integer>() {
@Override
public void call(final Integer selectedListId) {
switchListById(selectedListId);
}
}, true, cache.getListId());
}
}
/**
* move cache to another list
*
* @param listId
* the ID of the list
*/
public void switchListById(final int listId) {
if (listId < 0) {
return;
}
Settings.saveLastList(listId);
DataStore.moveToList(cache, listId);
updateListBox();
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateWatchlistBox() {
final LinearLayout layout = ButterKnife.findById(view, R.id.watchlist_box);
final boolean supportsWatchList = cache.supportsWatchList();
layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE);
if (!supportsWatchList) {
return;
}
final Button buttonAdd = ButterKnife.findById(view, R.id.add_to_watchlist);
final Button buttonRemove = ButterKnife.findById(view, R.id.remove_from_watchlist);
final TextView text = ButterKnife.findById(view, R.id.watchlist_text);
if (cache.isOnWatchlist() || cache.isOwner()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_watchlist_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_watchlist_not_on);
}
// the owner of a cache has it always on his watchlist. Adding causes an error
if (cache.isOwner()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides buttons, sets text in watchlist box
*/
private void updateFavPointBox() {
final LinearLayout layout = ButterKnife.findById(view, R.id.favpoint_box);
final boolean supportsFavoritePoints = cache.supportsFavoritePoints();
layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE);
if (!supportsFavoritePoints || cache.isOwner() || !Settings.isGCPremiumMember()) {
return;
}
final Button buttonAdd = ButterKnife.findById(view, R.id.add_to_favpoint);
final Button buttonRemove = ButterKnife.findById(view, R.id.remove_from_favpoint);
final TextView text = ButterKnife.findById(view, R.id.favpoint_text);
if (cache.isFavorite()) {
buttonAdd.setVisibility(View.GONE);
buttonRemove.setVisibility(View.VISIBLE);
text.setText(R.string.cache_favpoint_on);
} else {
buttonAdd.setVisibility(View.VISIBLE);
buttonRemove.setVisibility(View.GONE);
text.setText(R.string.cache_favpoint_not_on);
}
// Add/remove to Favorites is only possible if the cache has been found
if (!cache.isFound()) {
buttonAdd.setEnabled(false);
buttonAdd.setVisibility(View.GONE);
buttonRemove.setEnabled(false);
buttonRemove.setVisibility(View.GONE);
}
}
/**
* shows/hides/updates list box
*/
private void updateListBox() {
final View box = view.findViewById(R.id.list_box);
if (cache.isOffline()) {
// show box
box.setVisibility(View.VISIBLE);
// update text
final TextView text = ButterKnife.findById(view, R.id.list_text);
final StoredList list = DataStore.getList(cache.getListId());
if (list != null) {
text.setText(res.getString(R.string.cache_list_text) + " " + list.title);
} else {
// this should not happen
text.setText(R.string.cache_list_unknown);
}
} else {
// hide box
box.setVisibility(View.GONE);
}
}
}
private final Observable<BitmapDrawable> previewMap = Observable.create(new OnSubscribe<BitmapDrawable>() {
@Override
public void call(final Subscriber<? super BitmapDrawable> subscriber) {
try {
// persistent preview from storage
Bitmap image = StaticMapsProvider.getPreviewMap(cache);
if (image == null) {
if (Settings.isStoreOfflineMaps() && cache.getCoords() != null) {
RxUtils.waitForCompletion(StaticMapsProvider.storeCachePreviewMap(cache));
image = StaticMapsProvider.getPreviewMap(cache);
}
}
if (image != null) {
subscriber.onNext(ImageUtils.scaleBitmapToFitDisplay(image));
}
subscriber.onCompleted();
} catch (final Exception e) {
Log.w("CacheDetailActivity.previewMap", e);
subscriber.onError(e);
}
}
});
protected class DescriptionViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@InjectView(R.id.personalnote) protected TextView personalNoteView;
@InjectView(R.id.shortdesc) protected IndexOutOfBoundsAvoidingTextView shortDescView;
@InjectView(R.id.longdesc) protected IndexOutOfBoundsAvoidingTextView longDescView;
@InjectView(R.id.show_description) protected Button showDesc;
@InjectView(R.id.loading) protected View loadingView;
@Override
public ScrollView getDispatchedView(final ViewGroup parentView) {
if (cache == null) {
// something is really wrong
return null;
}
view = (ScrollView) getLayoutInflater().inflate(R.layout.cachedetail_description_page, parentView, false);
ButterKnife.inject(this, view);
// cache short description
if (StringUtils.isNotBlank(cache.getShortDescription())) {
loadDescription(cache.getShortDescription(), shortDescView, null);
}
// long description
if (StringUtils.isNotBlank(cache.getDescription())) {
if (Settings.isAutoLoadDescription()) {
loadLongDescription();
} else {
showDesc.setVisibility(View.VISIBLE);
showDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View arg0) {
loadLongDescription();
}
});
}
}
// cache personal note
setPersonalNote(personalNoteView, cache.getPersonalNote());
personalNoteView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
addContextMenu(personalNoteView);
final Button personalNoteEdit = ButterKnife.findById(view, R.id.edit_personalnote);
personalNoteEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
ensureSaved();
editPersonalNote(cache, CacheDetailActivity.this);
}
});
final Button personalNoteUpload = ButterKnife.findById(view, R.id.upload_personalnote);
if (cache.isOffline() && ConnectorFactory.getConnector(cache).supportsPersonalNote()) {
personalNoteUpload.setVisibility(View.VISIBLE);
personalNoteUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (StringUtils.length(cache.getPersonalNote()) > GCConstants.PERSONAL_NOTE_MAX_CHARS) {
warnPersonalNoteExceedsLimit();
} else {
uploadPersonalNote();
}
}
});
} else {
personalNoteUpload.setVisibility(View.GONE);
}
// cache hint and spoiler images
final View hintBoxView = view.findViewById(R.id.hint_box);
if (StringUtils.isNotBlank(cache.getHint()) || CollectionUtils.isNotEmpty(cache.getSpoilers())) {
hintBoxView.setVisibility(View.VISIBLE);
} else {
hintBoxView.setVisibility(View.GONE);
}
final TextView hintView = (ButterKnife.findById(view, R.id.hint));
if (StringUtils.isNotBlank(cache.getHint())) {
if (TextUtils.containsHtml(cache.getHint())) {
hintView.setText(Html.fromHtml(cache.getHint(), new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null), TextView.BufferType.SPANNABLE);
hintView.setText(CryptUtils.rot13((Spannable) hintView.getText()));
}
else {
hintView.setText(CryptUtils.rot13(cache.getHint()));
}
hintView.setVisibility(View.VISIBLE);
hintView.setClickable(true);
hintView.setOnClickListener(new DecryptTextClickListener(hintView));
hintBoxView.setOnClickListener(new DecryptTextClickListener(hintView));
hintBoxView.setClickable(true);
addContextMenu(hintView);
} else {
hintView.setVisibility(View.GONE);
hintView.setClickable(false);
hintView.setOnClickListener(null);
hintBoxView.setClickable(false);
hintBoxView.setOnClickListener(null);
}
final TextView spoilerlinkView = (ButterKnife.findById(view, R.id.hint_spoilerlink));
if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
spoilerlinkView.setVisibility(View.VISIBLE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View arg0) {
if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) {
showToast(res.getString(R.string.err_detail_no_spoiler));
return;
}
ImagesActivity.startActivitySpoilerImages(CacheDetailActivity.this, cache.getGeocode(), cache.getSpoilers());
}
});
} else {
spoilerlinkView.setVisibility(View.GONE);
spoilerlinkView.setClickable(true);
spoilerlinkView.setOnClickListener(null);
}
return view;
}
Thread currentThread;
private void uploadPersonalNote() {
final SimpleCancellableHandler myHandler = new SimpleCancellableHandler(CacheDetailActivity.this, progress);
final Message cancelMessage = myHandler.cancelMessage(res.getString(R.string.cache_personal_note_upload_cancelled));
progress.show(CacheDetailActivity.this, res.getString(R.string.cache_personal_note_uploading), res.getString(R.string.cache_personal_note_uploading), true, cancelMessage);
if (currentThread != null) {
currentThread.interrupt();
}
currentThread = new UploadPersonalNoteThread(cache, myHandler);
currentThread.start();
}
private void loadLongDescription() {
showDesc.setVisibility(View.GONE);
showDesc.setOnClickListener(null);
loadingView.setVisibility(View.VISIBLE);
final String longDescription = cache.getDescription();
loadDescription(longDescription, longDescView, loadingView);
}
private void warnPersonalNoteExceedsLimit() {
Dialogs.confirm(CacheDetailActivity.this, R.string.cache_personal_note_limit, getString(R.string.cache_personal_note_truncation, GCConstants.PERSONAL_NOTE_MAX_CHARS),
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
uploadPersonalNote();
}
});
}
}
// If description has an HTML construct which may be problematic to render, add a note at the end of the long description.
// Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though
// sometimes technically incorrect.
private void addWarning(final UnknownTagsHandler unknownTagsHandler, final Spanned description) {
if (unknownTagsHandler.isProblematicDetected()) {
final int startPos = description.length();
final IConnector connector = ConnectorFactory.getConnector(cache);
final Spanned tableNote = Html.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"));
((Editable) description).append("\n\n").append(tableNote);
((Editable) description).setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* Load the description in the background.
* @param descriptionString the HTML description as retrieved from the connector
* @param descriptionView the view to fill
* @param loadingIndicatorView the loading indicator view, will be hidden when completed
*/
private void loadDescription(final String descriptionString, final IndexOutOfBoundsAvoidingTextView descriptionView, final View loadingIndicatorView) {
try {
final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler();
final Spanned description = Html.fromHtml(descriptionString, new HtmlImage(cache.getGeocode(), true, cache.getListId(), false, descriptionView), unknownTagsHandler);
addWarning(unknownTagsHandler, description);
if (StringUtils.isNotBlank(descriptionString)) {
try {
descriptionView.setText(description, TextView.BufferType.SPANNABLE);
} catch (final Exception e) {
Log.e("Android bug setting text: ", e);
// remove the formatting by converting to a simple string
descriptionView.setText(description.toString());
}
descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
fixTextColor(descriptionString, descriptionView);
descriptionView.setVisibility(View.VISIBLE);
addContextMenu(descriptionView);
potentiallyHideShortDescription();
}
if (null != loadingIndicatorView) {
loadingIndicatorView.setVisibility(View.GONE);
}
} catch (final Exception ignored) {
showToast(res.getString(R.string.err_load_descr_failed));
}
}
private static void fixTextColor(final String descriptionString, final IndexOutOfBoundsAvoidingTextView descriptionView) {
int backcolor;
if (Settings.isLightSkin()) {
backcolor = color.white;
for (final Pattern pattern : LIGHT_COLOR_PATTERNS) {
final MatcherWrapper matcher = new MatcherWrapper(pattern, descriptionString);
if (matcher.find()) {
descriptionView.setBackgroundResource(color.darker_gray);
return;
}
}
} else {
backcolor = color.black;
for (final Pattern pattern : DARK_COLOR_PATTERNS) {
final MatcherWrapper matcher = new MatcherWrapper(pattern, descriptionString);
if (matcher.find()) {
descriptionView.setBackgroundResource(color.darker_gray);
return;
}
}
}
descriptionView.setBackgroundResource(backcolor);
}
/**
* Hide the short description, if it is contained somewhere at the start of the long description.
*/
public void potentiallyHideShortDescription() {
final View shortView = ButterKnife.findById(this, R.id.shortdesc);
if (shortView == null) {
return;
}
if (shortView.getVisibility() == View.GONE) {
return;
}
final String shortDescription = cache.getShortDescription();
if (StringUtils.isNotBlank(shortDescription)) {
final int index = StringUtils.indexOf(cache.getDescription(), shortDescription);
// allow up to 200 characters of HTML formatting
if (index >= 0 && index < 200) {
shortView.setVisibility(View.GONE);
}
}
}
private void ensureSaved() {
if (!cache.isOffline()) {
showToast(getString(R.string.info_cache_saved));
cache.setListId(StoredList.STANDARD_LIST_ID);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... params) {
DataStore.saveCache(cache, LoadFlags.SAVE_ALL);
return null;
}
}.execute();
}
}
private class WaypointsViewCreator extends AbstractCachingPageViewCreator<ListView> {
private final int VISITED_INSET = (int) (6.6f * CgeoApplication.getInstance().getResources().getDisplayMetrics().density + 0.5f);
@Override
public ListView getDispatchedView(final ViewGroup parentView) {
if (cache == null) {
// something is really wrong
return null;
}
// sort waypoints: PP, Sx, FI, OWN
final List<Waypoint> sortedWaypoints = new ArrayList<>(cache.getWaypoints());
Collections.sort(sortedWaypoints, Waypoint.WAYPOINT_COMPARATOR);
view = (ListView) getLayoutInflater().inflate(R.layout.cachedetail_waypoints_page, parentView, false);
view.setClickable(true);
final View addWaypointButton = getLayoutInflater().inflate(R.layout.cachedetail_waypoints_footer, view, false);
view.addFooterView(addWaypointButton);
addWaypointButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
ensureSaved();
EditWaypointActivity.startActivityAddWaypoint(CacheDetailActivity.this, cache);
refreshOnResume = true;
}
});
view.setAdapter(new ArrayAdapter<Waypoint>(CacheDetailActivity.this, R.layout.waypoint_item, sortedWaypoints) {
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.waypoint_item, parent, false);
rowView.setClickable(true);
rowView.setLongClickable(true);
registerForContextMenu(rowView);
}
WaypointViewHolder holder = (WaypointViewHolder) rowView.getTag();
if (null == holder) {
holder = new WaypointViewHolder(rowView);
}
final Waypoint waypoint = getItem(position);
fillViewHolder(rowView, holder, waypoint);
return rowView;
}
});
return view;
}
protected void fillViewHolder(final View rowView, final WaypointViewHolder holder, final Waypoint wpt) {
// coordinates
final TextView coordinatesView = holder.coordinatesView;
if (null != wpt.getCoords()) {
coordinatesView.setOnClickListener(new CoordinatesFormatSwitcher(wpt.getCoords()));
coordinatesView.setText(wpt.getCoords().toString());
coordinatesView.setVisibility(View.VISIBLE);
}
else {
coordinatesView.setVisibility(View.GONE);
}
// info
final String waypointInfo = Formatter.formatWaypointInfo(wpt);
final TextView infoView = holder.infoView;
if (StringUtils.isNotBlank(waypointInfo)) {
infoView.setText(waypointInfo);
infoView.setVisibility(View.VISIBLE);
}
else {
infoView.setVisibility(View.GONE);
}
// title
final TextView nameView = holder.nameView;
if (StringUtils.isNotBlank(wpt.getName())) {
nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.getName()));
} else if (null != wpt.getCoords()) {
nameView.setText(wpt.getCoords().toString());
} else {
nameView.setText(res.getString(R.string.waypoint));
}
setWaypointIcon(res, nameView, wpt);
// visited
if (wpt.isVisited()) {
final TypedValue a = new TypedValue();
getTheme().resolveAttribute(R.attr.text_color_grey, a, true);
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// really should be just a color!
nameView.setTextColor(a.data);
}
}
// note
final TextView noteView = holder.noteView;
if (StringUtils.isNotBlank(wpt.getNote())) {
noteView.setOnClickListener(new DecryptTextClickListener(noteView));
noteView.setVisibility(View.VISIBLE);
if (TextUtils.containsHtml(wpt.getNote())) {
noteView.setText(Html.fromHtml(wpt.getNote()), TextView.BufferType.SPANNABLE);
}
else {
noteView.setText(wpt.getNote());
}
}
else {
noteView.setVisibility(View.GONE);
}
final View wpNavView = holder.wpNavView;
wpNavView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
NavigationAppFactory.startDefaultNavigationApplication(1, CacheDetailActivity.this, wpt);
}
});
wpNavView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
NavigationAppFactory.startDefaultNavigationApplication(2, CacheDetailActivity.this, wpt);
return true;
}
});
addContextMenu(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
selectedWaypoint = wpt;
ensureSaved();
EditWaypointActivity.startActivityEditWaypoint(CacheDetailActivity.this, cache, wpt.getId());
refreshOnResume = true;
}
});
rowView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
selectedWaypoint = wpt;
openContextMenu(v);
return true;
}
});
}
private void setWaypointIcon(final Resources res, final TextView nameView, final Waypoint wpt) {
final WaypointType waypointType = wpt.getWaypointType();
final Drawable icon;
if (wpt.isVisited()) {
final LayerDrawable ld = new LayerDrawable(new Drawable[] {
res.getDrawable(waypointType.markerId),
res.getDrawable(R.drawable.tick) });
ld.setLayerInset(0, 0, 0, VISITED_INSET, VISITED_INSET);
ld.setLayerInset(1, VISITED_INSET, VISITED_INSET, 0, 0);
icon = ld;
} else {
icon = res.getDrawable(waypointType.markerId);
}
nameView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
}
}
private class InventoryViewCreator extends AbstractCachingPageViewCreator<ListView> {
@Override
public ListView getDispatchedView(final ViewGroup parentView) {
if (cache == null) {
// something is really wrong
return null;
}
view = (ListView) getLayoutInflater().inflate(R.layout.cachedetail_inventory_page, parentView, false);
// TODO: fix layout, then switch back to Android-resource and delete copied one
// this copy is modified to respect the text color
view.setAdapter(new ArrayAdapter<>(CacheDetailActivity.this, R.layout.simple_list_item_1, cache.getInventory()));
view.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
final Object selection = arg0.getItemAtPosition(arg2);
if (selection instanceof Trackable) {
final Trackable trackable = (Trackable) selection;
TrackableActivity.startActivity(CacheDetailActivity.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName());
}
}
});
return view;
}
}
private class ImagesViewCreator extends AbstractCachingPageViewCreator<View> {
@Override
public View getDispatchedView(final ViewGroup parentView) {
if (cache == null) {
return null; // something is really wrong
}
view = getLayoutInflater().inflate(R.layout.cachedetail_images_page, parentView, false);
if (imagesList == null && isCurrentPage(Page.IMAGES)) {
loadCacheImages();
}
return view;
}
}
public static void startActivity(final Context context, final String geocode, final String cacheName) {
final Intent cachesIntent = new Intent(context, CacheDetailActivity.class);
cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cachesIntent);
}
@Override
public void addContextMenu(final View view) {
view.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) {
switch (view.getId()) {
case R.id.value: // coordinates, gc-code, name
assert view instanceof TextView;
clickedItemText = ((TextView) view).getText();
final CharSequence itemTitle = ((TextView) ((View) view.getParent()).findViewById(R.id.name)).getText();
buildDetailsContextMenu(actionMode, menu, itemTitle, true);
return true;
case R.id.shortdesc:
clickedItemText = cache.getShortDescription();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_description), false);
return true;
case R.id.longdesc:
// combine short and long description
final String shortDesc = cache.getShortDescription();
if (StringUtils.isBlank(shortDesc)) {
clickedItemText = cache.getDescription();
} else {
clickedItemText = shortDesc + "\n\n" + cache.getDescription();
}
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_description), false);
return true;
case R.id.personalnote:
clickedItemText = cache.getPersonalNote();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_personal_note), true);
return true;
case R.id.hint:
clickedItemText = cache.getHint();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_hint), false);
return true;
case R.id.log:
assert view instanceof TextView;
clickedItemText = ((TextView) view).getText();
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_logs), false);
return true;
case R.id.date: // event date
clickedItemText = Formatter.formatHiddenDate(cache);
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_event), true);
menu.findItem(R.id.menu_calendar).setVisible(cache.canBeAddedToCalendar());
return true;
}
return false;
}
@Override
public void onDestroyActionMode(final ActionMode actionMode) {
// do nothing
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.details_context, menu);
// Return true so that the action mode is shown
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) {
switch (menuItem.getItemId()) {
// detail fields
case R.id.menu_calendar:
CalendarAddon.addToCalendarWithIntent(CacheDetailActivity.this, cache);
actionMode.finish();
return true;
// handle clipboard actions in base
default:
return onClipboardItemSelected(actionMode, menuItem, clickedItemText);
}
}
});
return true;
}
});
}
public static void startActivityGuid(final Context context, final String guid, final String cacheName) {
final Intent cacheIntent = new Intent(context, CacheDetailActivity.class);
cacheIntent.putExtra(Intents.EXTRA_GUID, guid);
cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName);
context.startActivity(cacheIntent);
}
/**
* A dialog to allow the user to select reseting coordinates local/remote/both.
*/
private AlertDialog createResetCacheCoordinatesDialog(final Geocache cache, final Waypoint wpt) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.waypoint_reset_cache_coords);
final String[] items = new String[] { res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords) };
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true);
final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1);
new ResetCoordsThread(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog).start();
}
});
return builder.create();
}
private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> {
private boolean remoteFinished = false;
private boolean localFinished = false;
private final ProgressDialog progressDialog;
private final boolean resetRemote;
protected HandlerResetCoordinates(final CacheDetailActivity activity, final ProgressDialog progressDialog, final boolean resetRemote) {
super(activity);
this.progressDialog = progressDialog;
this.resetRemote = resetRemote;
}
@Override
public void handleMessage(final Message msg) {
if (msg.what == ResetCoordsThread.LOCAL) {
localFinished = true;
} else {
remoteFinished = true;
}
if (localFinished && (remoteFinished || !resetRemote)) {
progressDialog.dismiss();
final CacheDetailActivity activity = getActivity();
if (activity != null) {
activity.notifyDataSetChanged();
}
}
}
}
private class ResetCoordsThread extends Thread {
private final Geocache cache;
private final Handler handler;
private final boolean local;
private final boolean remote;
private final Waypoint wpt;
private final ProgressDialog progress;
public static final int LOCAL = 0;
public static final int ON_WEBSITE = 1;
public ResetCoordsThread(final Geocache cache, final Handler handler, final Waypoint wpt, final boolean local, final boolean remote, final ProgressDialog progress) {
this.cache = cache;
this.handler = handler;
this.local = local;
this.remote = remote;
this.wpt = wpt;
this.progress = progress;
}
@Override
public void run() {
if (local) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords));
}
});
cache.setCoords(wpt.getCoords());
cache.setUserModifiedCoords(false);
cache.deleteWaypointForce(wpt);
DataStore.saveChangedCache(cache);
handler.sendEmptyMessage(LOCAL);
}
final IConnector con = ConnectorFactory.getConnector(cache);
if (remote && con.supportsOwnCoordinates()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website));
}
});
final boolean result = con.deleteModifiedCoordinates(cache);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (result) {
showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website));
} else {
showToast(getString(R.string.waypoint_coordinates_upload_error));
}
handler.sendEmptyMessage(ON_WEBSITE);
notifyDataSetChanged();
}
});
}
}
}
private static class UploadPersonalNoteThread extends Thread {
private Geocache cache = null;
private CancellableHandler handler = null;
public UploadPersonalNoteThread(final Geocache cache, final CancellableHandler handler) {
this.cache = cache;
this.handler = handler;
}
@Override
public void run() {
final IConnector con = ConnectorFactory.getConnector(cache);
if (con.supportsPersonalNote()) {
con.uploadPersonalNote(cache);
}
final Message msg = Message.obtain();
final Bundle bundle = new Bundle();
bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, CgeoApplication.getInstance().getString(R.string.cache_personal_note_upload_done));
msg.setData(bundle);
handler.sendMessage(msg);
}
}
@Override
protected String getTitle(final Page page) {
// show number of waypoints directly in waypoint title
if (page == Page.WAYPOINTS) {
final int waypointCount = cache.getWaypoints().size();
return res.getQuantityString(R.plurals.waypoints, waypointCount, waypointCount);
}
return res.getString(page.titleStringId);
}
@Override
protected Pair<List<? extends Page>, Integer> getOrderedPages() {
final ArrayList<Page> pages = new ArrayList<>();
pages.add(Page.WAYPOINTS);
pages.add(Page.DETAILS);
final int detailsIndex = pages.size() - 1;
pages.add(Page.DESCRIPTION);
if (!cache.getLogs().isEmpty()) {
pages.add(Page.LOGS);
}
if (CollectionUtils.isNotEmpty(cache.getFriendsLogs())) {
pages.add(Page.LOGSFRIENDS);
}
if (CollectionUtils.isNotEmpty(cache.getInventory())) {
pages.add(Page.INVENTORY);
}
if (CollectionUtils.isNotEmpty(cache.getImages())) {
pages.add(Page.IMAGES);
}
return new ImmutablePair<List<? extends Page>, Integer>(pages, detailsIndex);
}
@Override
protected AbstractViewPagerActivity.PageViewCreator createViewCreator(final Page page) {
switch (page) {
case DETAILS:
return new DetailsViewCreator();
case DESCRIPTION:
return new DescriptionViewCreator();
case LOGS:
return new CacheLogsViewCreator(this, true);
case LOGSFRIENDS:
return new CacheLogsViewCreator(this, false);
case WAYPOINTS:
return new WaypointsViewCreator();
case INVENTORY:
return new InventoryViewCreator();
case IMAGES:
return new ImagesViewCreator();
}
throw new IllegalStateException(); // cannot happen as long as switch case is enum complete
}
static void updateOfflineBox(final View view, final Geocache cache, final Resources res,
final OnClickListener refreshCacheClickListener,
final OnClickListener dropCacheClickListener,
final OnClickListener storeCacheClickListener) {
// offline use
final TextView offlineText = ButterKnife.findById(view, R.id.offline_text);
final Button offlineRefresh = ButterKnife.findById(view, R.id.offline_refresh);
final Button offlineStore = ButterKnife.findById(view, R.id.offline_store);
if (cache.isOffline()) {
final long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes
String ago;
if (diff < 15) {
ago = res.getString(R.string.cache_offline_time_mins_few);
} else if (diff < 50) {
ago = res.getString(R.string.cache_offline_time_about) + " " + diff + " " + res.getString(R.string.cache_offline_time_mins);
} else if (diff < 90) {
ago = res.getString(R.string.cache_offline_time_about) + " " + res.getString(R.string.cache_offline_time_hour);
} else if (diff < (48 * 60)) {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / 60) + " " + res.getString(R.string.cache_offline_time_hours);
} else {
ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / (24 * 60)) + " " + res.getString(R.string.cache_offline_time_days);
}
offlineText.setText(res.getString(R.string.cache_offline_stored) + "\n" + ago);
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_drop));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(dropCacheClickListener);
} else {
offlineText.setText(res.getString(R.string.cache_offline_not_ready));
offlineRefresh.setOnClickListener(refreshCacheClickListener);
offlineStore.setText(res.getString(R.string.cache_offline_store));
offlineStore.setClickable(true);
offlineStore.setOnClickListener(storeCacheClickListener);
}
offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE);
offlineRefresh.setClickable(true);
}
public Geocache getCache() {
return cache;
}
private static class StoreCacheHandler extends SimpleCancellableHandler {
public StoreCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_offline_save_message, (String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class RefreshCacheHandler extends SimpleCancellableHandler {
public RefreshCacheHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleRegularMessage(final Message msg) {
if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) {
updateStatusMsg(R.string.cache_dialog_refresh_message, (String) msg.obj);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static final class ChangeNotificationHandler extends SimpleHandler {
public ChangeNotificationHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleMessage(final Message msg) {
notifyDataSetChanged(activityRef);
}
}
private static final class SimpleUpdateHandler extends SimpleHandler {
public SimpleUpdateHandler(final CacheDetailActivity activity, final Progress progress) {
super(activity, progress);
}
@Override
public void handleMessage(final Message msg) {
if (msg.what == MESSAGE_FAILED) {
super.handleMessage(msg);
} else {
notifyDataSetChanged(activityRef);
}
}
}
private static void notifyDataSetChanged(final WeakReference<AbstractActivity> activityRef) {
final CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get());
if (activity != null) {
activity.notifyDataSetChanged();
}
}
protected void storeCache(final int listId, final StoreCacheHandler storeCacheHandler) {
progress.show(this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage());
RxUtils.networkScheduler.createWorker().schedule(new Action0() {
@Override
public void call() {
cache.store(listId, storeCacheHandler);
}
});
}
public static void editPersonalNote(final Geocache cache, final CacheDetailActivity activity) {
if (cache.isOffline()) {
final FragmentManager fm = activity.getSupportFragmentManager();
final EditNoteDialog dialog = EditNoteDialog.newInstance(cache.getPersonalNote());
dialog.show(fm, "fragment_edit_note");
}
}
@Override
public void onFinishEditNoteDialog(final String note) {
final TextView personalNoteView = ButterKnife.findById(this, R.id.personalnote);
setPersonalNote(personalNoteView, note);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(final Void... params) {
cache.setPersonalNote(note);
cache.parseWaypointsFromNote();
DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));
return null;
}
@Override
protected void onPostExecute(final Void v) {
notifyDataSetChanged();
}
}.execute();
}
private static void setPersonalNote(final TextView personalNoteView, final String personalNote) {
personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE);
if (StringUtils.isNotBlank(personalNote)) {
personalNoteView.setVisibility(View.VISIBLE);
} else {
personalNoteView.setVisibility(View.GONE);
}
}
@Override
public void navigateTo() {
startDefaultNavigation();
}
@Override
public void showNavigationMenu() {
NavigationAppFactory.showNavigationMenu(this, cache, null, null);
}
@Override
public void cachesAround() {
CacheListActivity.startActivityCoordinates(this, cache.getCoords());
}
} |
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.databinding.ImageselectActivityBinding;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.ImageActivityHelper;
import cgeo.geocaching.ui.TextSpinner;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.ImageUtils;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
public class ImageSelectActivity extends AbstractActionBarActivity {
private ImageselectActivityBinding binding;
private final TextSpinner<Integer> imageScale = new TextSpinner<>();
private static final String SAVED_STATE_IMAGE = "cgeo.geocaching.saved_state_image";
private static final String SAVED_STATE_ORIGINAL_IMAGE = "cgeo.geocaching.saved_state_original_image";
private static final String SAVED_STATE_IMAGE_INDEX = "cgeo.geocaching.saved_state_image_index";
private static final String SAVED_STATE_IMAGE_SCALE = "cgeo.geocaching.saved_state_image_scale";
private static final String SAVED_STATE_MAX_IMAGE_UPLOAD_SIZE = "cgeo.geocaching.saved_state_max_image_upload_size";
private static final String SAVED_STATE_IMAGE_CAPTION_MANDATORY = "cgeo.geocaching.saved_state_image_caption_mandatory";
private static final String SAVED_STATE_GEOCODE = "cgeo.geocaching.saved_state_geocode";
private static final String SAVED_STATE_IMAGEHELPER = "cgeo.geocaching.saved_state_imagehelper";
private Image originalImage;
private Image image;
private int imageIndex = -1;
private long maxImageUploadSize;
private boolean imageCaptionMandatory;
@Nullable private String geocode;
private final ImageActivityHelper imageActivityHelper = new ImageActivityHelper(this, (rc, imgs, uk) -> {
deleteImageFromDeviceIfNotOriginal(image);
image = imgs.isEmpty() ? null : ImageUtils.toLocalLogImage(geocode, imgs.get(0));
loadImagePreview();
});
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setThemeAndContentView(R.layout.imageselect_activity);
binding = ImageselectActivityBinding.bind(findViewById(R.id.imageselect_activity_viewroot));
imageScale.setSpinner(findViewById(R.id.logImageScale))
.setValues(Arrays.asList(ArrayUtils.toObject(getResources().getIntArray(R.array.log_image_scale_values))))
.setChangeListener(Settings::setLogImageScale);
// Get parameters from intent and basic cache information from database
final Bundle extras = getIntent().getExtras();
if (extras != null) {
image = extras.getParcelable(Intents.EXTRA_IMAGE);
originalImage = image;
imageIndex = extras.getInt(Intents.EXTRA_INDEX, -1);
maxImageUploadSize = extras.getLong(Intents.EXTRA_MAX_IMAGE_UPLOAD_SIZE);
imageCaptionMandatory = extras.getBoolean(Intents.EXTRA_IMAGE_CAPTION_MANDATORY);
geocode = extras.getString(Intents.EXTRA_GEOCODE);
//try to find a good title from what we got
final String context = extras.getString(Intents.EXTRA_GEOCODE);
if (StringUtils.isBlank(context)) {
setTitle(getString(R.string.cache_image));
} else {
final Geocache cache = DataStore.loadCache(context, LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
setCacheTitleBar(cache);
} else {
setTitle(context + ": " + getString(R.string.cache_image));
}
}
}
// Restore previous state
if (savedInstanceState != null) {
image = savedInstanceState.getParcelable(SAVED_STATE_IMAGE);
originalImage = savedInstanceState.getParcelable(SAVED_STATE_ORIGINAL_IMAGE);
imageIndex = savedInstanceState.getInt(SAVED_STATE_IMAGE_INDEX, -1);
imageScale.set(savedInstanceState.getInt(SAVED_STATE_IMAGE_SCALE));
maxImageUploadSize = savedInstanceState.getLong(SAVED_STATE_MAX_IMAGE_UPLOAD_SIZE);
imageCaptionMandatory = savedInstanceState.getBoolean(SAVED_STATE_IMAGE_CAPTION_MANDATORY);
geocode = savedInstanceState.getString(SAVED_STATE_GEOCODE);
imageActivityHelper.setState(savedInstanceState.getBundle(SAVED_STATE_IMAGEHELPER));
}
if (image == null) {
image = Image.NONE;
imageScale.set(Settings.getLogImageScale());
} else {
imageScale.set(image.targetScale);
}
updateScaleValueDisplay();
binding.camera.setOnClickListener(view -> selectImageFromCamera());
binding.stored.setOnClickListener(view -> selectImageFromStorage());
if (image.hasTitle()) {
binding.caption.setText(image.getTitle());
Dialogs.moveCursorToEnd(binding.caption);
}
if (image.hasDescription()) {
binding.description.setText(image.getDescription());
Dialogs.moveCursorToEnd(binding.caption);
}
binding.save.setOnClickListener(v -> saveImageInfo(true, false));
binding.cancel.setOnClickListener(v -> saveImageInfo(false, false));
binding.delete.setOnClickListener(v -> saveImageInfo(false, true));
binding.delete.setVisibility(imageIndex >= 0 ? View.VISIBLE : View.GONE);
loadImagePreview();
}
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
syncEditTexts();
outState.putParcelable(SAVED_STATE_IMAGE, image);
outState.putParcelable(SAVED_STATE_ORIGINAL_IMAGE, originalImage);
outState.putInt(SAVED_STATE_IMAGE_INDEX, imageIndex);
outState.putInt(SAVED_STATE_IMAGE_SCALE, imageScale.get());
outState.putLong(SAVED_STATE_MAX_IMAGE_UPLOAD_SIZE, maxImageUploadSize);
outState.putBoolean(SAVED_STATE_IMAGE_CAPTION_MANDATORY, imageCaptionMandatory);
outState.putString(SAVED_STATE_GEOCODE, geocode);
outState.putBundle(SAVED_STATE_IMAGEHELPER, imageActivityHelper.getState());
}
public void saveImageInfo(final boolean saveInfo, final boolean deleteImage) {
if (saveInfo) {
final Intent intent = new Intent();
syncEditTexts();
intent.putExtra(Intents.EXTRA_IMAGE, image);
intent.putExtra(Intents.EXTRA_INDEX, imageIndex);
//"originalImage" is now obsolete. But we never delete originalImage (in case log gets not stored)
setResult(RESULT_OK, intent);
finish();
} else if (deleteImage) {
final Intent intent = new Intent();
intent.putExtra(Intents.EXTRA_DELETE_FLAG, true);
intent.putExtra(Intents.EXTRA_INDEX, imageIndex);
setResult(RESULT_OK, intent);
deleteImageFromDeviceIfNotOriginal(image);
//original image is now obsolete. BUt we never delete original Image (in case log gets not stored)
finish();
} else {
deleteImageFromDeviceIfNotOriginal(image);
setResult(RESULT_CANCELED);
finish();
}
}
private void syncEditTexts() {
image = new Image.Builder()
.setUrl(image.uri)
.setTitle(binding.caption.getText().toString())
.setTargetScale(imageScale.get())
.setDescription(binding.description.getText().toString())
.build();
}
private void selectImageFromCamera() {
imageActivityHelper.getImageFromCamera(this.geocode, false, null);
}
private void selectImageFromStorage() {
imageActivityHelper.getImageFromStorage(this.geocode, false, null);
}
private boolean deleteImageFromDeviceIfNotOriginal(final Image img) {
if (img != null && img.getUri() != null && (originalImage == null || !img.getUri().equals(originalImage.getUri()))) {
return ImageUtils.deleteImage(img.getUri());
}
return false;
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data); // call super to make lint happy
imageActivityHelper.onActivityResult(requestCode, resultCode, data);
}
private void loadImagePreview() {
ImageActivityHelper.displayImageAsync(image, binding.imagePreview);
updateScaleValueDisplay();
}
private void updateScaleValueDisplay() {
int width = -1;
int height = -1;
if (image != null) {
final ImmutablePair<Integer, Integer> size = ImageUtils.getImageSize(image.getUri());
if (size != null) {
width = size.left;
height = size.right;
}
}
updateScaleValueDisplayIntern(width, height);
}
private void updateScaleValueDisplayIntern(final int width, final int height) {
imageScale.setDisplayMapper(scaleSize -> {
if (width < 0 || height < 0) {
return scaleSize < 0 ? getResources().getString(R.string.log_image_scale_option_noscaling) :
getResources().getString(R.string.log_image_scale_option_entry_noimage, scaleSize);
}
final ImmutableTriple<Integer, Integer, Boolean> scales = ImageUtils.calculateScaledImageSizes(width, height, scaleSize, scaleSize);
String displayValue = getResources().getString(R.string.log_image_scale_option_entry, scales.left, scales.middle);
if (scaleSize < 0) {
displayValue += " (" + getResources().getString(R.string.log_image_scale_option_noscaling) + ")";
}
return displayValue;
});
}
} |
package cgeo.geocaching;
import cgeo.geocaching.concurrent.BlockingThreadPool;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.geopoint.GeopointFormatter.Format;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.utils.Log;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import android.app.Activity;
import android.content.Context;
import android.view.Display;
import android.view.WindowManager;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class StaticMapsProvider {
private static final String MARKERS_URL = "http://cgeo.carnero.cc/_markers/";
/** In my tests the "no image available" image had 5470 bytes, while "street only" maps had at least 20000 bytes */
private static final int MIN_MAP_IMAGE_BYTES = 6000;
/** ThreadPool restricting this to 1 Thread. **/
private static final BlockingThreadPool pool = new BlockingThreadPool(1, Thread.MIN_PRIORITY);
public static File getMapFile(final String geocode, String prefix, final int level, final boolean createDirs) {
return LocalStorage.getStorageFile(geocode, "map_" + prefix + level, false, createDirs);
}
private static void downloadDifferentZooms(final String geocode, String markerUrl, String prefix, String latlonMap, int edge, final Parameters waypoints) {
downloadMap(geocode, 20, "satellite", markerUrl, prefix, 1, latlonMap, edge, waypoints);
downloadMap(geocode, 18, "satellite", markerUrl, prefix, 2, latlonMap, edge, waypoints);
downloadMap(geocode, 16, "roadmap", markerUrl, prefix, 3, latlonMap, edge, waypoints);
downloadMap(geocode, 14, "roadmap", markerUrl, prefix, 4, latlonMap, edge, waypoints);
downloadMap(geocode, 11, "roadmap", markerUrl, prefix, 5, latlonMap, edge, waypoints);
}
private static void downloadMap(String geocode, int zoom, String mapType, String markerUrl, String prefix, int level, String latlonMap, int edge, final Parameters waypoints) {
final String mapUrl = "http://maps.google.com/maps/api/staticmap";
final Parameters params = new Parameters(
"center", latlonMap,
"zoom", String.valueOf(zoom),
"size", edge + "x" + edge,
"maptype", mapType,
"markers", "icon:" + markerUrl + '|' + latlonMap,
"sensor", "false");
if (waypoints != null) {
params.addAll(waypoints);
}
final HttpResponse httpResponse = Network.getRequest(mapUrl, params);
if (httpResponse != null) {
if (httpResponse.getStatusLine().getStatusCode() == 200) {
final File file = getMapFile(geocode, prefix, level, true);
if (LocalStorage.saveEntityToFile(httpResponse, file)) {
// Delete image if it has no contents
final long fileSize = file.length();
if (fileSize < MIN_MAP_IMAGE_BYTES) {
file.delete();
}
}
} else {
Log.d("StaticMapsProvider.downloadMap: httpResponseCode = " + httpResponse.getStatusLine().getStatusCode());
}
} else {
Log.e("StaticMapsProvider.downloadMap: httpResponse is null");
}
}
public static void downloadMaps(cgCache cache, cgeoapplication app) {
final Display display = ((WindowManager) app.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
downloadMaps(cache, display);
}
public static void downloadMaps(cgCache cache, Activity activity) {
final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
downloadMaps(cache, display);
}
public static void downloadMaps(cgCache cache, Display display) {
if ((!Settings.isStoreOfflineMaps() && !Settings.isStoreOfflineWpMaps()) || StringUtils.isBlank(cache.getGeocode())) {
return;
}
int edge = guessMinDisplaySide(display);
if (Settings.isStoreOfflineMaps() && cache.getCoords() != null) {
storeCacheStaticMap(cache, edge, false);
}
// download static map for current waypoints
if (Settings.isStoreOfflineWpMaps() && CollectionUtils.isNotEmpty(cache.getWaypoints())) {
for (cgWaypoint waypoint : cache.getWaypoints()) {
storeWaypointStaticMap(cache.getGeocode(), edge, waypoint, false);
}
}
}
public static void storeWaypointStaticMap(cgCache cache, Activity activity, cgWaypoint waypoint, boolean waitForResult) {
int edge = StaticMapsProvider.guessMinDisplaySide(activity);
storeWaypointStaticMap(cache.getGeocode(), edge, waypoint, waitForResult);
}
private static void storeWaypointStaticMap(final String geocode, int edge, cgWaypoint waypoint, final boolean waitForResult) {
if (waypoint.getCoords() == null) {
return;
}
String wpLatlonMap = waypoint.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA);
String wpMarkerUrl = getWpMarkerUrl(waypoint);
// download map images in separate background thread for higher performance
downloadMaps(geocode, wpMarkerUrl, "wp" + waypoint.getId() + "_", wpLatlonMap, edge, null, waitForResult);
}
public static void storeCacheStaticMap(cgCache cache, Activity activity, final boolean waitForResult) {
int edge = guessMinDisplaySide(activity);
storeCacheStaticMap(cache, edge, waitForResult);
}
private static void storeCacheStaticMap(final cgCache cache, final int edge, final boolean waitForResult) {
final String latlonMap = cache.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA);
final Parameters waypoints = new Parameters();
for (final cgWaypoint waypoint : cache.getWaypoints()) {
if (waypoint.getCoords() == null) {
continue;
}
final String wpMarkerUrl = getWpMarkerUrl(waypoint);
waypoints.put("markers", "icon:" + wpMarkerUrl + "|" + waypoint.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA));
}
// download map images in separate background thread for higher performance
final String cacheMarkerUrl = getCacheMarkerUrl(cache);
downloadMaps(cache.getGeocode(), cacheMarkerUrl, "", latlonMap, edge, waypoints, waitForResult);
}
private static int guessMinDisplaySide(Display display) {
final int maxWidth = display.getWidth() - 25;
final int maxHeight = display.getHeight() - 25;
int edge = 0;
if (maxWidth > maxHeight) {
edge = maxWidth;
} else {
edge = maxHeight;
}
return edge;
}
private static int guessMinDisplaySide(Activity activity) {
return guessMinDisplaySide(((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay());
}
private static void downloadMaps(final String geocode, final String markerUrl, final String prefix, final String latlonMap, final int edge,
final Parameters waypoints, boolean waitForResult) {
if (waitForResult) {
downloadDifferentZooms(geocode, markerUrl, prefix, latlonMap, edge, waypoints);
}
else {
final Runnable currentTask = new Runnable() {
@Override
public void run() {
downloadDifferentZooms(geocode, markerUrl, prefix, latlonMap, edge, waypoints);
}
};
try {
pool.add(currentTask, 20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e("StaticMapsProvider.downloadMaps error adding task: " + e.toString());
}
}
}
private static String getCacheMarkerUrl(final cgCache cache) {
String type = cache.getType().id;
if (cache.isFound()) {
type += "_found";
} else if (cache.isDisabled()) {
type += "_disabled";
}
return MARKERS_URL + "marker_cache_" + type + ".png";
}
private static String getWpMarkerUrl(final cgWaypoint waypoint) {
String type = waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null;
return MARKERS_URL + "marker_waypoint_" + type + ".png";
}
public static void removeWpStaticMaps(int wp_id, String geocode) {
for (int level = 1; level <= 5; level++) {
try {
if (wp_id > 0) {
StaticMapsProvider.getMapFile(geocode, "wp" + wp_id + "_", level, false).delete();
}
} catch (Exception e) {
Log.e("StaticMapsProvider.removeWpStaticMaps: " + e.toString());
}
}
}
/**
* Check if at least one map file exists for the given geocode.
*
* @param geocode
* @return <code>true</code> if at least one mapfile exists; <code>false</code> otherwise
*/
public static boolean doesExistStaticMapForCache(String geocode) {
for (int level = 1; level <= 5; level++) {
File mapFile = StaticMapsProvider.getMapFile(geocode, "", level, false);
if (mapFile != null && mapFile.exists()) {
return true;
}
}
return false;
}
/**
* Checks if at least one map file exists for the given geocode and waypoint ID.
*
* @param geocode
* @param waypointId
* @return <code>true</code> if at least one mapfile exists; <code>false</code> otherwise
*/
public static boolean doesExistStaticMapForWaypoint(String geocode, int waypointId) {
for (int level = 1; level <= 5; level++) {
File mapFile = StaticMapsProvider.getMapFile(geocode, "wp" + waypointId + "_", level, false);
if (mapFile != null && mapFile.exists()) {
return true;
}
}
return false;
}
} |
package minesweeper;
/**
*
* @author veeti "walther" haapsamo
*/
public class Square {
private boolean visible;
private int value;
public Square() {
this.visible = false;
this.value = 0; // 0-8 = amount of mines in the square's surroundings, 9 = mine
}
public void setVisible() {
this.visible = true;
}
public void setMine() {
this.value = 9;
}
public void setValue(int value) {
if (value >= 0 && value < 10) {
this.value = value;
} else {
throw new IllegalArgumentException();
}
}
public boolean isMine() {
return this.value == 9;
}
public boolean isEmpty() {
return this.value == 0;
}
@Override
public String toString() {
return this.value + "";
}
boolean isVisible() {
return this.visible;
}
boolean isNumber() {
return this.value > 0 && this.value < 9;
}
int getValue() {
return this.value;
}
} |
package com.fkxpjj.mikoto.api;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.fkxpjj.mikoto.Mikoto;
import com.fkxpjj.mikoto.model.MsgType;
import com.fkxpjj.mikoto.model.req.ReqBase;
import com.fkxpjj.mikoto.model.req.ReqText;
import com.fkxpjj.mikoto.model.resp.Media;
import com.fkxpjj.mikoto.model.resp.MediaMusic;
import com.fkxpjj.mikoto.model.resp.MediaVideo;
import com.fkxpjj.mikoto.model.resp.RespArticle;
import com.fkxpjj.mikoto.model.resp.RespImg;
import com.fkxpjj.mikoto.model.resp.RespMusic;
import com.fkxpjj.mikoto.model.resp.RespNews;
import com.fkxpjj.mikoto.model.resp.RespText;
import com.fkxpjj.mikoto.model.resp.RespVideo;
import com.fkxpjj.mikoto.model.resp.RespVoice;
public class PassiveApi {
public RespText getRespText(ReqBase reqBase, String content){
RespText respText = new RespText();
respText.setFromUserName(reqBase.getToUserName());
respText.setToUserName(reqBase.getFromUserName());
respText.setContent(content);
respText.setMsgType(MsgType.TEXT);
respText.setCreateTime(System.currentTimeMillis());
return respText;
}
public RespImg getRespImg(ReqBase reqBase, String mediaId){
RespImg respImg = new RespImg();
Media image = new Media();
respImg.setFromUserName(reqBase.getToUserName());
respImg.setToUserName(reqBase.getFromUserName());
respImg.setMsgType(MsgType.IMAGE);
respImg.setCreateTime(System.currentTimeMillis());
image.setMediaId(mediaId);
respImg.setImage(image);
return respImg;
}
public RespVoice getRespVoice(ReqBase reqBase, String mediaId){
RespVoice respVoice = new RespVoice();
Media voice = new Media();
respVoice.setFromUserName(reqBase.getToUserName());
respVoice.setToUserName(reqBase.getFromUserName());
respVoice.setMsgType(MsgType.VOICE);
respVoice.setCreateTime(System.currentTimeMillis());
voice.setMediaId(mediaId);
respVoice.setVoice(voice);
return respVoice;
}
public RespVideo getRespVideo(ReqBase reqBase, String mediaId, String title, String desc){
RespVideo respVideo = new RespVideo();
MediaVideo video = new MediaVideo();
respVideo.setFromUserName(reqBase.getToUserName());
respVideo.setToUserName(reqBase.getFromUserName());
respVideo.setMsgType(MsgType.VIDEO);
respVideo.setCreateTime(System.currentTimeMillis());
video.setTitle(title);
video.setDescription(desc);
video.setMediaId(mediaId);
respVideo.setVideo(video);
return respVideo;
}
public RespMusic getRespMusic(ReqBase reqBase, String title, String description, String musicUrl, String hQMusicUrl, String thumbMediaId){
RespMusic respMusic = new RespMusic();
MediaMusic music = new MediaMusic();
respMusic.setFromUserName(reqBase.getToUserName());
respMusic.setToUserName(reqBase.getFromUserName());
respMusic.setMsgType(MsgType.MUSIC);
respMusic.setCreateTime(System.currentTimeMillis());
music.setTitle(title);
music.setDescription(description);
music.setMusicUrl(musicUrl);
music.setHQMusicUrl(hQMusicUrl);
music.setThumbMediaId(thumbMediaId);
respMusic.setMusic(music);
return respMusic;
}
public RespNews getRespNews(ReqBase reqBase, int count, List<RespArticle> articles){
RespNews respNews = new RespNews();
respNews.setFromUserName(reqBase.getToUserName());
respNews.setToUserName(reqBase.getFromUserName());
respNews.setMsgType(MsgType.NEWS);
respNews.setCreateTime(System.currentTimeMillis());
respNews.setArticleCount(count);
respNews.setArticles(articles);
return respNews;
}
public RespArticle getRespArticle(String title, String description, String picUrl, String url){
RespArticle respArticle = new RespArticle();
respArticle.setTitle(title);
respArticle.setDescription(description);
respArticle.setPicUrl(picUrl);
respArticle.setUrl(url);
return respArticle;
}
public void sendRespText(ReqText reqText, String content, HttpServletResponse resp) throws IOException{
RespText respText = getRespText(reqText, content);
String xml = Mikoto.parse.RespToXML(respText);
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.print(xml);
out.close();
}
} |
package mod.gamenature.skullforge.common;
import mod.gamenature.skullforge.update.ConnectionHandler;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = "skullforge", name = "SkullForge", version = SkullForge.version)
@NetworkMod(clientSideRequired = true, serverSideRequired = false)
public class SkullForge {
@Instance("skullforge")
public static SkullForge instance;
// Proxy defs
@SidedProxy(clientSide="mod.gamenature.skullforge.client.SkullForgeClientProxy", serverSide="mod.gamenature.skullforge.common.SkullForgeCommonProxy")
public static SkullForgeCommonProxy proxy;
//Version String
public static final String version = "V1.6.4A";
// Item declarations
public static Item hotbones;
public static Item witherbones;
public static Item rehydratedmeat;
public static Item paintbrush;
public static Item paintscraper;
@EventHandler
public static void preInit( FMLPreInitializationEvent event ) {
//Sound Loader
MinecraftForge.EVENT_BUS.register(new SoundManager());
}
@EventHandler
public void init(FMLInitializationEvent event) {
//Register our Connection Handler please!
NetworkRegistry.instance().registerConnectionHandler(new ConnectionHandler());
// Construct our items
hotbones = (new itemHotBones(4005)).setUnlocalizedName("skullforge:HotBones").setTextureName("HotBones");
witherbones = (new itemWitherBones(4003)).setUnlocalizedName("skullforge:WitherBones").setTextureName("WitherBones");
rehydratedmeat = (new itemWaterMeat(4004, 4, false)).setUnlocalizedName("skullforge:RehydratedMeat").setTextureName("RehydratedMeat");
paintbrush = (new itemPaintbrush(4006)).setUnlocalizedName("skullforge:pb").setTextureName("pb");
paintscraper = (new itemPaintScraper(4007)).setUnlocalizedName("skullforge:MyPaintScraper").setTextureName("MyPaintScrapper");
// Add the recipes
// Smelting recipe for bones into hot bones
GameRegistry.addSmelting(Item.bone.itemID, new ItemStack(SkullForge.hotbones,1), 1);
// Recipe to turn hot bones into wither bones with either charcoal or coal
GameRegistry.addRecipe(new ItemStack(SkullForge.witherbones, 1), new Object [] {
" # ", "#$#", " # ", Character.valueOf('#'), Item.coal, Character.valueOf('$'), SkullForge.hotbones});
GameRegistry.addRecipe(new ItemStack(SkullForge.witherbones, 1), new Object [] {
" # ", "#$#", " # ", Character.valueOf('#'), new ItemStack(Item.coal, 1, 1), Character.valueOf('$'), SkullForge.hotbones});
// Wither Skull
GameRegistry.addRecipe(new ItemStack(Item.skull, 1, 1), new Object []
{"ccc", "csc", "ddd", Character.valueOf('c'), SkullForge.witherbones, Character.valueOf('s'), Item.skull, Character.valueOf('d'), Item.diamond});
// Creeper Head
GameRegistry.addRecipe(new ItemStack(Item.skull, 1, 4), new Object[]
{"
// Zombie Head
GameRegistry.addRecipe(new ItemStack(Item.skull, 1, 2), new Object[]
{"
// Skeleton Skull
GameRegistry.addRecipe(new ItemStack(Item.skull, 1, 0), new Object[]
{"
// Rehydrated flesh recipe
GameRegistry.addRecipe(new ItemStack(SkullForge.rehydratedmeat, 8), new Object[]
{"
// Cool down those hot bones!
GameRegistry.addShapelessRecipe(new ItemStack(Item.bone, 1), new ItemStack(SkullForge.hotbones), new ItemStack(Item.bucketWater));
// Steve Head
GameRegistry.addRecipe(new ItemStack(Item.skull, 1, 3), new Object[]{"XXX","XYX","XXX",
Character.valueOf('X'), SkullForge.rehydratedmeat,
Character.valueOf('Y'), Block.slowSand});
//Paint Brush
GameRegistry.addRecipe(new ItemStack(paintbrush), new Object[]{
"z",
"x",
"n",
'z', Item.silk, 'x', Item.stick, 'n', new ItemStack(Item.dyePowder, 1, 4)
});
//Putty Knife
GameRegistry.addRecipe(new ItemStack(paintscraper), new Object[]{
"p",
"o",
"f",
'p', Item.ingotIron, 'o', Item.stick, 'f', new ItemStack(Item.dyePowder, 1, 1)
});
// Add the names
LanguageRegistry.addName(SkullForge.hotbones, "Heated Bone");
LanguageRegistry.addName(SkullForge.witherbones, "Wither Bone");
LanguageRegistry.addName(SkullForge.rehydratedmeat, "Rehydrated Flesh");
LanguageRegistry.addName(SkullForge.paintbrush, "Paintbrush");
LanguageRegistry.addName(SkullForge.paintscraper, "Putty Knife");
// Register the images
proxy.registerRenderThings();
}
} |
package org.jpos.qi;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.data.ValueContext;
import com.vaadin.server.*;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.jdom2.DataConversionException;
import org.jdom2.Element;
import org.jpos.core.ConfigurationException;
import org.jpos.ee.DB;
import org.jpos.ee.User;
import org.jpos.ee.Visitor;
import org.jpos.ee.VisitorManager;
import org.jpos.iso.ISOUtil;
import org.jpos.q2.Q2;
import org.jpos.q2.qbean.QXmlConfig;
import org.jpos.qi.login.LoginView;
import org.jpos.util.Log;
import org.jpos.util.NameRegistrar;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
@Theme("jpos")
@Title("jPOS")
public class QI extends UI {
private Locale locale;
private List<Element> availableLocales;
private HashMap<Locale,SortedMap<String,Object>> messagesMap;
private List<Element> messageFiles;
private ValueContext valueContext;
private Log log;
private Q2 q2;
private static final String CONFIG_NAME = "QI";
private static final long CONFIG_TIMEOUT = 5000L;
private static ThreadLocal<DB> tldb = new ThreadLocal<>();
private HashMap<String,ViewConfig> views;
private Visitor visitor;
private QILayout qiLayout;
private Header header;
private Sidebar sidebar;
private LoginView loginView;
public QI() {
locale = Locale.getDefault();
log = Log.getLog(Q2.LOGGER_NAME, "QI");
qiLayout = new QILayout();
views = new HashMap<>();
try {
q2 = NameRegistrar.get("Q2");
} catch (NameRegistrar.NotFoundException e) {
throw new IllegalStateException ("Q2 not available");
}
messagesMap = new HashMap<>();
valueContext = new ValueContext(locale);
}
protected QILayout getQILayout() {
return qiLayout;
}
protected Sidebar getSidebar() {
return sidebar;
}
protected Visitor getVisitor() {
return visitor;
}
protected LoginView getLoginView() {
return loginView;
}
private void parseMessages() {
Properties master = new Properties();
for (Element element: availableLocales) {
String localeCode = element.getValue();
Locale l = Locale.forLanguageTag(localeCode);
Iterator<Element> iterator = messageFiles.iterator();
if (iterator.hasNext()) {
String masterName = iterator.next().getValue();
try {
master.load(getClass().getResourceAsStream("/" + masterName.concat("_" + localeCode + ".properties")));
while (iterator.hasNext()) {
Properties additionalProp = new Properties();
String additionalName = iterator.next().getValue();
additionalProp.load(getClass().getResourceAsStream("/" + additionalName.concat("_" + localeCode + ".properties")));
master.putAll(additionalProp);
}
} catch (NullPointerException | IOException n) {
//Log but continue
//Show notification only if main locale is faulty
if (locale.toString().equals(localeCode))
displayNotification("Invalid locale '" + localeCode +"' : check configuration");
log.error(ErrorMessage.SYSERR_INVALID_LOCALE,localeCode);
}
TreeMap<String, Object> treeMap = new TreeMap<>((Map) master);
messagesMap.put(l, treeMap);
}
}
}
@Override
protected void init(VaadinRequest request) {
Element cfg = getXmlConfiguration();
if (cfg != null) {
setContent(qiLayout);
setResponsive(true);
addStyleName(ValoTheme.UI_WITH_MENU);
init(request, cfg);
try (DB db = new DB()) {
db.open();
db.beginTransaction();
visitor = getVisitor(db);
User user = getUser();
if (user == null) {
user = visitor.getUser();
if (user != null) {
setUser(user);
}
}
if (user == null || !user.isActive())
createLoginView();
else
createMainView();
db.commit();
}
}
}
public String getMessage (String id, Object... obj) {
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
MessageFormat mf = new MessageFormat((String) map.getOrDefault(id, id));
mf.setLocale(locale);
return mf.format(obj);
}
return id;
}
public String getMessage (ErrorMessage em) {
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
return (String) map.getOrDefault(em.getPropertyName(), em.getDefaultMessage());
}
return em.getPropertyName();
}
public String getMessage (ErrorMessage em, Object... obj) {
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
String format = (String) map.getOrDefault(em.getPropertyName(), em.getDefaultMessage());
MessageFormat mf = new MessageFormat(format, locale);
return mf.format(obj);
}
return em.getPropertyName();
}
@SuppressWarnings("unused")
private void init (VaadinRequest vr, Element cfg) {
String title = cfg.getChildText("title");
String theme = cfg.getChildText("theme");
String logger = cfg.getAttributeValue("logger");
messageFiles = cfg.getChildren("messages");
if (logger != null) {
String realm = cfg.getAttributeValue("realm");
log = Log.getLog(logger, realm != null ? realm : "QI");
}
if (title != null)
getPage().setTitle(title);
if (theme != null) {
setTheme(theme);
}
//Get all the available locales
//The first one will be the default.
availableLocales = cfg.getChildren("locale");
if (availableLocales.size() > 0) {
String localeName = availableLocales.get(0).getValue();
if (localeName != null) {
Locale l = Locale.forLanguageTag(localeName);
if (l.hashCode() == 0) {
Notification.show(
getMessage(ErrorMessage.SYSERR_INVALID_LOCALE, localeName),
Notification.Type.ERROR_MESSAGE);
} else {
locale = l;
}
}
}
parseMessages();
}
public Log getLog() {
return log;
}
public void displayNotification (String message) {
Notification n = new Notification(message,Notification.Type.TRAY_NOTIFICATION);
n.setHtmlContentAllowed(true);
n.show(Page.getCurrent());
}
public void displayNotificationMessage (String message) {
Notification n = new Notification(getMessage(message),Notification.Type.TRAY_NOTIFICATION);
n.setHtmlContentAllowed(true);
n.show(Page.getCurrent());
}
public void displayError (String error, String detail, Object... obj) {
Notification.show(
getMessage(error),
getMessage(detail, obj),
Notification.Type.ERROR_MESSAGE
);
}
public void login (User user, boolean rememberMe) {
setUser(user);
try (DB db = new DB()) {
db.open();
db.beginTransaction();
db.session().refresh(user);
db.session().refresh(visitor);
if (rememberMe)
visitor.setUser(user);
String users = visitor.getProps().get("USERS");
users = users == null ? "" : users;
if (!users.contains(user.getNickAndId())) {
if (users.length() > 0)
users = users + ",";
visitor.getProps().put("USERS", users + user.getNickAndId());
}
user.setLastLogin(new Date());
db.session().update(visitor);
db.session().update(user);
db.commit();
}
getLog().info(String.format(
"LOGIN user=%s[id=%d], visitor='%s'%s",
user.getNick(),
user.getId(),
ISOUtil.protect(visitor.getId()),
rememberMe ? ", remember=yes" : ""));
qiLayout.getContentLayout().removeComponent(loginView);
createMainView();
String fragment = UI.getCurrent().getPage().getUriFragment();
if (fragment == null || fragment.isEmpty()) {
navigateTo("/home");
} else if (fragment.startsWith("!")) {
navigateTo(fragment.substring(1));
}
}
void logout() {
qiLayout.removeAllComponents();
getSession().close();
if (visitor.getUser() != null) {
try (DB db = new DB()) {
db.open();
db.beginTransaction();
db.session().refresh(visitor);
visitor.setUser(null);
db.session().update(visitor);
db.commit();
}
}
getUI().getPage().setLocation("/");
VaadinService.getCurrentRequest().getWrappedSession().invalidate();
}
public User getUser() {
try {
VaadinSession.getCurrent().getLockInstance().lock();
return VaadinSession.getCurrent().getAttribute(User.class);
} finally {
VaadinSession.getCurrent().getLockInstance().unlock();
}
}
public void setUser (User user) {
// Store user in VaadinSession.
if (user != null) {
try {
VaadinSession.getCurrent().getLockInstance().lock();
if (VaadinSession.getCurrent().getAttribute(User.class) == null)
VaadinSession.getCurrent().setAttribute(User.class, user);
} finally {
VaadinSession.getCurrent().getLockInstance().unlock();
}
}
}
public static QI getQI() {
return (QI) UI.getCurrent();
}
public static DB getDB() {
DB db = tldb.get();
if (db == null) {
db = new DB();
db.open();
tldb.set(db);
}
return db;
}
static void closeDB() {
DB db = tldb.get();
if (db != null) {
db.close();
tldb.remove();
}
}
void navigateTo(String navigationState) {
getNavigator().navigateTo(navigationState);
}
Element getXmlConfiguration() {
Element cfg = QXmlConfig.getConfiguration (CONFIG_NAME, CONFIG_TIMEOUT);
if (cfg == null) {
Notification.show(getMessage(ErrorMessage.SYSERR_CONFIG_NOT_FOUND), Notification.Type.ERROR_MESSAGE);
return null;
}
return cfg;
}
Sidebar sidebar() {
return sidebar;
}
private void createLoginView() {
qiLayout.getContentLayout().addComponent(loginView = prepareLoginView());
}
protected LoginView prepareLoginView() {
return new LoginView();
}
private Visitor getVisitor(DB db) {
VaadinRequest request = VaadinService.getCurrentRequest();
Cookie[] cookies = request.getCookies();
if (cookies == null)
cookies = new Cookie[0];
VisitorManager vmgr = new VisitorManager(db, cookies);
Visitor v = vmgr.getVisitor(true);
if (v != null) {
vmgr.set (v, "IP", request.getRemoteAddr());
vmgr.set (v,"HOST", request.getRemoteHost());
}
VaadinService.getCurrentResponse().addCookie(vmgr.getCookie());
return v;
}
protected void createMainView() {
setNavigator(new QINavigator(this, qiLayout.getContentLayout()));
if (qiLayout.getHeaderLayout() != null) {
header = new Header(this);
qiLayout.getHeaderLayout().addComponent(header);
}
sidebar = new Sidebar();
if (sidebar.isEnabled()) {
qiLayout.addMenu(sidebar);
Page.getCurrent().addBrowserWindowResizeListener(
(Page.BrowserWindowResizeListener) event -> {
if (sidebar != null && event.getWidth() < 1100)
sidebar.expandSidebar();
});
}
if (getUser().isForcePasswordChange())
navigateTo("/users/" + getUser().getId() + "/profile/password_change");
}
public Header getHeader() {
return header;
}
public HashMap<String, ViewConfig> getViews() {
return views;
}
public void setViews(HashMap<String, ViewConfig> views) {
this.views = views;
}
void addView(String route, Element e) {
ViewConfig vc = new ViewConfig();
try {
vc.setXmlElement(e);
vc.setConfiguration(getQ2().getFactory().getConfiguration(e));
this.views.put(route, vc);
} catch (ConfigurationException | DataConversionException exc) {
getLog().warn(exc);
}
}
public ViewConfig getView(String route) {
return views.get(route);
}
public ValueContext getValueContext() {
return this.valueContext;
}
public Q2 getQ2() {
return q2;
}
} |
package wyc.builder;
import static wyc.lang.WhileyFile.internalFailure;
import static wyc.lang.WhileyFile.syntaxError;
import static wycc.lang.SyntaxError.internalFailure;
import static wycc.lang.SyntaxError.syntaxError;
import static wyil.util.ErrorMessages.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import wyautl_old.lang.Automata;
import wyautl_old.lang.Automaton;
import wybs.lang.*;
import wybs.util.*;
import wyc.lang.*;
import wyc.lang.WhileyFile.Context;
import wycc.lang.NameID;
import wycc.lang.SyntacticElement;
import wycc.lang.SyntaxError;
import wycc.util.Pair;
import wycc.util.ResolveError;
import wyfs.lang.Path;
import wyfs.util.Trie;
import wyil.lang.Constant;
import wyil.lang.Modifier;
import wyil.lang.Type;
import wyil.lang.WyilFile;
/**
* Propagates type information in a <i>flow-sensitive</i> fashion from declared
* parameter and return types through variable declarations and assigned
* expressions, to determine types for all intermediate expressions and
* variables. During this propagation, type checking is performed to ensure
* types are used soundly. For example:
*
* <pre>
* function sum([int] data) => int:
* int r = 0 // declared int type for r
* for v in data: // infers int type for v, based on type of data
* r = r + v // infers int type for r + v, based on type of operands
* return r // infers int type for return expression
* </pre>
*
* <p>
* The flow typing algorithm distinguishes between the <i>declared type</i> of a
* variable and its <i>known type</i>. That is, the known type at any given
* point is permitted to be more precise than the declared type (but not vice
* versa). For example:
* </p>
*
* <pre>
* function id(int x) => int:
* return x
*
* function f(int y) => int:
* int|null x = y
* f(x)
* </pre>
*
* <p>
* The above example is considered type safe because the known type of
* <code>x</code> at the function call is <code>int</code>, which differs from
* its declared type (i.e. <code>int|null</code>).
* </p>
*
* <p>
* Loops present an interesting challenge for type propagation. Consider this
* example:
* </p>
*
* <pre>
* function loopy(int max) => real:
* var i = 0
* while i < max:
* i = i + 0.5
* return i
* </pre>
*
* <p>
* On the first pass through the loop, variable <code>i</code> is inferred to
* have type <code>int</code> (based on the type of the constant <code>0</code>
* ). However, the add expression is inferred to have type <code>real</code>
* (based on the type of the rhs) and, hence, the resulting type inferred for
* <code>i</code> is <code>real</code>. At this point, the loop must be
* reconsidered taking into account this updated type for <code>i</code>.
* </p>
*
* <p>
* The operation of the flow type checker splits into two stages:
* </p>
* <ul>
* <li><b>Global Propagation.</b> During this stage, all named types are checked
* and expanded.</li>
* <li><b>Local Propagation.</b> During this stage, types are propagated through
* statements and expressions (as above).</li>
* </ul>
*
* <h3>References</h3>
* <ul>
* <li>
* <p>
* David J. Pearce and James Noble. Structural and Flow-Sensitive Types for
* Whiley. Technical Report, Victoria University of Wellington, 2010.
* </p>
* </li>
* </ul>
*
* @author David J. Pearce
*
*/
public class FlowTypeChecker {
private WhileyBuilder builder;
private String filename;
private WhileyFile.FunctionOrMethod current;
/**
* The constant cache contains a cache of expanded constant values. This is
* simply to prevent recomputing them every time.
*/
private final HashMap<NameID, Constant> constantCache = new HashMap<NameID, Constant>();
public FlowTypeChecker(WhileyBuilder builder) {
this.builder = builder;
}
// WhileyFile(s)
public void propagate(List<WhileyFile> files) {
for (WhileyFile wf : files) {
propagate(wf);
}
}
public void propagate(WhileyFile wf) {
this.filename = wf.filename;
for (WhileyFile.Declaration decl : wf.declarations) {
try {
if (decl instanceof WhileyFile.FunctionOrMethod) {
propagate((WhileyFile.FunctionOrMethod) decl);
} else if (decl instanceof WhileyFile.Type) {
propagate((WhileyFile.Type) decl);
} else if (decl instanceof WhileyFile.Constant) {
propagate((WhileyFile.Constant) decl);
}
} catch (ResolveError e) {
syntaxError(errorMessage(RESOLUTION_ERROR, e.getMessage()),
filename, decl, e);
} catch (SyntaxError e) {
throw e;
} catch (Throwable t) {
internalFailure(t.getMessage(), filename, decl, t);
}
}
}
// Declarations
/**
* Resolve types for a given type declaration. If an invariant expression is
* given, then we have to propagate and resolve types throughout the
* expression.
*
* @param td
* Type declaration to check.
* @throws IOException
*/
public void propagate(WhileyFile.Type td) throws IOException {
// First, resolve the declared syntactic type into the corresponding
// nominal type.
td.resolvedType = resolveAsType(td.pattern.toSyntacticType(), td);
if (td.invariant != null) {
// Second, an invariant expression is given, so propagate through
// that.
// Construct the appropriate typing environment
Environment environment = new Environment();
environment = addDeclaredVariables(td.pattern, environment, td);
// Propagate type information through the constraint
td.invariant = propagate(td.invariant, environment, td);
}
}
/**
* Propagate and check types for a given constant declaration.
*
* @param cd
* Constant declaration to check.
* @throws IOException
*/
public void propagate(WhileyFile.Constant cd) throws IOException, ResolveError {
NameID nid = new NameID(cd.file().module, cd.name());
cd.resolvedValue = resolveAsConstant(nid);
}
/**
* Propagate and check types for a given function or method declaration.
*
* @param fd
* Function or method declaration to check.
* @throws IOException
*/
public void propagate(WhileyFile.FunctionOrMethod d) throws IOException {
this.current = d; // ugly
Environment environment = new Environment();
// Resolve the types of all parameters and construct an appropriate
// environment for use in the flow-sensitive type propagation.
for (WhileyFile.Parameter p : d.parameters) {
environment = environment.declare(p.name, resolveAsType(p.type, d), resolveAsType(p.type, d));
}
// Resolve types for any preconditions (i.e. requires clauses) provided.
final List<Expr> d_requires = d.requires;
for (int i = 0; i != d_requires.size(); ++i) {
Expr condition = d_requires.get(i);
condition = propagate(condition, environment.clone(), d);
d_requires.set(i, condition);
}
// Resolve types for any postconditions (i.e. ensures clauses) provided.
final List<Expr> d_ensures = d.ensures;
if (d_ensures.size() > 0) {
// At least one ensures clause is provided; so, first, construct an
// appropriate environment from the initial one create.
Environment ensuresEnvironment = addDeclaredVariables(d.ret,
environment.clone(), d);
// Now, type check each ensures clause
for (int i = 0; i != d_ensures.size(); ++i) {
Expr condition = d_ensures.get(i);
condition = propagate(condition, ensuresEnvironment, d);
d_ensures.set(i, condition);
}
}
// Resolve the overall type for the function or method.
if (d instanceof WhileyFile.Function) {
WhileyFile.Function f = (WhileyFile.Function) d;
f.resolvedType = resolveAsType(f.unresolvedType(), d);
} else {
WhileyFile.Method m = (WhileyFile.Method) d;
m.resolvedType = resolveAsType(m.unresolvedType(), d);
}
// Finally, propagate type information throughout all statements in the
// function / method body.
propagate(d.statements, environment);
}
// Blocks & Statements
/**
* Propagate type information in a flow-sensitive fashion through a block of
* statements, whilst type checking each statement and expression.
*
* @param block
* Block of statements to flow sensitively type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(ArrayList<Stmt> block, Environment environment) {
for (int i = 0; i != block.size(); ++i) {
Stmt stmt = block.get(i);
if (stmt instanceof Expr) {
block.set(i,
(Stmt) propagate((Expr) stmt, environment, current));
} else {
environment = propagate(stmt, environment);
}
}
return environment;
}
/**
* Propagate type information in a flow-sensitive fashion through a given
* statement, whilst type checking it at the same time. For statements which
* contain other statements (e.g. if, while, etc), then this will
* recursively propagate type information through them as well.
*
*
* @param block
* Block of statements to flow-sensitively type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt stmt, Environment environment) {
try {
if (stmt instanceof Stmt.VariableDeclaration) {
return propagate((Stmt.VariableDeclaration) stmt, environment);
} else if (stmt instanceof Stmt.Assign) {
return propagate((Stmt.Assign) stmt, environment);
} else if (stmt instanceof Stmt.Return) {
return propagate((Stmt.Return) stmt, environment);
} else if (stmt instanceof Stmt.IfElse) {
return propagate((Stmt.IfElse) stmt, environment);
} else if (stmt instanceof Stmt.While) {
return propagate((Stmt.While) stmt, environment);
} else if (stmt instanceof Stmt.ForAll) {
return propagate((Stmt.ForAll) stmt, environment);
} else if (stmt instanceof Stmt.Switch) {
return propagate((Stmt.Switch) stmt, environment);
} else if (stmt instanceof Stmt.DoWhile) {
return propagate((Stmt.DoWhile) stmt, environment);
} else if (stmt instanceof Stmt.Break) {
return propagate((Stmt.Break) stmt, environment);
} else if (stmt instanceof Stmt.Throw) {
return propagate((Stmt.Throw) stmt, environment);
} else if (stmt instanceof Stmt.TryCatch) {
return propagate((Stmt.TryCatch) stmt, environment);
} else if (stmt instanceof Stmt.Assert) {
return propagate((Stmt.Assert) stmt, environment);
} else if (stmt instanceof Stmt.Assume) {
return propagate((Stmt.Assume) stmt, environment);
} else if (stmt instanceof Stmt.Debug) {
return propagate((Stmt.Debug) stmt, environment);
} else if (stmt instanceof Stmt.Skip) {
return propagate((Stmt.Skip) stmt, environment);
} else {
internalFailure("unknown statement: "
+ stmt.getClass().getName(), filename, stmt);
return null; // deadcode
}
} catch (ResolveError e) {
syntaxError(errorMessage(RESOLUTION_ERROR, e.getMessage()),
filename, stmt, e);
return null; // dead code
} catch (SyntaxError e) {
throw e;
} catch (Throwable e) {
internalFailure(e.getMessage(), filename, stmt, e);
return null; // dead code
}
}
/**
* Type check an assertion statement. This requires checking that the
* expression being asserted is well-formed and has boolean type.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Assert stmt, Environment environment) {
stmt.expr = propagate(stmt.expr, environment, current);
checkIsSubtype(Type.T_BOOL, stmt.expr);
return environment;
}
/**
* Type check an assume statement. This requires checking that the
* expression being asserted is well-formed and has boolean type.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Assume stmt, Environment environment) {
stmt.expr = propagate(stmt.expr, environment, current);
checkIsSubtype(Type.T_BOOL, stmt.expr);
return environment;
}
/**
* Type check a variable declaration statement. This must associate the
* given variable with either its declared and actual type in the
* environment. If no initialiser is given, then the actual type is the void
* (since the variable is not yet defined). Otherwise, the actual type is
* the type of the initialiser expression. Additionally, when an initialiser
* is given we must check it is well-formed and that it is a subtype of the
* declared type.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.VariableDeclaration stmt,
Environment environment) throws IOException {
// First, resolve declared type
stmt.type = resolveAsType(stmt.pattern.toSyntacticType(), current);
// First, resolve type of initialiser
if (stmt.expr != null) {
stmt.expr = propagate(stmt.expr, environment, current);
checkIsSubtype(stmt.type, stmt.expr);
}
// Second, update environment accordingly. Observe that we can safely
// assume any variable(s) are not already declared in the enclosing
// scope because the parser checks this for us.
environment = addDeclaredVariables(stmt.pattern, environment, current);
// Done.
return environment;
}
/**
* Type check an assignment statement.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Assign stmt, Environment environment)
throws IOException, ResolveError {
Expr.LVal lhs = propagate(stmt.lhs, environment);
Expr rhs = propagate(stmt.rhs, environment, current);
if (lhs instanceof Expr.RationalLVal) {
// represents a destructuring assignment
Expr.RationalLVal tv = (Expr.RationalLVal) lhs;
Pair<Expr.AssignedVariable, Expr.AssignedVariable> avs = inferAfterType(
tv, rhs);
environment = environment.update(avs.first().var,
avs.first().afterType);
environment = environment.update(avs.second().var,
avs.second().afterType);
} else if (lhs instanceof Expr.Tuple) {
// represents a destructuring assignment
Expr.Tuple tv = (Expr.Tuple) lhs;
List<Expr.AssignedVariable> as = inferAfterType(tv, rhs);
for (Expr.AssignedVariable av : as) {
environment = environment.update(av.var, av.afterType);
}
} else {
// represents element or field update
Expr.AssignedVariable av = inferAfterType(lhs, rhs.result());
environment = environment.update(av.var, av.afterType);
}
stmt.lhs = (Expr.LVal) lhs;
stmt.rhs = rhs;
return environment;
}
private Pair<Expr.AssignedVariable, Expr.AssignedVariable> inferAfterType(
Expr.RationalLVal tv, Expr rhs) throws IOException {
Nominal afterType = rhs.result();
if (!Type.isImplicitCoerciveSubtype(Type.T_REAL, afterType.raw())) {
syntaxError("real value expected, got " + afterType, filename, rhs);
}
if (tv.numerator instanceof Expr.AssignedVariable
&& tv.denominator instanceof Expr.AssignedVariable) {
Expr.AssignedVariable lv = (Expr.AssignedVariable) tv.numerator;
Expr.AssignedVariable rv = (Expr.AssignedVariable) tv.denominator;
lv.type = Nominal.T_VOID;
rv.type = Nominal.T_VOID;
lv.afterType = Nominal.T_INT;
rv.afterType = Nominal.T_INT;
return new Pair<Expr.AssignedVariable, Expr.AssignedVariable>(lv,
rv);
} else {
syntaxError(errorMessage(INVALID_TUPLE_LVAL), filename, tv);
return null; // dead code
}
}
private List<Expr.AssignedVariable> inferAfterType(Expr.Tuple lv, Expr rhs)
throws IOException, ResolveError {
Nominal afterType = rhs.result();
// First, check that the rhs is a subtype of the lhs
checkIsSubtype(lv.type, afterType, rhs);
Nominal.EffectiveTuple rhsType = expandAsEffectiveTuple(afterType);
// Second, construct the list of assigned variables
ArrayList<Expr.AssignedVariable> rs = new ArrayList<Expr.AssignedVariable>();
for (int i = 0; i != rhsType.elements().size(); ++i) {
Expr element = lv.fields.get(i);
if (element instanceof Expr.LVal) {
rs.add(inferAfterType((Expr.LVal) element, rhsType.element(i)));
} else {
syntaxError(errorMessage(INVALID_TUPLE_LVAL), filename, element);
}
}
// done
return rs;
}
private Expr.AssignedVariable inferAfterType(Expr.LVal lv, Nominal afterType) {
if (lv instanceof Expr.AssignedVariable) {
Expr.AssignedVariable v = (Expr.AssignedVariable) lv;
v.afterType = afterType;
return v;
} else if (lv instanceof Expr.Dereference) {
Expr.Dereference pa = (Expr.Dereference) lv;
// The before and after types are the same since an assignment
// through a reference does not change its type.
checkIsSubtype(pa.srcType, Nominal.Reference(afterType), lv);
return inferAfterType((Expr.LVal) pa.src, pa.srcType);
} else if (lv instanceof Expr.IndexOf) {
Expr.IndexOf la = (Expr.IndexOf) lv;
Nominal.EffectiveIndexible srcType = la.srcType;
afterType = (Nominal) srcType.update(la.index.result(), afterType);
return inferAfterType((Expr.LVal) la.src, afterType);
} else if (lv instanceof Expr.FieldAccess) {
Expr.FieldAccess la = (Expr.FieldAccess) lv;
Nominal.EffectiveRecord srcType = la.srcType;
// I know I can modify this hash map, since it's created fresh
// in Nominal.Record.fields().
afterType = (Nominal) srcType.update(la.name, afterType);
return inferAfterType((Expr.LVal) la.src, afterType);
} else {
internalFailure("unknown lval: " + lv.getClass().getName(),
filename, lv);
return null; // deadcode
}
}
/**
* Type check a break statement. This requires propagating the current
* environment to the block destination, to ensure that the actual types of
* all variables at that point are precise.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Break stmt, Environment environment) {
// FIXME: need to propagate environment to the break destination
return BOTTOM;
}
/**
* Type check an assume statement. This requires checking that the
* expression being printed is well-formed and has string type.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Debug stmt, Environment environment) {
stmt.expr = propagate(stmt.expr, environment, current);
checkIsSubtype(Type.T_STRING, stmt.expr);
return environment;
}
/**
* Type check a do-while statement.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.DoWhile stmt, Environment environment) {
// Iterate to a fixed point
environment = computeFixedPoint(environment,stmt.body,stmt.condition,true,stmt);
// Type invariants
List<Expr> stmt_invariants = stmt.invariants;
for (int i = 0; i != stmt_invariants.size(); ++i) {
Expr invariant = stmt_invariants.get(i);
invariant = propagate(invariant, environment, current);
stmt_invariants.set(i, invariant);
checkIsSubtype(Type.T_BOOL, invariant);
}
// Type condition assuming its false to represent the terminated loop.
// This is important if the condition contains a type test, as we'll
// know that doesn't hold here.
Pair<Expr, Environment> p = propagateCondition(stmt.condition, false,
environment, current);
stmt.condition = p.first();
environment = p.second();
return environment;
}
/**
* Type check a <code>for</code> statement.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.ForAll stmt, Environment environment)
throws IOException, ResolveError {
stmt.source = propagate(stmt.source, environment, current);
Nominal.EffectiveCollection srcType = expandAsEffectiveCollection(stmt.source
.result());
stmt.srcType = srcType;
if (srcType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION), filename,
stmt);
}
// At this point, the major task is to determine what the types for the
// iteration variables declared in the for loop. More than one variable
// is permitted in some cases.
Nominal[] elementTypes = new Nominal[stmt.variables.size()];
if (elementTypes.length == 2 && srcType instanceof Nominal.EffectiveMap) {
Nominal.EffectiveMap dt = (Nominal.EffectiveMap) srcType;
elementTypes[0] = dt.key();
elementTypes[1] = dt.value();
} else {
if (elementTypes.length == 1) {
elementTypes[0] = srcType.element();
} else {
syntaxError(errorMessage(VARIABLE_POSSIBLY_UNITIALISED),
filename, stmt);
}
}
// Update the environment to include those declared variables
ArrayList<String> stmtVariables = stmt.variables;
for (int i = 0; i != elementTypes.length; ++i) {
String var = stmtVariables.get(i);
if (environment.containsKey(var)) {
syntaxError(errorMessage(VARIABLE_ALREADY_DEFINED, var),
filename, stmt);
}
environment = environment.declare(var, elementTypes[i], elementTypes[i]);
}
// Iterate to a fixed point
environment = computeFixedPoint(environment,stmt.body,null,false,stmt);
// Remove the loop variables from the environment, since they are only
// scoped for the duration of the body but not beyond.
for (int i = 0; i != elementTypes.length; ++i) {
String var = stmtVariables.get(i);
environment = environment.remove(var);
}
// Finally, type the invariant
if (stmt.invariant != null) {
stmt.invariant = propagate(stmt.invariant, environment, current);
checkIsSubtype(Type.T_BOOL, stmt.invariant);
}
return environment;
}
private Environment propagate(Stmt.IfElse stmt, Environment environment) {
// First, check condition and apply variable retypings.
Pair<Expr, Environment> p1, p2;
p1 = propagateCondition(stmt.condition, true, environment.clone(),
current);
p2 = propagateCondition(stmt.condition, false, environment, current);
stmt.condition = p1.first();
Environment trueEnvironment = p1.second();
Environment falseEnvironment = p2.second();
// Second, update environments for true and false branches
if (stmt.trueBranch != null && stmt.falseBranch != null) {
trueEnvironment = propagate(stmt.trueBranch, trueEnvironment);
falseEnvironment = propagate(stmt.falseBranch, falseEnvironment);
} else if (stmt.trueBranch != null) {
trueEnvironment = propagate(stmt.trueBranch, trueEnvironment);
} else if (stmt.falseBranch != null) {
trueEnvironment = environment;
falseEnvironment = propagate(stmt.falseBranch, falseEnvironment);
}
// Finally, join results back together
return trueEnvironment.merge(environment.keySet(), falseEnvironment);
}
/**
* Type check a <code>return</code> statement. If a return expression is
* given, then we must check that this is well-formed and is a subtype of
* the enclosing function or method's declared return type. The environment
* after a return statement is "bottom" because that represents an
* unreachable program point.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Return stmt, Environment environment)
throws IOException {
if (stmt.expr != null) {
stmt.expr = propagate(stmt.expr, environment, current);
Nominal rhs = stmt.expr.result();
checkIsSubtype(current.resolvedType().ret(), rhs, stmt.expr);
}
environment.free();
return BOTTOM;
}
/**
* Type check a <code>skip</code> statement, which has no effect on the
* environment.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Skip stmt, Environment environment) {
return environment;
}
private Environment propagate(Stmt.Switch stmt, Environment environment)
throws IOException {
stmt.expr = propagate(stmt.expr, environment, current);
Environment finalEnv = null;
boolean hasDefault = false;
for (Stmt.Case c : stmt.cases) {
// first, resolve the constants
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr e : c.expr) {
values.add(resolveAsConstant(e, current));
}
c.constants = values;
// second, propagate through the statements
Environment localEnv = environment.clone();
localEnv = propagate(c.stmts, localEnv);
if (finalEnv == null) {
finalEnv = localEnv;
} else {
finalEnv = finalEnv.merge(environment.keySet(), environment);
}
// third, keep track of whether a default
hasDefault |= c.expr.isEmpty();
}
if (!hasDefault) {
// in this case, there is no default case in the switch. We must
// therefore assume that there are values which will fall right
// through the switch statement without hitting a case. Therefore,
// we must include the original environment to accound for this.
finalEnv = finalEnv.merge(environment.keySet(), environment);
} else {
environment.free();
}
return finalEnv;
}
/**
* Type check a <code>throw</code> statement. We must check that the throw
* expression is well-formed. The environment after a throw statement is
* "bottom" because that represents an unreachable program point.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.Throw stmt, Environment environment) {
stmt.expr = propagate(stmt.expr, environment, current);
return BOTTOM;
}
/**
* Type check a try-catch statement.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.TryCatch stmt, Environment environment)
throws IOException {
for (Stmt.Catch handler : stmt.catches) {
// FIXME: need to deal with handler environments properly!
try {
Nominal type = resolveAsType(handler.unresolvedType, current);
handler.type = type;
Environment local = environment.clone();
local = local.declare(handler.variable, type, type);
propagate(handler.stmts, local);
local.free();
} catch (SyntaxError e) {
throw e;
} catch (Throwable t) {
internalFailure(t.getMessage(), filename, handler, t);
}
}
environment = propagate(stmt.body, environment);
// need to do handlers here
return environment;
}
/**
* Type check a <code>whiley</code> statement.
*
* @param stmt
* Statement to type check
* @param environment
* Determines the type of all variables immediately going into
* this block
* @return
*/
private Environment propagate(Stmt.While stmt, Environment environment) {
// Determine typing at beginning of loop
environment = computeFixedPoint(environment,stmt.body,stmt.condition,false,stmt);
// Type loop invariant(s)
List<Expr> stmt_invariants = stmt.invariants;
for (int i = 0; i != stmt_invariants.size(); ++i) {
Expr invariant = stmt_invariants.get(i);
invariant = propagate(invariant, environment, current);
stmt_invariants.set(i, invariant);
checkIsSubtype(Type.T_BOOL, invariant);
}
// Type condition assuming its false to represent the terminated loop.
// This is important if the condition contains a type test, as we'll
// know that doesn't hold here.
Pair<Expr, Environment> p = propagateCondition(stmt.condition, false,
environment, current);
stmt.condition = p.first();
environment = p.second();
return environment;
}
// LVals
private Expr.LVal propagate(Expr.LVal lval, Environment environment) {
try {
if (lval instanceof Expr.AbstractVariable) {
Expr.AbstractVariable av = (Expr.AbstractVariable) lval;
Nominal p = environment.getCurrentType(av.var);
if (p == null) {
syntaxError(errorMessage(UNKNOWN_VARIABLE), filename, lval);
}
Expr.AssignedVariable lv = new Expr.AssignedVariable(av.var,
av.attributes());
lv.type = p;
return lv;
} else if (lval instanceof Expr.RationalLVal) {
Expr.RationalLVal av = (Expr.RationalLVal) lval;
av.numerator = propagate(av.numerator, environment);
av.denominator = propagate(av.denominator, environment);
return av;
} else if (lval instanceof Expr.Dereference) {
Expr.Dereference pa = (Expr.Dereference) lval;
Expr.LVal src = propagate((Expr.LVal) pa.src, environment);
pa.src = src;
pa.srcType = expandAsReference(src.result());
return pa;
} else if (lval instanceof Expr.IndexOf) {
// this indicates either a list, string or dictionary update
Expr.IndexOf ai = (Expr.IndexOf) lval;
Expr.LVal src = propagate((Expr.LVal) ai.src, environment);
Expr index = propagate(ai.index, environment, current);
ai.src = src;
ai.index = index;
Nominal.EffectiveIndexible srcType = expandAsEffectiveMap(src
.result());
if (srcType == null) {
syntaxError(errorMessage(INVALID_LVAL_EXPRESSION),
filename, lval);
}
ai.srcType = srcType;
return ai;
} else if (lval instanceof Expr.FieldAccess) {
// this indicates a record update
Expr.FieldAccess ad = (Expr.FieldAccess) lval;
Expr.LVal src = propagate((Expr.LVal) ad.src, environment);
Expr.FieldAccess ra = new Expr.FieldAccess(src, ad.name,
ad.attributes());
Nominal.EffectiveRecord srcType = expandAsEffectiveRecord(src
.result());
if (srcType == null) {
syntaxError(errorMessage(INVALID_LVAL_EXPRESSION),
filename, lval);
} else if (srcType.field(ra.name) == null) {
syntaxError(errorMessage(RECORD_MISSING_FIELD, ra.name),
filename, lval);
}
ra.srcType = srcType;
return ra;
} else if (lval instanceof Expr.Tuple) {
// this indicates a tuple update
Expr.Tuple tup = (Expr.Tuple) lval;
ArrayList<Nominal> elements = new ArrayList<Nominal>();
for (int i = 0; i != tup.fields.size(); ++i) {
Expr element = tup.fields.get(i);
if (element instanceof Expr.LVal) {
element = propagate((Expr.LVal) element, environment);
tup.fields.set(i, element);
elements.add(element.result());
} else {
syntaxError(errorMessage(INVALID_LVAL_EXPRESSION),
filename, lval);
}
}
tup.type = Nominal.Tuple(elements);
return tup;
}
} catch (SyntaxError e) {
throw e;
} catch (Throwable e) {
internalFailure(e.getMessage(), filename, lval, e);
return null; // dead code
}
internalFailure("unknown lval: " + lval.getClass().getName(), filename,
lval);
return null; // dead code
}
/**
* The purpose of this method is to add variable names declared within a
* type pattern to the given environment. For example, as follows:
*
* <pre>
* define tup as {int x, int y} where x < y
* </pre>
*
* In this case, <code>x</code> and <code>y</code> are variable names
* declared as part of the pattern.
*
* <p>
* Note, variables are both declared and initialised with the given type. In
* some cases (e.g. parameters), this makes sense. In other cases (e.g.
* local variable declarations), it does not. In the latter, the variable
* should then be updated with an appropriate type.
* </p>
*
* @param src
* @param t
* @param environment
*/
private Environment addDeclaredVariables(TypePattern pattern,
Environment environment, WhileyFile.Context context) {
if (pattern instanceof TypePattern.Union) {
// FIXME: in principle, we can do better here. However, I leave this
// unusual case for the future.
} else if (pattern instanceof TypePattern.Intersection) {
// FIXME: in principle, we can do better here. However, I leave this
// unusual case for the future.
} else if (pattern instanceof TypePattern.Rational) {
TypePattern.Rational tp = (TypePattern.Rational) pattern;
environment = addDeclaredVariables(tp.numerator, environment,
context);
environment = addDeclaredVariables(tp.denominator, environment,
context);
} else if (pattern instanceof TypePattern.Record) {
TypePattern.Record tp = (TypePattern.Record) pattern;
for (TypePattern element : tp.elements) {
environment = addDeclaredVariables(element, environment,
context);
}
} else if (pattern instanceof TypePattern.Tuple) {
TypePattern.Tuple tp = (TypePattern.Tuple) pattern;
for (TypePattern element : tp.elements) {
environment = addDeclaredVariables(element, environment,
context);
}
} else {
TypePattern.Leaf lp = (TypePattern.Leaf) pattern;
if (lp.var != null) {
Nominal type = resolveAsType(pattern.toSyntacticType(), context);
environment = environment.declare(lp.var.var, type, type);
}
}
return environment;
}
// Condition
/**
* <p>
* Propagate type information through an expression being used as a
* condition, whilst checking it is well-typed at the same time. When used
* as a condition (e.g. of an if-statement) an expression may update the
* environment in accordance with any type tests used within. This is
* important to ensure that variables are retyped in e.g. if-statements. For
* example:
* </p>
*
* <pre>
* if x is int && x >= 0
* // x is int
* else:
* //
* </pre>
* <p>
* Here, the if-condition must update the type of x in the true branch, but
* *cannot* update the type of x in the false branch.
* </p>
* <p>
* To handle conditions on the false branch, this function uses a sign flag
* rather than expanding them using DeMorgan's laws (for efficiency). When
* determining type for the false branch, the sign flag is initially false.
* This prevents falsely concluding that e.g. "x is int" holds in the false
* branch.
* </p>
*
* @param expr
* Condition expression to type check and propagate through
* @param sign
* Indicates how expression should be treated. If true, then
* expression is treated "as is"; if false, then expression
* should be treated as negated
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
public Pair<Expr, Environment> propagateCondition(Expr expr, boolean sign,
Environment environment, Context context) {
// Split up into the compound and non-compound forms.
if (expr instanceof Expr.UnOp) {
return propagateCondition((Expr.UnOp) expr, sign, environment,
context);
} else if (expr instanceof Expr.BinOp) {
return propagateCondition((Expr.BinOp) expr, sign, environment,
context);
} else {
// For non-compound forms, can just default back to the base rules
// for general expressions.
expr = propagate(expr, environment, context);
checkIsSubtype(Type.T_BOOL, expr, context);
return new Pair<Expr, Environment>(expr, environment);
}
}
/**
* <p>
* Propagate type information through a unary expression being used as a
* condition and, in fact, only logical not is syntactically valid here.
* </p>
*
* @param expr
* Condition expression to type check and propagate through
* @param sign
* Indicates how expression should be treated. If true, then
* expression is treated "as is"; if false, then expression
* should be treated as negated
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
private Pair<Expr, Environment> propagateCondition(Expr.UnOp expr,
boolean sign, Environment environment, Context context) {
Expr.UnOp uop = (Expr.UnOp) expr;
// Check whether we have logical not
if (uop.op == Expr.UOp.NOT) {
Pair<Expr, Environment> p = propagateCondition(uop.mhs, !sign,
environment, context);
uop.mhs = p.first();
checkIsSubtype(Type.T_BOOL, uop.mhs, context);
uop.type = Nominal.T_BOOL;
return new Pair(uop, p.second());
} else {
// Nothing else other than logical not is valid at this point.
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, expr);
return null; // deadcode
}
}
/**
* <p>
* Propagate type information through a binary expression being used as a
* condition. In this case, only logical connectives ("&&", "||", "^") and
* comparators (e.g. "==", "<=", etc) are permitted here.
* </p>
*
* @param expr
* Condition expression to type check and propagate through
* @param sign
* Indicates how expression should be treated. If true, then
* expression is treated "as is"; if false, then expression
* should be treated as negated
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
private Pair<Expr, Environment> propagateCondition(Expr.BinOp bop,
boolean sign, Environment environment, Context context) {
Expr.BOp op = bop.op;
// Split into the two broard cases: logical connectives and primitives.
switch (op) {
case AND:
case OR:
case XOR:
return resolveNonLeafCondition(bop, sign, environment, context);
case EQ:
case NEQ:
case LT:
case LTEQ:
case GT:
case GTEQ:
case ELEMENTOF:
case SUBSET:
case SUBSETEQ:
case IS:
return resolveLeafCondition(bop, sign, environment, context);
default:
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, bop);
return null; // dead code
}
}
/**
* <p>
* Propagate type information through a binary expression being used as a
* logical connective ("&&", "||", "^").
* </p>
*
* @param bop
* Binary operator for this expression.
* @param sign
* Indicates how expression should be treated. If true, then
* expression is treated "as is"; if false, then expression
* should be treated as negated
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
private Pair<Expr, Environment> resolveNonLeafCondition(Expr.BinOp bop,
boolean sign, Environment environment, Context context) {
Expr.BOp op = bop.op;
Pair<Expr, Environment> p;
boolean followOn = (sign && op == Expr.BOp.AND)
|| (!sign && op == Expr.BOp.OR);
if (followOn) {
// In this case, the environment feeds directly from the result of
// propagating through the lhs into the rhs, and then into the
// result of this expression. This means that updates to the
// environment by either the lhs or rhs are visible outside of this
// method.
p = propagateCondition(bop.lhs, sign, environment.clone(), context);
bop.lhs = p.first();
p = propagateCondition(bop.rhs, sign, p.second(), context);
bop.rhs = p.first();
environment = p.second();
} else {
// We could do better here
p = propagateCondition(bop.lhs, sign, environment.clone(), context);
bop.lhs = p.first();
Environment local = p.second();
// Recompute the lhs assuming that it is false. This is necessary to
// generate the right environment going into the rhs, which is only
// evaluated if the lhs is false. For example:
// if(e is int && e > 0):
// else:
// In the false branch, we're determing the environment for
// !(e is int && e > 0). This becomes !(e is int) || (e <= 0) where
// on the rhs we require (e is int).
p = propagateCondition(bop.lhs, !sign, environment.clone(), context);
// Note, the following is intentional since we're specifically
// considering the case where the lhs was false, and this case is
// true.
p = propagateCondition(bop.rhs, sign, p.second(), context);
bop.rhs = p.first();
environment = local.merge(local.keySet(), p.second());
}
checkIsSubtype(Type.T_BOOL, bop.lhs, context);
checkIsSubtype(Type.T_BOOL, bop.rhs, context);
bop.srcType = Nominal.T_BOOL;
return new Pair<Expr, Environment>(bop, environment);
}
/**
* <p>
* Propagate type information through a binary expression being used as a
* comparators (e.g. "==", "<=", etc).
* </p>
*
* @param bop
* Binary operator for this expression.
* @param sign
* Indicates how expression should be treated. If true, then
* expression is treated "as is"; if false, then expression
* should be treated as negated
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
private Pair<Expr, Environment> resolveLeafCondition(Expr.BinOp bop,
boolean sign, Environment environment, Context context) {
Expr.BOp op = bop.op;
Expr lhs = propagate(bop.lhs, environment, context);
Expr rhs = propagate(bop.rhs, environment, context);
bop.lhs = lhs;
bop.rhs = rhs;
Type lhsRawType = lhs.result().raw();
Type rhsRawType = rhs.result().raw();
switch (op) {
case IS:
// this one is slightly more difficult. In the special case that
// we have a type constant on the right-hand side then we want
// to check that it makes sense. Otherwise, we just check that
// it has type meta.
if (rhs instanceof Expr.TypeVal) {
// yes, right-hand side is a constant
Expr.TypeVal tv = (Expr.TypeVal) rhs;
Nominal unconstrainedTestType = resolveAsUnconstrainedType(
tv.unresolvedType, context);
/**
* Determine the types guaranteed to hold on the true and false
* branches respectively. We have to use the negated
* unconstrainedTestType for the false branch because only that
* is guaranteed if the test fails. For example:
*
* <pre>
* define nat as int where $ >= 0
* define listnat as [int]|nat
*
* int f([int]|int x):
* if x if listnat:
* x : [int]|int
* ...
* else:
* x : int
* </pre>
*
* The unconstrained type of listnat is [int], since nat is a
* constrained type.
*/
Nominal glbForFalseBranch = Nominal.intersect(lhs.result(),
Nominal.Negation(unconstrainedTestType));
Nominal glbForTrueBranch = Nominal.intersect(lhs.result(),
tv.type);
if (glbForFalseBranch.raw() == Type.T_VOID) {
// DEFINITE TRUE CASE
syntaxError(errorMessage(BRANCH_ALWAYS_TAKEN), context, bop);
} else if (glbForTrueBranch.raw() == Type.T_VOID) {
// DEFINITE FALSE CASE
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,
tv.type.raw()), context, bop);
}
// Finally, if the lhs is local variable then update its
// type in the resulting environment.
if (lhs instanceof Expr.LocalVariable) {
Expr.LocalVariable lv = (Expr.LocalVariable) lhs;
Nominal newType;
if (sign) {
newType = glbForTrueBranch;
} else {
newType = glbForFalseBranch;
}
environment = environment.update(lv.var, newType);
}
} else {
// In this case, we can't update the type of the lhs since
// we don't know anything about the rhs. It may be possible
// to support bounds here in order to do that, but frankly
// that's future work :)
checkIsSubtype(Type.T_META, rhs, context);
}
bop.srcType = lhs.result();
break;
case ELEMENTOF:
Type.EffectiveList listType = rhsRawType instanceof Type.EffectiveList ? (Type.EffectiveList) rhsRawType
: null;
Type.EffectiveSet setType = rhsRawType instanceof Type.EffectiveSet ? (Type.EffectiveSet) rhsRawType
: null;
if (listType != null
&& !Type.isImplicitCoerciveSubtype(listType.element(),
lhsRawType)) {
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,
listType.element()), context, bop);
} else if (setType != null
&& !Type.isImplicitCoerciveSubtype(setType.element(),
lhsRawType)) {
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,
setType.element()), context, bop);
}
bop.srcType = rhs.result();
break;
case SUBSET:
case SUBSETEQ:
case LT:
case LTEQ:
case GTEQ:
case GT:
if (op == Expr.BOp.SUBSET || op == Expr.BOp.SUBSETEQ) {
checkIsSubtype(Type.T_SET_ANY, lhs, context);
checkIsSubtype(Type.T_SET_ANY, rhs, context);
} else {
checkIsSubtype(Type.T_REAL, lhs, context);
checkIsSubtype(Type.T_REAL, rhs, context);
}
if (Type.isImplicitCoerciveSubtype(lhsRawType, rhsRawType)) {
bop.srcType = lhs.result();
} else if (Type.isImplicitCoerciveSubtype(rhsRawType, lhsRawType)) {
bop.srcType = rhs.result();
} else {
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,
rhsRawType), context, bop);
return null; // dead code
}
break;
case NEQ:
// following is a sneaky trick for the special case below
sign = !sign;
case EQ:
// first, check for special case of e.g. x != null. This is then
// treated the same as !(x is null)
if (lhs instanceof Expr.LocalVariable
&& rhs instanceof Expr.Constant
&& ((Expr.Constant) rhs).value == Constant.V_NULL) {
// bingo, special case
Expr.LocalVariable lv = (Expr.LocalVariable) lhs;
Nominal newType;
Nominal glb = Nominal.intersect(lhs.result(), Nominal.T_NULL);
if (glb.raw() == Type.T_VOID) {
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhs.result()
.raw(), Type.T_NULL), context, bop);
return null;
} else if (sign) {
newType = glb;
} else {
newType = Nominal
.intersect(lhs.result(), Nominal.T_NOTNULL);
}
bop.srcType = lhs.result();
environment = environment.update(lv.var, newType);
} else {
// handle general case
if (Type.isImplicitCoerciveSubtype(lhsRawType, rhsRawType)) {
bop.srcType = lhs.result();
} else if (Type.isImplicitCoerciveSubtype(rhsRawType,
lhsRawType)) {
bop.srcType = rhs.result();
} else {
syntaxError(
errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,
rhsRawType), context, bop);
return null; // dead code
}
}
}
return new Pair<Expr, Environment>(bop, environment);
}
// Expressions
/**
* Propagate types through a given expression, whilst checking that it is
* well typed. In this case, any use of a runtime type test cannot effect
* callers of this function.
*
* @param expr
* Expression to propagate types through.
* @param environment
* Determines the type of all variables immediately going into
* this expression
* @param context
* Enclosing context of this expression (e.g. type declaration,
* function declaration, etc)
* @return
*/
public Expr propagate(Expr expr, Environment environment, Context context) {
try {
if (expr instanceof Expr.BinOp) {
return propagate((Expr.BinOp) expr, environment, context);
} else if (expr instanceof Expr.UnOp) {
return propagate((Expr.UnOp) expr, environment, context);
} else if (expr instanceof Expr.Comprehension) {
return propagate((Expr.Comprehension) expr, environment,
context);
} else if (expr instanceof Expr.Constant) {
return propagate((Expr.Constant) expr, environment, context);
} else if (expr instanceof Expr.Cast) {
return propagate((Expr.Cast) expr, environment, context);
} else if (expr instanceof Expr.ConstantAccess) {
return propagate((Expr.ConstantAccess) expr, environment,
context);
} else if (expr instanceof Expr.FieldAccess) {
return propagate((Expr.FieldAccess) expr, environment, context);
} else if (expr instanceof Expr.Map) {
return propagate((Expr.Map) expr, environment, context);
} else if (expr instanceof Expr.AbstractFunctionOrMethod) {
return propagate((Expr.AbstractFunctionOrMethod) expr,
environment, context);
} else if (expr instanceof Expr.AbstractInvoke) {
return propagate((Expr.AbstractInvoke) expr, environment,
context);
} else if (expr instanceof Expr.AbstractIndirectInvoke) {
return propagate((Expr.AbstractIndirectInvoke) expr,
environment, context);
} else if (expr instanceof Expr.IndexOf) {
return propagate((Expr.IndexOf) expr, environment, context);
} else if (expr instanceof Expr.Lambda) {
return propagate((Expr.Lambda) expr, environment, context);
} else if (expr instanceof Expr.LengthOf) {
return propagate((Expr.LengthOf) expr, environment, context);
} else if (expr instanceof Expr.LocalVariable) {
return propagate((Expr.LocalVariable) expr, environment,
context);
} else if (expr instanceof Expr.List) {
return propagate((Expr.List) expr, environment, context);
} else if (expr instanceof Expr.Set) {
return propagate((Expr.Set) expr, environment, context);
} else if (expr instanceof Expr.SubList) {
return propagate((Expr.SubList) expr, environment, context);
} else if (expr instanceof Expr.SubString) {
return propagate((Expr.SubString) expr, environment, context);
} else if (expr instanceof Expr.Dereference) {
return propagate((Expr.Dereference) expr, environment, context);
} else if (expr instanceof Expr.Record) {
return propagate((Expr.Record) expr, environment, context);
} else if (expr instanceof Expr.New) {
return propagate((Expr.New) expr, environment, context);
} else if (expr instanceof Expr.Tuple) {
return propagate((Expr.Tuple) expr, environment, context);
} else if (expr instanceof Expr.TypeVal) {
return propagate((Expr.TypeVal) expr, environment, context);
}
} catch (ResolveError e) {
syntaxError(errorMessage(RESOLUTION_ERROR, e.getMessage()),
context, expr, e);
} catch (SyntaxError e) {
throw e;
} catch (Throwable e) {
internalFailure(e.getMessage(), context, expr, e);
return null; // dead code
}
internalFailure("unknown expression: " + expr.getClass().getName(),
context, expr);
return null; // dead code
}
private Expr propagate(Expr.BinOp expr, Environment environment,
Context context) throws IOException {
// TODO: split binop into arithmetic and conditional operators. This
// would avoid the following case analysis since conditional binary
// operators and arithmetic binary operators actually behave quite
// differently.
switch (expr.op) {
case AND:
case OR:
case XOR:
case EQ:
case NEQ:
case LT:
case LTEQ:
case GT:
case GTEQ:
case ELEMENTOF:
case SUBSET:
case SUBSETEQ:
case IS:
return propagateCondition(expr, true, environment, context).first();
}
Expr lhs = propagate(expr.lhs, environment, context);
Expr rhs = propagate(expr.rhs, environment, context);
expr.lhs = lhs;
expr.rhs = rhs;
Type lhsRawType = lhs.result().raw();
Type rhsRawType = rhs.result().raw();
boolean lhs_set = Type.isImplicitCoerciveSubtype(Type.T_SET_ANY,
lhsRawType);
boolean rhs_set = Type.isImplicitCoerciveSubtype(Type.T_SET_ANY,
rhsRawType);
boolean lhs_list = Type.isImplicitCoerciveSubtype(Type.T_LIST_ANY,
lhsRawType);
boolean rhs_list = Type.isImplicitCoerciveSubtype(Type.T_LIST_ANY,
rhsRawType);
boolean lhs_str = Type.isSubtype(Type.T_STRING, lhsRawType);
boolean rhs_str = Type.isSubtype(Type.T_STRING, rhsRawType);
Type srcType;
if (lhs_str || rhs_str) {
switch (expr.op) {
case LISTAPPEND:
expr.op = Expr.BOp.STRINGAPPEND;
case STRINGAPPEND:
break;
default:
syntaxError("Invalid string operation: " + expr.op, context,
expr);
}
srcType = Type.T_STRING;
} else if (lhs_list && rhs_list) {
checkIsSubtype(Type.T_LIST_ANY, lhs, context);
checkIsSubtype(Type.T_LIST_ANY, rhs, context);
Type.EffectiveList lel = (Type.EffectiveList) lhsRawType;
Type.EffectiveList rel = (Type.EffectiveList) rhsRawType;
switch (expr.op) {
case LISTAPPEND:
srcType = Type.List(Type.Union(lel.element(), rel.element()),
false);
break;
default:
syntaxError("invalid list operation: " + expr.op, context, expr);
return null; // dead-code
}
} else if (lhs_set && rhs_set) {
checkIsSubtype(Type.T_SET_ANY, lhs, context);
checkIsSubtype(Type.T_SET_ANY, rhs, context);
// FIXME: something tells me there should be a function for doing
// this. Perhaps effectiveSetType?
if (lhs_list) {
Type.EffectiveList tmp = (Type.EffectiveList) lhsRawType;
lhsRawType = Type.Set(tmp.element(), false);
}
if (rhs_list) {
Type.EffectiveList tmp = (Type.EffectiveList) rhsRawType;
rhsRawType = Type.Set(tmp.element(), false);
}
// FIXME: loss of nominal information here
Type.EffectiveSet ls = (Type.EffectiveSet) lhsRawType;
Type.EffectiveSet rs = (Type.EffectiveSet) rhsRawType;
switch (expr.op) {
case ADD:
expr.op = Expr.BOp.UNION;
case UNION:
// TODO: this forces unnecessary coercions, which would be
// good to remove.
srcType = Type.Set(Type.Union(ls.element(), rs.element()),
false);
break;
case BITWISEAND:
expr.op = Expr.BOp.INTERSECTION;
case INTERSECTION:
// FIXME: this is just plain wierd.
if (Type.isSubtype(lhsRawType, rhsRawType)) {
srcType = rhsRawType;
} else {
srcType = lhsRawType;
}
break;
case SUB:
expr.op = Expr.BOp.DIFFERENCE;
case DIFFERENCE:
srcType = lhsRawType;
break;
default:
syntaxError("invalid set operation: " + expr.op, context, expr);
return null; // deadcode
}
} else {
switch (expr.op) {
case IS:
case AND:
case OR:
case XOR:
return propagateCondition(expr, true, environment, context)
.first();
case BITWISEAND:
case BITWISEOR:
case BITWISEXOR:
checkIsSubtype(Type.T_BYTE, lhs, context);
checkIsSubtype(Type.T_BYTE, rhs, context);
srcType = Type.T_BYTE;
break;
case LEFTSHIFT:
case RIGHTSHIFT:
checkIsSubtype(Type.T_BYTE, lhs, context);
checkIsSubtype(Type.T_INT, rhs, context);
srcType = Type.T_BYTE;
break;
case RANGE:
checkIsSubtype(Type.T_INT, lhs, context);
checkIsSubtype(Type.T_INT, rhs, context);
srcType = Type.List(Type.T_INT, false);
break;
case REM:
checkIsSubtype(Type.T_INT, lhs, context);
checkIsSubtype(Type.T_INT, rhs, context);
srcType = Type.T_INT;
break;
default:
// all other operations go through here
if (Type.isImplicitCoerciveSubtype(lhsRawType, rhsRawType)) {
checkIsSubtype(Type.T_REAL, lhs, context);
if (Type.isSubtype(Type.T_CHAR, lhsRawType)) {
srcType = Type.T_INT;
} else if (Type.isSubtype(Type.T_INT, lhsRawType)) {
srcType = Type.T_INT;
} else {
srcType = Type.T_REAL;
}
} else {
checkIsSubtype(Type.T_REAL, lhs, context);
checkIsSubtype(Type.T_REAL, rhs, context);
if (Type.isSubtype(Type.T_CHAR, rhsRawType)) {
srcType = Type.T_INT;
} else if (Type.isSubtype(Type.T_INT, rhsRawType)) {
srcType = Type.T_INT;
} else {
srcType = Type.T_REAL;
}
}
}
}
// FIXME: loss of nominal information
expr.srcType = Nominal.construct(srcType, srcType);
return expr;
}
private Expr propagate(Expr.UnOp expr, Environment environment,
Context context) throws IOException {
if (expr.op == Expr.UOp.NOT) {
// hand off to special method for conditions
return propagateCondition(expr, true, environment, context).first();
}
Expr src = propagate(expr.mhs, environment, context);
expr.mhs = src;
switch (expr.op) {
case NEG:
checkIsSubtype(Type.T_REAL, src, context);
break;
case INVERT:
checkIsSubtype(Type.T_BYTE, src, context);
break;
default:
internalFailure(
"unknown operator: " + expr.op.getClass().getName(),
context, expr);
}
expr.type = src.result();
return expr;
}
private Expr propagate(Expr.Comprehension expr, Environment environment,
Context context) throws IOException, ResolveError {
ArrayList<Pair<String, Expr>> sources = expr.sources;
Environment local = environment.clone();
for (int i = 0; i != sources.size(); ++i) {
Pair<String, Expr> p = sources.get(i);
Expr e = propagate(p.second(), local, context);
p = new Pair<String, Expr>(p.first(), e);
sources.set(i, p);
Nominal type = e.result();
Nominal.EffectiveCollection colType = expandAsEffectiveCollection(type);
if (colType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION),
context, e);
return null; // dead code
}
// update environment for subsequent source expressions, the
// condition and the value.
local = local.declare(p.first(), colType.element(), colType.element());
}
if (expr.condition != null) {
expr.condition = propagate(expr.condition, local, context);
}
if (expr.cop == Expr.COp.SETCOMP || expr.cop == Expr.COp.LISTCOMP) {
expr.value = propagate(expr.value, local, context);
expr.type = Nominal.Set(expr.value.result(), false);
} else {
expr.type = Nominal.T_BOOL;
}
local.free();
return expr;
}
private Expr propagate(Expr.Constant expr, Environment environment,
Context context) {
return expr;
}
private Expr propagate(Expr.Cast c, Environment environment, Context context)
throws IOException {
c.expr = propagate(c.expr, environment, context);
c.type = resolveAsType(c.unresolvedType, context);
Type from = c.expr.result().raw();
Type to = c.type.raw();
if (!Type.isExplicitCoerciveSubtype(to, from)) {
syntaxError(errorMessage(SUBTYPE_ERROR, to, from), context, c);
}
return c;
}
private Expr propagate(Expr.AbstractFunctionOrMethod expr,
Environment environment, Context context) throws IOException, ResolveError {
if (expr instanceof Expr.FunctionOrMethod) {
return expr;
}
Pair<NameID, Nominal.FunctionOrMethod> p;
if (expr.paramTypes != null) {
ArrayList<Nominal> paramTypes = new ArrayList<Nominal>();
for (SyntacticType t : expr.paramTypes) {
paramTypes.add(resolveAsType(t, context));
}
// FIXME: clearly a bug here in the case of message reference
p = (Pair<NameID, Nominal.FunctionOrMethod>) resolveAsFunctionOrMethod(
expr.name, paramTypes, context);
} else {
p = resolveAsFunctionOrMethod(expr.name, context);
}
expr = new Expr.FunctionOrMethod(p.first(), expr.paramTypes,
expr.attributes());
expr.type = p.second();
return expr;
}
private Expr propagate(Expr.Lambda expr, Environment environment,
Context context) throws IOException {
ArrayList<Type> rawTypes = new ArrayList<Type>();
ArrayList<Type> nomTypes = new ArrayList<Type>();
for (WhileyFile.Parameter p : expr.parameters) {
Nominal n = resolveAsType(p.type, context);
rawTypes.add(n.raw());
nomTypes.add(n.nominal());
// Now, update the environment to include those declared variables
String var = p.name();
if (environment.containsKey(var)) {
syntaxError(errorMessage(VARIABLE_ALREADY_DEFINED, var),
context, p);
}
environment = environment.declare(var, n, n);
}
expr.body = propagate(expr.body, environment, context);
Type.FunctionOrMethod rawType;
Type.FunctionOrMethod nomType;
if (Exprs.isPure(expr.body, context)) {
rawType = Type.Function(expr.body.result().raw(), Type.T_VOID,
rawTypes);
nomType = Type.Function(expr.body.result().nominal(), Type.T_VOID,
nomTypes);
} else {
rawType = Type.Method(expr.body.result().raw(), Type.T_VOID,
rawTypes);
nomType = Type.Method(expr.body.result().nominal(), Type.T_VOID,
nomTypes);
}
expr.type = (Nominal.FunctionOrMethod) Nominal.construct(nomType,
rawType);
return expr;
}
private Expr propagate(Expr.AbstractIndirectInvoke expr,
Environment environment, Context context) throws IOException, ResolveError {
expr.src = propagate(expr.src, environment, context);
Nominal type = expr.src.result();
if (!(type instanceof Nominal.FunctionOrMethod)) {
syntaxError("function or method type expected", context, expr.src);
}
Nominal.FunctionOrMethod funType = (Nominal.FunctionOrMethod) type;
List<Nominal> paramTypes = funType.params();
ArrayList<Expr> exprArgs = expr.arguments;
if (paramTypes.size() != exprArgs.size()) {
syntaxError(
"insufficient arguments for function or method invocation",
context, expr.src);
}
for (int i = 0; i != exprArgs.size(); ++i) {
Nominal pt = paramTypes.get(i);
Expr arg = propagate(exprArgs.get(i), environment, context);
checkIsSubtype(pt, arg, context);
exprArgs.set(i, arg);
}
if (funType instanceof Nominal.Function) {
Expr.IndirectFunctionCall ifc = new Expr.IndirectFunctionCall(
expr.src, exprArgs, expr.attributes());
ifc.functionType = (Nominal.Function) funType;
return ifc;
} else {
Expr.IndirectMethodCall imc = new Expr.IndirectMethodCall(expr.src,
exprArgs, expr.attributes());
imc.methodType = (Nominal.Method) funType;
return imc;
}
}
private Expr propagate(Expr.AbstractInvoke expr, Environment environment,
Context context) throws IOException, ResolveError {
// first, resolve through receiver and parameters.
Path.ID qualification = expr.qualification;
ArrayList<Expr> exprArgs = expr.arguments;
ArrayList<Nominal> paramTypes = new ArrayList<Nominal>();
for (int i = 0; i != exprArgs.size(); ++i) {
Expr arg = propagate(exprArgs.get(i), environment, context);
exprArgs.set(i, arg);
paramTypes.add(arg.result());
}
// second, determine the fully qualified name of this function based on
// the given function name and any supplied qualifications.
ArrayList<String> qualifications = new ArrayList<String>();
if (expr.qualification != null) {
for (String n : expr.qualification) {
qualifications.add(n);
}
}
qualifications.add(expr.name);
NameID name = resolveAsName(qualifications, context);
// third, lookup the appropriate function or method based on the name
// and given parameter types.
Nominal.FunctionOrMethod funType = resolveAsFunctionOrMethod(name,
paramTypes, context);
if (funType instanceof Nominal.Function) {
Expr.FunctionCall r = new Expr.FunctionCall(name, qualification,
exprArgs, expr.attributes());
r.functionType = (Nominal.Function) funType;
return r;
} else {
Expr.MethodCall r = new Expr.MethodCall(name, qualification,
exprArgs, expr.attributes());
r.methodType = (Nominal.Method) funType;
return r;
}
}
private Expr propagate(Expr.IndexOf expr, Environment environment,
Context context) throws IOException, ResolveError {
expr.src = propagate(expr.src, environment, context);
expr.index = propagate(expr.index, environment, context);
Nominal.EffectiveIndexible srcType = expandAsEffectiveMap(expr.src
.result());
if (srcType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION), context,
expr.src);
} else {
expr.srcType = srcType;
}
checkIsSubtype(srcType.key(), expr.index, context);
return expr;
}
private Expr propagate(Expr.LengthOf expr, Environment environment,
Context context) throws IOException, ResolveError {
expr.src = propagate(expr.src, environment, context);
Nominal srcType = expr.src.result();
Type rawSrcType = srcType.raw();
// First, check whether this is still only an abstract access and, in
// such case, upgrade it to the appropriate access expression.
if (rawSrcType instanceof Type.EffectiveCollection) {
expr.srcType = expandAsEffectiveCollection(srcType);
return expr;
} else {
syntaxError("found " + expr.src.result().nominal()
+ ", expected string, set, list or dictionary.", context,
expr.src);
}
// Second, determine the expanded src type for this access expression
// and check the key value.
checkIsSubtype(Type.T_STRING, expr.src, context);
return expr;
}
private Expr propagate(Expr.LocalVariable expr, Environment environment,
Context context) throws IOException {
Nominal type = environment.getCurrentType(expr.var);
expr.type = type;
return expr;
}
private Expr propagate(Expr.Set expr, Environment environment,
Context context) {
Nominal element = Nominal.T_VOID;
ArrayList<Expr> exprs = expr.arguments;
for (int i = 0; i != exprs.size(); ++i) {
Expr e = propagate(exprs.get(i), environment, context);
Nominal t = e.result();
exprs.set(i, e);
element = Nominal.Union(t, element);
}
expr.type = Nominal.Set(element, false);
return expr;
}
private Expr propagate(Expr.List expr, Environment environment,
Context context) {
Nominal element = Nominal.T_VOID;
ArrayList<Expr> exprs = expr.arguments;
for (int i = 0; i != exprs.size(); ++i) {
Expr e = propagate(exprs.get(i), environment, context);
Nominal t = e.result();
exprs.set(i, e);
element = Nominal.Union(t, element);
}
expr.type = Nominal.List(element, false);
return expr;
}
private Expr propagate(Expr.Map expr, Environment environment,
Context context) {
Nominal keyType = Nominal.T_VOID;
Nominal valueType = Nominal.T_VOID;
ArrayList<Pair<Expr, Expr>> exprs = expr.pairs;
for (int i = 0; i != exprs.size(); ++i) {
Pair<Expr, Expr> p = exprs.get(i);
Expr key = propagate(p.first(), environment, context);
Expr value = propagate(p.second(), environment, context);
Nominal kt = key.result();
Nominal vt = value.result();
exprs.set(i, new Pair<Expr, Expr>(key, value));
keyType = Nominal.Union(kt, keyType);
valueType = Nominal.Union(vt, valueType);
}
expr.type = Nominal.Map(keyType, valueType);
return expr;
}
private Expr propagate(Expr.Record expr, Environment environment,
Context context) {
HashMap<String, Expr> exprFields = expr.fields;
HashMap<String, Nominal> fieldTypes = new HashMap<String, Nominal>();
ArrayList<String> fields = new ArrayList<String>(exprFields.keySet());
for (String field : fields) {
Expr e = propagate(exprFields.get(field), environment, context);
Nominal t = e.result();
exprFields.put(field, e);
fieldTypes.put(field, t);
}
expr.type = Nominal.Record(false, fieldTypes);
return expr;
}
private Expr propagate(Expr.Tuple expr, Environment environment,
Context context) {
ArrayList<Expr> exprFields = expr.fields;
ArrayList<Nominal> fieldTypes = new ArrayList<Nominal>();
for (int i = 0; i != exprFields.size(); ++i) {
Expr e = propagate(exprFields.get(i), environment, context);
Nominal t = e.result();
exprFields.set(i, e);
fieldTypes.add(t);
}
expr.type = Nominal.Tuple(fieldTypes);
return expr;
}
private Expr propagate(Expr.SubList expr, Environment environment,
Context context) throws IOException, ResolveError {
expr.src = propagate(expr.src, environment, context);
expr.start = propagate(expr.start, environment, context);
expr.end = propagate(expr.end, environment, context);
checkIsSubtype(Type.T_LIST_ANY, expr.src, context);
checkIsSubtype(Type.T_INT, expr.start, context);
checkIsSubtype(Type.T_INT, expr.end, context);
expr.type = expandAsEffectiveList(expr.src.result());
if (expr.type == null) {
// must be a substring
return new Expr.SubString(expr.src, expr.start, expr.end,
expr.attributes());
}
return expr;
}
private Expr propagate(Expr.SubString expr, Environment environment,
Context context) throws IOException {
expr.src = propagate(expr.src, environment, context);
expr.start = propagate(expr.start, environment, context);
expr.end = propagate(expr.end, environment, context);
checkIsSubtype(Type.T_STRING, expr.src, context);
checkIsSubtype(Type.T_INT, expr.start, context);
checkIsSubtype(Type.T_INT, expr.end, context);
return expr;
}
private Expr propagate(Expr.FieldAccess ra, Environment environment,
Context context) throws IOException, ResolveError {
ra.src = propagate(ra.src, environment, context);
Nominal srcType = ra.src.result();
Nominal.EffectiveRecord recType = expandAsEffectiveRecord(srcType);
if (recType == null) {
syntaxError(errorMessage(RECORD_TYPE_REQUIRED, srcType.raw()),
context, ra);
}
Nominal fieldType = recType.field(ra.name);
if (fieldType == null) {
syntaxError(errorMessage(RECORD_MISSING_FIELD, ra.name), context,
ra);
}
ra.srcType = recType;
return ra;
}
private Expr propagate(Expr.ConstantAccess expr, Environment environment,
Context context) throws IOException {
// First, determine the fully qualified name of this function based on
// the given function name and any supplied qualifications.
ArrayList<String> qualifications = new ArrayList<String>();
if (expr.qualification != null) {
for (String n : expr.qualification) {
qualifications.add(n);
}
}
qualifications.add(expr.name);
try {
NameID name = resolveAsName(qualifications, context);
// Second, determine the value of the constant.
expr.value = resolveAsConstant(name);
return expr;
} catch (ResolveError e) {
syntaxError(errorMessage(UNKNOWN_VARIABLE), context, expr);
return null;
}
}
private Expr propagate(Expr.Dereference expr, Environment environment,
Context context) throws IOException, ResolveError {
Expr src = propagate(expr.src, environment, context);
expr.src = src;
Nominal.Reference srcType = expandAsReference(src.result());
if (srcType == null) {
syntaxError("invalid reference expression", context, src);
}
expr.srcType = srcType;
return expr;
}
private Expr propagate(Expr.New expr, Environment environment,
Context context) {
expr.expr = propagate(expr.expr, environment, context);
expr.type = Nominal.Reference(expr.expr.result());
return expr;
}
private Expr propagate(Expr.TypeVal expr, Environment environment,
Context context) throws IOException {
expr.type = resolveAsType(expr.unresolvedType, context);
return expr;
}
// Compute fixed point
/**
* Compute the fixed point of an environment across a body of statements.
* The fixed point is the environment which, starting from the initial
* environment, doesn't change after being put through body. For example:
*
* <pre>
* x = 1
* while i < 10:
* // x -> int, i -> int
* x = null
* i = i + 1
* // x -> null, i -> int
* </pre>
*
* <p>
* Here, we see the environment before the loop body, along with that after.
* The fixed point for this example, then, is {x -> int|null, i -> int}
* </p>
*
* <p>
* <b>NOTE:</b> The fixed-point computation is technically not guaranteed to
* terminate (i.e. because the lattice has infinite height). As a simplistic
* step, for now, the computatino just bails out after 10 iterations. In
* principle, one can do better and this is discussed in the following
* paper:
*
* <ul>
* <li>A Calculus for Constraint-Based Flow Typing. David J. Pearce. In
* Proceedings of the Workshop on Formal Techniques for Java-like Languages
* (FTFJP), Article 7, 2013.</li>
* </ul>
* (Aaaahhh, the irony that I haven't implemented by own paper :)
* </p>
*
* @param environment
* The initial environment, which is guaranteed not to be changed
* by this method.
* @param body
* The statement body which is to be iterated over.
* @param condition
* An optional condition which is to be included in the
* computation. Maybe null.
* @param doWhile
* Indicates whether this is a do-while loop or not. A do-while
* loop is different because the condition does not hold on the
* first iteration.
* @return
*/
private Environment computeFixedPoint(Environment environment,
ArrayList<Stmt> body, Expr condition, boolean doWhile,
SyntacticElement element) {
// The count is used simply to guarantee termination.
int count = 0;
// The original environment is an exact copy of the initial environment.
// This is needed to feed into the iteration.
Environment original = environment.clone();
// We clone the original environment again to force the refcount > 1
original = original.clone();
// Precompute the set of variables to be merged
Set<String> variables = original.keySet();
// The old environment is used to compare the environment after one
// iteration with previous "old" environment to see whether anything has
// changed.
Environment old;
// The temporary environment is used simply to hold the environment in
// between the condition and the statement body.
Environment tmp;
do {
// First, take a copy of environment so we can later tell whether anything changed.
old = environment.clone();
// Second, propagate through condition (if applicable). This may
// update the environment if one or more type tests are used.
if(condition != null && !doWhile) {
tmp = propagateCondition(condition, true, old.clone(), current)
.second();
} else {
tmp = old;
doWhile = false;
}
// Merge updated environment with original environment to produce
// potentially updated environment.
environment = original.merge(variables, propagate(body, tmp));
old.free(); // hacky, but safe
// Finally, check loop count to force termination
if(count++ == 10) {
internalFailure("Unable to type loop",filename,element);
}
} while (!environment.equals(old));
return environment;
}
// Resolve as Function or Method
/**
* Responsible for determining the true type of a method or function being
* invoked. To do this, it must find the function/method with the most
* precise type that matches the argument types.
*
* @param nid
* @param parameters
* @return
* @throws IOException
*/
public Nominal.FunctionOrMethod resolveAsFunctionOrMethod(NameID nid,
List<Nominal> parameters, Context context) throws IOException,
ResolveError {
// Thet set of candidate names and types for this function or method.
HashSet<Pair<NameID, Nominal.FunctionOrMethod>> candidates = new HashSet<Pair<NameID, Nominal.FunctionOrMethod>>();
// First, add all valid candidates to the list without considering which
// is the most precise.
addCandidateFunctionsAndMethods(nid, parameters, candidates, context);
// Second, add to narrow down the list of candidates to a single choice.
// If this is impossible, then we have an ambiguity error.
return selectCandidateFunctionOrMethod(nid.name(), parameters,
candidates, context).second();
}
public Pair<NameID, Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(
String name, Context context) throws IOException, ResolveError {
return resolveAsFunctionOrMethod(name, null, context);
}
public Pair<NameID, Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(
String name, List<Nominal> parameters, Context context)
throws IOException,ResolveError {
HashSet<Pair<NameID, Nominal.FunctionOrMethod>> candidates = new HashSet<Pair<NameID, Nominal.FunctionOrMethod>>();
// first, try to find the matching message
for (WhileyFile.Import imp : context.imports()) {
String impName = imp.name;
if (impName == null || impName.equals(name) || impName.equals("*")) {
Trie filter = imp.filter;
if (impName == null) {
// import name is null, but it's possible that a module of
// the given name exists, in which case any matching names
// are automatically imported.
filter = filter.parent().append(name);
}
for (Path.ID mid : builder.imports(filter)) {
NameID nid = new NameID(mid, name);
addCandidateFunctionsAndMethods(nid, parameters,
candidates, context);
}
}
}
return selectCandidateFunctionOrMethod(name, parameters, candidates,
context);
}
private boolean paramSubtypes(Type.FunctionOrMethod f1,
Type.FunctionOrMethod f2) {
List<Type> f1_params = f1.params();
List<Type> f2_params = f2.params();
if (f1_params.size() == f2_params.size()) {
for (int i = 0; i != f1_params.size(); ++i) {
Type f1_param = f1_params.get(i);
Type f2_param = f2_params.get(i);
if (!Type.isImplicitCoerciveSubtype(f1_param, f2_param)) {
return false;
}
}
return true;
}
return false;
}
private boolean paramStrictSubtypes(Type.FunctionOrMethod f1,
Type.FunctionOrMethod f2) {
List<Type> f1_params = f1.params();
List<Type> f2_params = f2.params();
if (f1_params.size() == f2_params.size()) {
boolean allEqual = true;
for (int i = 0; i != f1_params.size(); ++i) {
Type f1_param = f1_params.get(i);
Type f2_param = f2_params.get(i);
if (!Type.isImplicitCoerciveSubtype(f1_param, f2_param)) {
return false;
}
allEqual &= f1_param.equals(f2_param);
}
// This function returns true if the parameters are a strict
// subtype. Therefore, if they are all equal it must return false.
return !allEqual;
}
return false;
}
private String parameterString(List<Nominal> paramTypes) {
String paramStr = "(";
boolean firstTime = true;
if (paramTypes == null) {
paramStr += "...";
} else {
for (Nominal t : paramTypes) {
if (!firstTime) {
paramStr += ",";
}
firstTime = false;
paramStr += t.nominal();
}
}
return paramStr + ")";
}
private Pair<NameID, Nominal.FunctionOrMethod> selectCandidateFunctionOrMethod(
String name, List<Nominal> parameters,
Collection<Pair<NameID, Nominal.FunctionOrMethod>> candidates,
Context context) throws IOException,ResolveError {
List<Type> rawParameters;
Type.Function target;
if (parameters != null) {
rawParameters = stripNominal(parameters);
target = (Type.Function) Type.Function(Type.T_ANY, Type.T_ANY,
rawParameters);
} else {
rawParameters = null;
target = null;
}
NameID candidateID = null;
Nominal.FunctionOrMethod candidateType = null;
for (Pair<NameID, Nominal.FunctionOrMethod> p : candidates) {
Nominal.FunctionOrMethod nft = p.second();
Type.FunctionOrMethod ft = nft.raw();
if (parameters == null || paramSubtypes(ft, target)) {
// this is now a genuine candidate
if (candidateType == null
|| paramStrictSubtypes(candidateType.raw(), ft)) {
candidateType = nft;
candidateID = p.first();
} else if (!paramStrictSubtypes(ft, candidateType.raw())) {
// this is an ambiguous error
String msg = name + parameterString(parameters)
+ " is ambiguous";
// FIXME: should report all ambiguous matches here
msg += "\n\tfound: " + candidateID + " : "
+ candidateType.nominal();
msg += "\n\tfound: " + p.first() + " : "
+ p.second().nominal();
throw new ResolveError(msg);
}
}
}
if (candidateType == null) {
// second, didn't find matching message so generate error message
String msg = "no match for " + name + parameterString(parameters);
for (Pair<NameID, Nominal.FunctionOrMethod> p : candidates) {
msg += "\n\tfound: " + p.first() + " : " + p.second().nominal();
}
throw new ResolveError(msg);
} else {
// now check protection modifier
WhileyFile wf = builder.getSourceFile(candidateID.module());
if (wf != null) {
if (wf != context.file()) {
for (WhileyFile.FunctionOrMethod d : wf.declarations(
WhileyFile.FunctionOrMethod.class,
candidateID.name())) {
if (d.parameters.equals(candidateType.params())) {
if (!d.hasModifier(Modifier.PUBLIC)
&& !d.hasModifier(Modifier.PROTECTED)) {
String msg = candidateID.module() + "." + name
+ parameterString(parameters)
+ " is not visible";
throw new ResolveError(msg);
}
}
}
}
} else {
WyilFile m = builder.getModule(candidateID.module());
WyilFile.FunctionOrMethodDeclaration d = m.method(
candidateID.name(), candidateType.raw());
if (!d.hasModifier(Modifier.PUBLIC)
&& !d.hasModifier(Modifier.PROTECTED)) {
String msg = candidateID.module() + "." + name
+ parameterString(parameters) + " is not visible";
throw new ResolveError(msg);
}
}
}
return new Pair<NameID, Nominal.FunctionOrMethod>(candidateID,
candidateType);
}
private void addCandidateFunctionsAndMethods(NameID nid,
List<?> parameters,
Collection<Pair<NameID, Nominal.FunctionOrMethod>> candidates,
Context context) throws IOException {
Path.ID mid = nid.module();
int nparams = parameters != null ? parameters.size() : -1;
WhileyFile wf = builder.getSourceFile(mid);
if (wf != null) {
for (WhileyFile.FunctionOrMethod f : wf.declarations(
WhileyFile.FunctionOrMethod.class, nid.name())) {
if (nparams == -1 || f.parameters.size() == nparams) {
Nominal.FunctionOrMethod ft = (Nominal.FunctionOrMethod) resolveAsType(
f.unresolvedType(), f);
candidates.add(new Pair<NameID, Nominal.FunctionOrMethod>(
nid, ft));
}
}
} else {
WyilFile m = builder.getModule(mid);
for (WyilFile.FunctionOrMethodDeclaration mm : m.methods()) {
if ((mm.isFunction() || mm.isMethod())
&& mm.name().equals(nid.name())
&& (nparams == -1 || mm.type().params().size() == nparams)) {
// FIXME: loss of nominal information
// FIXME: loss of visibility information (e.g if this
// function is declared in terms of a protected type)
Type.FunctionOrMethod t = (Type.FunctionOrMethod) mm
.type();
Nominal.FunctionOrMethod fom;
if (t instanceof Type.Function) {
Type.Function ft = (Type.Function) t;
fom = new Nominal.Function(ft, ft);
} else {
Type.Method mt = (Type.Method) t;
fom = new Nominal.Method(mt, mt);
}
candidates
.add(new Pair<NameID, Nominal.FunctionOrMethod>(
nid, fom));
}
}
}
}
private static List<Type> stripNominal(List<Nominal> types) {
ArrayList<Type> r = new ArrayList<Type>();
for (Nominal t : types) {
r.add(t.raw());
}
return r;
}
// ResolveAsName
public NameID resolveAsName(String name, Context context)
throws IOException, ResolveError {
for (WhileyFile.Import imp : context.imports()) {
String impName = imp.name;
if (impName == null || impName.equals(name) || impName.equals("*")) {
Trie filter = imp.filter;
if (impName == null) {
// import name is null, but it's possible that a module of
// the given name exists, in which case any matching names
// are automatically imported.
filter = filter.parent().append(name);
}
for (Path.ID mid : builder.imports(filter)) {
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
// ok, we have found the name in question. But, is it
// visible?
if (isNameVisible(nid, context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
}
}
}
throw new ResolveError("name not found: " + name);
}
public NameID resolveAsName(List<String> names, Context context)
throws IOException, ResolveError {
if (names.size() == 1) {
return resolveAsName(names.get(0), context);
} else if (names.size() == 2) {
String name = names.get(1);
Path.ID mid = resolveAsModule(names.get(0), context);
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
if (isNameVisible(nid, context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
} else {
String name = names.get(names.size() - 1);
String module = names.get(names.size() - 2);
Path.ID pkg = Trie.ROOT;
for (int i = 0; i != names.size() - 2; ++i) {
pkg = pkg.append(names.get(i));
}
Path.ID mid = pkg.append(module);
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
if (isNameVisible(nid, context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
}
String name = null;
for (String n : names) {
if (name != null) {
name = name + "." + n;
} else {
name = n;
}
}
throw new ResolveError("name not found: " + name);
}
public Path.ID resolveAsModule(String name, Context context)
throws IOException, ResolveError {
for (WhileyFile.Import imp : context.imports()) {
Trie filter = imp.filter;
String last = filter.last();
if (last.equals("*")) {
// this is generic import, so narrow the filter.
filter = filter.parent().append(name);
} else if (!last.equals(name)) {
continue; // skip as not relevant
}
for (Path.ID mid : builder.imports(filter)) {
return mid;
}
}
throw new ResolveError("module not found: " + name);
}
// ResolveAsType
public Nominal.Function resolveAsType(SyntacticType.Function t,
Context context) {
return (Nominal.Function) resolveAsType((SyntacticType) t, context);
}
public Nominal.Method resolveAsType(SyntacticType.Method t, Context context) {
return (Nominal.Method) resolveAsType((SyntacticType) t, context);
}
public Nominal resolveAsType(SyntacticType type, Context context) {
Type nominalType = resolveAsType(type, context, true, false);
Type rawType = resolveAsType(type, context, false, false);
return Nominal.construct(nominalType, rawType);
}
public Nominal resolveAsUnconstrainedType(SyntacticType type,
Context context) {
Type nominalType = resolveAsType(type, context, true, true);
Type rawType = resolveAsType(type, context, false, true);
return Nominal.construct(nominalType, rawType);
}
private Type resolveAsType(SyntacticType t, Context context,
boolean nominal, boolean unconstrained) {
if (t instanceof SyntacticType.Primitive) {
if (t instanceof SyntacticType.Any) {
return Type.T_ANY;
} else if (t instanceof SyntacticType.Void) {
return Type.T_VOID;
} else if (t instanceof SyntacticType.Null) {
return Type.T_NULL;
} else if (t instanceof SyntacticType.Bool) {
return Type.T_BOOL;
} else if (t instanceof SyntacticType.Byte) {
return Type.T_BYTE;
} else if (t instanceof SyntacticType.Char) {
return Type.T_CHAR;
} else if (t instanceof SyntacticType.Int) {
return Type.T_INT;
} else if (t instanceof SyntacticType.Real) {
return Type.T_REAL;
} else if (t instanceof SyntacticType.Strung) {
return Type.T_STRING;
} else {
internalFailure("unrecognised type encountered ("
+ t.getClass().getName() + ")", context, t);
return null; // deadcode
}
} else {
ArrayList<Automaton.State> states = new ArrayList<Automaton.State>();
HashMap<NameID, Integer> roots = new HashMap<NameID, Integer>();
resolveAsType(t, context, states, roots, nominal, unconstrained);
return Type.construct(new Automaton(states));
}
}
private int resolveAsType(SyntacticType type, Context context,
ArrayList<Automaton.State> states, HashMap<NameID, Integer> roots,
boolean nominal, boolean unconstrained) {
if (type instanceof SyntacticType.Primitive) {
return resolveAsType((SyntacticType.Primitive) type, context,
states);
}
int myIndex = states.size();
int myKind;
int[] myChildren;
Object myData = null;
boolean myDeterministic = true;
states.add(null); // reserve space for me
if (type instanceof SyntacticType.List) {
SyntacticType.List lt = (SyntacticType.List) type;
myKind = Type.K_LIST;
myChildren = new int[1];
myChildren[0] = resolveAsType(lt.element, context, states, roots,
nominal, unconstrained);
myData = false;
} else if (type instanceof SyntacticType.Set) {
SyntacticType.Set st = (SyntacticType.Set) type;
myKind = Type.K_SET;
myChildren = new int[1];
myChildren[0] = resolveAsType(st.element, context, states, roots,
nominal, unconstrained);
myData = false;
} else if (type instanceof SyntacticType.Map) {
SyntacticType.Map st = (SyntacticType.Map) type;
myKind = Type.K_MAP;
myChildren = new int[2];
myChildren[0] = resolveAsType(st.key, context, states, roots,
nominal, unconstrained);
myChildren[1] = resolveAsType(st.value, context, states, roots,
nominal, unconstrained);
} else if (type instanceof SyntacticType.Record) {
SyntacticType.Record tt = (SyntacticType.Record) type;
HashMap<String, SyntacticType> ttTypes = tt.types;
Type.Record.State fields = new Type.Record.State(tt.isOpen,
ttTypes.keySet());
Collections.sort(fields);
myKind = Type.K_RECORD;
myChildren = new int[fields.size()];
for (int i = 0; i != fields.size(); ++i) {
String field = fields.get(i);
myChildren[i] = resolveAsType(ttTypes.get(field), context,
states, roots, nominal, unconstrained);
}
myData = fields;
} else if (type instanceof SyntacticType.Tuple) {
SyntacticType.Tuple tt = (SyntacticType.Tuple) type;
ArrayList<SyntacticType> ttTypes = tt.types;
myKind = Type.K_TUPLE;
myChildren = new int[ttTypes.size()];
for (int i = 0; i != ttTypes.size(); ++i) {
myChildren[i] = resolveAsType(ttTypes.get(i), context, states,
roots, nominal, unconstrained);
}
} else if (type instanceof SyntacticType.Nominal) {
// This case corresponds to a user-defined type. This will be
// defined in some module (possibly ours), and we need to identify
// what module that is here, and save it for future use.
// Furthermore, we need to determine whether the name is visible
// (i.e. non-private) and/or whether the body of the type is visible
// (i.e. non-protected).
SyntacticType.Nominal dt = (SyntacticType.Nominal) type;
NameID nid;
try {
// Determine the full qualified name of this nominal type. This
// will additionally ensure that the name is visible
nid = resolveAsName(dt.names, context);
if (nominal || !isTypeVisible(nid, context)) {
myKind = Type.K_NOMINAL;
myData = nid;
myChildren = Automaton.NOCHILDREN;
} else {
// At this point, we're going to expand the given nominal
// type. We're going to use resolveAsType(NameID,...) to do
// this which will load the expanded type onto states at the
// current point. Therefore, we need to remove the initial
// null we loaded on.
states.remove(myIndex);
return resolveAsType(nid, states, roots, unconstrained);
}
} catch (ResolveError e) {
syntaxError(e.getMessage(), context, dt, e);
return 0; // dead-code
} catch (SyntaxError e) {
throw e;
} catch (Throwable e) {
internalFailure(e.getMessage(), context, dt, e);
return 0; // dead-code
}
} else if (type instanceof SyntacticType.Negation) {
SyntacticType.Negation ut = (SyntacticType.Negation) type;
myKind = Type.K_NEGATION;
myChildren = new int[1];
myChildren[0] = resolveAsType(ut.element, context, states, roots,
nominal, unconstrained);
} else if (type instanceof SyntacticType.Union) {
SyntacticType.Union ut = (SyntacticType.Union) type;
ArrayList<SyntacticType.NonUnion> utTypes = ut.bounds;
myKind = Type.K_UNION;
myChildren = new int[utTypes.size()];
for (int i = 0; i != utTypes.size(); ++i) {
myChildren[i] = resolveAsType(utTypes.get(i), context, states,
roots, nominal, unconstrained);
}
myDeterministic = false;
} else if (type instanceof SyntacticType.Intersection) {
internalFailure("intersection types not supported yet", context,
type);
return 0; // dead-code
} else if (type instanceof SyntacticType.Reference) {
SyntacticType.Reference ut = (SyntacticType.Reference) type;
myKind = Type.K_REFERENCE;
myChildren = new int[1];
myChildren[0] = resolveAsType(ut.element, context, states, roots,
nominal, unconstrained);
} else {
SyntacticType.FunctionOrMethod ut = (SyntacticType.FunctionOrMethod) type;
ArrayList<SyntacticType> utParamTypes = ut.paramTypes;
int start = 0;
if (ut instanceof SyntacticType.Method) {
myKind = Type.K_METHOD;
} else {
myKind = Type.K_FUNCTION;
}
myChildren = new int[start + 2 + utParamTypes.size()];
myChildren[start++] = resolveAsType(ut.ret, context, states, roots,
nominal, unconstrained);
if (ut.throwType == null) {
// this case indicates the user did not provide a throws clause.
myChildren[start++] = resolveAsType(new SyntacticType.Void(),
context, states, roots, nominal, unconstrained);
} else {
myChildren[start++] = resolveAsType(ut.throwType, context,
states, roots, nominal, unconstrained);
}
for (SyntacticType pt : utParamTypes) {
myChildren[start++] = resolveAsType(pt, context, states, roots,
nominal, unconstrained);
}
}
states.set(myIndex, new Automaton.State(myKind, myData,
myDeterministic, myChildren));
return myIndex;
}
private int resolveAsType(NameID key, ArrayList<Automaton.State> states,
HashMap<NameID, Integer> roots, boolean unconstrained)
throws IOException, ResolveError {
// First, check the various caches we have
Integer root = roots.get(key);
if (root != null) {
return root;
}
// check whether this type is external or not
WhileyFile wf = builder.getSourceFile(key.module());
if (wf == null) {
// indicates a non-local key which we can resolve immediately
WyilFile mi = builder.getModule(key.module());
WyilFile.TypeDeclaration td = mi.type(key.name());
return append(td.type(), states);
}
WhileyFile.Type td = wf.typeDecl(key.name());
if (td == null) {
// FIXME: the following allows (in certain cases) constants to be
// interpreted as types. This should not be allowed and needs to be
// removed in the future. However, to do this requires some kind of
// unit/constant/enum type. See #315
Type t = resolveAsConstant(key).type();
if (t instanceof Type.Set) {
if (unconstrained) {
// crikey this is ugly
int myIndex = states.size();
int kind = Type.leafKind(Type.T_VOID);
Object data = null;
states.add(new Automaton.State(kind, data, true,
Automaton.NOCHILDREN));
return myIndex;
}
Type.Set ts = (Type.Set) t;
return append(ts.element(), states);
} else {
throw new ResolveError("type not found: " + key);
}
}
// following is needed to terminate any recursion
roots.put(key, states.size());
SyntacticType type = td.pattern.toSyntacticType();
// now, expand the given type fully
if (unconstrained && td.invariant != null) {
int myIndex = states.size();
int kind = Type.leafKind(Type.T_VOID);
Object data = null;
states.add(new Automaton.State(kind, data, true,
Automaton.NOCHILDREN));
return myIndex;
} else if (type instanceof Type.Leaf) {
// FIXME: I believe this code is now redundant, and should be
// removed or updated. The problem is that SyntacticType no longer
// extends Type.
int myIndex = states.size();
int kind = Type.leafKind((Type.Leaf) type);
Object data = Type.leafData((Type.Leaf) type);
states.add(new Automaton.State(kind, data, true,
Automaton.NOCHILDREN));
return myIndex;
} else {
return resolveAsType(type, td, states, roots, false, unconstrained);
}
// TODO: performance can be improved here, but actually assigning the
// constructed type into a cache of previously expanded types cache.
// This is challenging, in the case that the type may not be complete at
// this point. In particular, if it contains any back-links above this
// index there could be an issue.
}
private int resolveAsType(SyntacticType.Primitive t, Context context,
ArrayList<Automaton.State> states) {
int myIndex = states.size();
int kind;
if (t instanceof SyntacticType.Any) {
kind = Type.K_ANY;
} else if (t instanceof SyntacticType.Void) {
kind = Type.K_VOID;
} else if (t instanceof SyntacticType.Null) {
kind = Type.K_NULL;
} else if (t instanceof SyntacticType.Bool) {
kind = Type.K_BOOL;
} else if (t instanceof SyntacticType.Byte) {
kind = Type.K_BYTE;
} else if (t instanceof SyntacticType.Char) {
kind = Type.K_CHAR;
} else if (t instanceof SyntacticType.Int) {
kind = Type.K_INT;
} else if (t instanceof SyntacticType.Real) {
kind = Type.K_RATIONAL;
} else if (t instanceof SyntacticType.Strung) {
kind = Type.K_STRING;
} else {
internalFailure("unrecognised type encountered ("
+ t.getClass().getName() + ")", context, t);
return 0; // dead-code
}
states.add(new Automaton.State(kind, null, true, Automaton.NOCHILDREN));
return myIndex;
}
private static int append(Type type, ArrayList<Automaton.State> states) {
int myIndex = states.size();
Automaton automaton = Type.destruct(type);
Automaton.State[] tStates = automaton.states;
int[] rmap = new int[tStates.length];
for (int i = 0, j = myIndex; i != rmap.length; ++i, ++j) {
rmap[i] = j;
}
for (Automaton.State state : tStates) {
states.add(Automata.remap(state, rmap));
}
return myIndex;
}
// ResolveAsConstant
/**
* <p>
* Resolve a given name as a constant value. This is a global problem, since
* a constant declaration in one source file may refer to constants declared
* in other compilation units. This function will actually evaluate constant
* expressions (e.g. "1+2") to produce actual constant vales.
* </p>
*
* <p>
* Constant declarations form a global graph spanning multiple compilation
* units. In resolving a given constant, this function must traverse those
* portions of the graph which make up the constant. Constants are not
* permitted to be declared recursively (i.e. in terms of themselves) and
* this function will report an error is such a recursive cycle is detected
* in the constant graph.
* </p>
*
* @param nid
* Fully qualified name identifier of constant to resolve
* @return Constant value representing named constant
* @throws IOException
*/
public Constant resolveAsConstant(NameID nid) throws IOException, ResolveError {
return resolveAsConstant(nid, new HashSet<NameID>());
}
/**
* <p>
* Resolve a given <i>constant expression</i> as a constant value. A
* constant expression is one which refers only to known and visible
* constant values, rather than e.g. local variables. Constant expressions
* may still use operators (e.g. "1+2", or "1+c" where c is a declared
* constant).
* </p>
*
* <p>
* Constant expressions used in a few places in Whiley. In particular, the
* cases of a <code>switch</code> statement must be defined using constant
* expressions.
* </p>
*
* @param e
* @param context
* @return
*/
public Constant resolveAsConstant(Expr e, Context context) {
e = propagate(e, new Environment(), context);
return resolveAsConstant(e, context, new HashSet<NameID>());
}
private Constant resolveAsConstant(NameID key, HashSet<NameID> visited)
throws IOException, ResolveError {
Constant result = constantCache.get(key);
if (result != null) {
return result;
} else if (visited.contains(key)) {
throw new ResolveError("cyclic constant definition encountered ("
+ key + " -> " + key + ")");
} else {
visited.add(key);
}
WhileyFile wf = builder.getSourceFile(key.module());
if (wf != null) {
WhileyFile.Declaration decl = wf.declaration(key.name());
if (decl instanceof WhileyFile.Constant) {
WhileyFile.Constant cd = (WhileyFile.Constant) decl;
if (cd.resolvedValue == null) {
cd.constant = propagate(cd.constant, new Environment(), cd);
cd.resolvedValue = resolveAsConstant(cd.constant, cd,
visited);
}
result = cd.resolvedValue;
} else {
throw new ResolveError("unable to find constant " + key);
}
} else {
WyilFile module = builder.getModule(key.module());
WyilFile.ConstantDeclaration cd = module.constant(key.name());
if (cd != null) {
result = cd.constant();
} else {
throw new ResolveError("unable to find constant " + key);
}
}
constantCache.put(key, result);
return result;
}
private Constant resolveAsConstant(Expr expr, Context context,
HashSet<NameID> visited) {
try {
if (expr instanceof Expr.Constant) {
Expr.Constant c = (Expr.Constant) expr;
return c.value;
} else if (expr instanceof Expr.ConstantAccess) {
Expr.ConstantAccess c = (Expr.ConstantAccess) expr;
ArrayList<String> qualifications = new ArrayList<String>();
if (c.qualification != null) {
for (String n : c.qualification) {
qualifications.add(n);
}
}
qualifications.add(c.name);
try {
NameID nid = resolveAsName(qualifications, context);
return resolveAsConstant(nid, visited);
} catch (ResolveError e) {
syntaxError(errorMessage(UNKNOWN_VARIABLE), context, expr);
return null;
}
} else if (expr instanceof Expr.BinOp) {
Expr.BinOp bop = (Expr.BinOp) expr;
Constant lhs = resolveAsConstant(bop.lhs, context, visited);
Constant rhs = resolveAsConstant(bop.rhs, context, visited);
return evaluate(bop, lhs, rhs, context);
} else if (expr instanceof Expr.UnOp) {
Expr.UnOp uop = (Expr.UnOp) expr;
Constant lhs = resolveAsConstant(uop.mhs, context, visited);
return evaluate(uop, lhs, context);
} else if (expr instanceof Expr.Set) {
Expr.Set nop = (Expr.Set) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr arg : nop.arguments) {
values.add(resolveAsConstant(arg, context, visited));
}
return Constant.V_SET(values);
} else if (expr instanceof Expr.List) {
Expr.List nop = (Expr.List) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr arg : nop.arguments) {
values.add(resolveAsConstant(arg, context, visited));
}
return Constant.V_LIST(values);
} else if (expr instanceof Expr.Record) {
Expr.Record rg = (Expr.Record) expr;
HashMap<String, Constant> values = new HashMap<String, Constant>();
for (Map.Entry<String, Expr> e : rg.fields.entrySet()) {
Constant v = resolveAsConstant(e.getValue(), context,
visited);
if (v == null) {
return null;
}
values.put(e.getKey(), v);
}
return Constant.V_RECORD(values);
} else if (expr instanceof Expr.Tuple) {
Expr.Tuple rg = (Expr.Tuple) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr e : rg.fields) {
Constant v = resolveAsConstant(e, context, visited);
if (v == null) {
return null;
}
values.add(v);
}
return Constant.V_TUPLE(values);
} else if (expr instanceof Expr.Map) {
Expr.Map rg = (Expr.Map) expr;
HashSet<Pair<Constant, Constant>> values = new HashSet<Pair<Constant, Constant>>();
for (Pair<Expr, Expr> e : rg.pairs) {
Constant key = resolveAsConstant(e.first(), context,
visited);
Constant value = resolveAsConstant(e.second(), context,
visited);
if (key == null || value == null) {
return null;
}
values.add(new Pair<Constant, Constant>(key, value));
}
return Constant.V_MAP(values);
} else if (expr instanceof Expr.FunctionOrMethod) {
// TODO: add support for proper lambdas
Expr.FunctionOrMethod f = (Expr.FunctionOrMethod) expr;
return Constant.V_LAMBDA(f.nid, f.type.raw());
}
} catch (SyntaxError.InternalFailure e) {
throw e;
} catch (Throwable e) {
internalFailure(e.getMessage(), context, expr, e);
}
internalFailure("unknown constant expression: "
+ expr.getClass().getName(), context, expr);
return null; // deadcode
}
/**
* Determine whether a name is visible in a given context. This effectively
* corresponds to checking whether or not the already name exists in the
* given context; or, a public or protected named is imported from another
* file.
*
* @param nid
* Name to check modifiers of
* @param context
* Context in which we are trying to access named item
*
* @return True if given context permitted to access name
* @throws IOException
*/
public boolean isNameVisible(NameID nid, Context context) throws IOException {
// Any element in the same file is automatically visible
if (nid.module().equals(context.file().module)) {
return true;
} else {
return hasModifier(nid, context, Modifier.PUBLIC)
|| hasModifier(nid, context, Modifier.PROTECTED);
}
}
/**
* Determine whether a named type is fully visible in a given context. This
* effectively corresponds to checking whether or not the already type
* exists in the given context; or, a public type is imported from another
* file.
*
* @param nid
* Name to check modifiers of
* @param context
* Context in which we are trying to access named item
*
* @return True if given context permitted to access name
* @throws IOException
*/
public boolean isTypeVisible(NameID nid, Context context) throws IOException {
// Any element in the same file is automatically visible
if (nid.module().equals(context.file().module)) {
return true;
} else {
return hasModifier(nid, context, Modifier.PUBLIC);
}
}
/**
* Determine whether a named item has a modifier matching one of a given
* list. This is particularly useful for checking visibility (e.g. public,
* private, etc) of named items.
*
* @param nid
* Name to check modifiers of
* @param context
* Context in which we are trying to access named item
* @param modifiers
*
* @return True if given context permitted to access name
* @throws IOException
*/
public boolean hasModifier(NameID nid, Context context, Modifier modifier)
throws IOException {
Path.ID mid = nid.module();
// Attempt to access source file first.
WhileyFile wf = builder.getSourceFile(mid);
if (wf != null) {
// Source file location, so check visible of element.
WhileyFile.NamedDeclaration nd = wf.declaration(nid.name());
return nd != null && nd.hasModifier(modifier);
} else {
// Source file not being compiled, therefore attempt to access wyil
// file directly.
// we have to do the following basically because we don't load
// modifiers properly out of jvm class files (at the moment).
// return false;
WyilFile w = builder.getModule(mid);
List<WyilFile.Declaration> declarations = w.declarations();
for (int i = 0; i != declarations.size(); ++i) {
WyilFile.Declaration d = declarations.get(i);
if (d instanceof WyilFile.NamedDeclaration) {
WyilFile.NamedDeclaration nd = (WyilFile.NamedDeclaration) d;
return nd != null && nd.hasModifier(modifier);
}
}
return false;
}
}
// Constant Evaluation
/**
* Evaluate a given unary operator on a given input value.
*
* @param operator
* Unary operator to evaluate
* @param operand
* Operand to apply operator on
* @param context
* Context in which to apply operator (useful for error
* reporting)
* @return
*/
private Constant evaluate(Expr.UnOp operator, Constant operand,
Context context) {
switch (operator.op) {
case NOT:
if (operand instanceof Constant.Bool) {
Constant.Bool b = (Constant.Bool) operand;
return Constant.V_BOOL(!b.value);
}
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context,
operator);
break;
case NEG:
if (operand instanceof Constant.Integer) {
Constant.Integer b = (Constant.Integer) operand;
return Constant.V_INTEGER(b.value.negate());
} else if (operand instanceof Constant.Decimal) {
Constant.Decimal b = (Constant.Decimal) operand;
return Constant.V_DECIMAL(b.value.negate());
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION), context,
operator);
break;
case INVERT:
if (operand instanceof Constant.Byte) {
Constant.Byte b = (Constant.Byte) operand;
return Constant.V_BYTE((byte) ~b.value);
}
break;
}
syntaxError(errorMessage(INVALID_UNARY_EXPRESSION), context, operator);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant v1, Constant v2,
Context context) {
Type v1_type = v1.type();
Type v2_type = v2.type();
Type lub = Type.Union(v1_type, v2_type);
// FIXME: there are bugs here related to coercions.
if (Type.isSubtype(Type.T_BOOL, lub)) {
return evaluateBoolean(bop, (Constant.Bool) v1, (Constant.Bool) v2,
context);
} else if (Type.isSubtype(Type.T_INT, lub)) {
return evaluate(bop, (Constant.Integer) v1, (Constant.Integer) v2,
context);
} else if (Type.isImplicitCoerciveSubtype(Type.T_REAL, v1_type)
&& Type.isImplicitCoerciveSubtype(Type.T_REAL, v1_type)) {
if (v1 instanceof Constant.Integer) {
Constant.Integer i1 = (Constant.Integer) v1;
v1 = Constant.V_DECIMAL(new BigDecimal(i1.value));
} else if (v2 instanceof Constant.Integer) {
Constant.Integer i2 = (Constant.Integer) v2;
v2 = Constant.V_DECIMAL(new BigDecimal(i2.value));
}
return evaluate(bop, (Constant.Decimal) v1, (Constant.Decimal) v2,
context);
} else if (Type.isSubtype(Type.T_LIST_ANY, lub)) {
return evaluate(bop, (Constant.List) v1, (Constant.List) v2,
context);
} else if (Type.isSubtype(Type.T_SET_ANY, lub)) {
return evaluate(bop, (Constant.Set) v1, (Constant.Set) v2, context);
}
syntaxError(errorMessage(INVALID_BINARY_EXPRESSION), context, bop);
return null;
}
private Constant evaluateBoolean(Expr.BinOp bop, Constant.Bool v1,
Constant.Bool v2, Context context) {
switch (bop.op) {
case AND:
return Constant.V_BOOL(v1.value & v2.value);
case OR:
return Constant.V_BOOL(v1.value | v2.value);
case XOR:
return Constant.V_BOOL(v1.value ^ v2.value);
}
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Integer v1,
Constant.Integer v2, Context context) {
switch (bop.op) {
case ADD:
return Constant.V_INTEGER(v1.value.add(v2.value));
case SUB:
return Constant.V_INTEGER(v1.value.subtract(v2.value));
case MUL:
return Constant.V_INTEGER(v1.value.multiply(v2.value));
case DIV:
return Constant.V_INTEGER(v1.value.divide(v2.value));
case REM:
return Constant.V_INTEGER(v1.value.remainder(v2.value));
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION), context, bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Decimal v1,
Constant.Decimal v2, Context context) {
switch (bop.op) {
case ADD:
return Constant.V_DECIMAL(v1.value.add(v2.value));
case SUB:
return Constant.V_DECIMAL(v1.value.subtract(v2.value));
case MUL:
return Constant.V_DECIMAL(v1.value.multiply(v2.value));
case DIV:
return Constant.V_DECIMAL(v1.value.divide(v2.value));
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION), context, bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.List v1,
Constant.List v2, Context context) {
switch (bop.op) {
case ADD:
ArrayList<Constant> vals = new ArrayList<Constant>(v1.values);
vals.addAll(v2.values);
return Constant.V_LIST(vals);
}
syntaxError(errorMessage(INVALID_LIST_EXPRESSION), context, bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Set v1, Constant.Set v2,
Context context) {
switch (bop.op) {
case UNION: {
HashSet<Constant> vals = new HashSet<Constant>(v1.values);
vals.addAll(v2.values);
return Constant.V_SET(vals);
}
case INTERSECTION: {
HashSet<Constant> vals = new HashSet<Constant>();
for (Constant v : v1.values) {
if (v2.values.contains(v)) {
vals.add(v);
}
}
return Constant.V_SET(vals);
}
case SUB: {
HashSet<Constant> vals = new HashSet<Constant>();
for (Constant v : v1.values) {
if (!v2.values.contains(v)) {
vals.add(v);
}
}
return Constant.V_SET(vals);
}
}
syntaxError(errorMessage(INVALID_SET_EXPRESSION), context, bop);
return null;
}
// expandAsType
public Nominal.EffectiveSet expandAsEffectiveSet(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveSet) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveSet)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveSet) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.EffectiveList expandAsEffectiveList(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveList) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveList)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveList) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.EffectiveCollection expandAsEffectiveCollection(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveCollection) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveCollection)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveCollection) Nominal
.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.EffectiveIndexible expandAsEffectiveMap(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveIndexible) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveIndexible)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveIndexible) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.EffectiveMap expandAsEffectiveDictionary(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveMap) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveMap)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveMap) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.EffectiveRecord expandAsEffectiveRecord(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.Record) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.Record)) {
nominal = (Type) raw; // discard nominal information
}
return (Nominal.Record) Nominal.construct(nominal, raw);
} else if (raw instanceof Type.UnionOfRecords) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.UnionOfRecords)) {
nominal = (Type) raw; // discard nominal information
}
return (Nominal.UnionOfRecords) Nominal.construct(nominal, raw);
}
{
return null;
}
}
public Nominal.EffectiveTuple expandAsEffectiveTuple(Nominal lhs)
throws IOException, ResolveError {
Type raw = lhs.raw();
if (raw instanceof Type.EffectiveTuple) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.EffectiveTuple)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveTuple) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.Reference expandAsReference(Nominal lhs) throws IOException, ResolveError {
Type.Reference raw = Type.effectiveReference(lhs.raw());
if (raw != null) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.Reference)) {
nominal = raw; // discard nominal information
}
return (Nominal.Reference) Nominal.construct(nominal, raw);
} else {
return null;
}
}
public Nominal.FunctionOrMethod expandAsFunctionOrMethod(Nominal lhs)
throws IOException, ResolveError {
Type.FunctionOrMethod raw = Type.effectiveFunctionOrMethod(lhs.raw());
if (raw != null) {
Type nominal = expandOneLevel(lhs.nominal());
if (!(nominal instanceof Type.FunctionOrMethod)) {
nominal = raw; // discard nominal information
}
return (Nominal.FunctionOrMethod) Nominal.construct(nominal, raw);
} else {
return null;
}
}
private Type expandOneLevel(Type type) throws IOException, ResolveError {
if (type instanceof Type.Nominal) {
Type.Nominal nt = (Type.Nominal) type;
NameID nid = nt.name();
Path.ID mid = nid.module();
WhileyFile wf = builder.getSourceFile(mid);
Type r = null;
if (wf != null) {
WhileyFile.Declaration decl = wf.declaration(nid.name());
if (decl instanceof WhileyFile.Type) {
WhileyFile.Type td = (WhileyFile.Type) decl;
r = resolveAsType(td.pattern.toSyntacticType(), td)
.nominal();
}
} else {
WyilFile m = builder.getModule(mid);
WyilFile.TypeDeclaration td = m.type(nid.name());
if (td != null) {
r = td.type();
}
}
if (r == null) {
throw new ResolveError("unable to locate " + nid);
}
return expandOneLevel(r);
} else if (type instanceof Type.Leaf || type instanceof Type.Reference
|| type instanceof Type.Tuple || type instanceof Type.Set
|| type instanceof Type.List || type instanceof Type.Map
|| type instanceof Type.Record
|| type instanceof Type.FunctionOrMethod
|| type instanceof Type.Negation) {
return type;
} else {
Type.Union ut = (Type.Union) type;
ArrayList<Type> bounds = new ArrayList<Type>();
for (Type b : ut.bounds()) {
bounds.add(expandOneLevel(b));
}
return Type.Union(bounds);
}
}
// Misc
// Check t1 :> t2
private void checkIsSubtype(Nominal t1, Nominal t2, SyntacticElement elem) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.raw())) {
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.nominal()),
filename, elem);
}
}
private void checkIsSubtype(Nominal t1, Expr t2) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.result()
.nominal()), filename, t2);
}
}
private void checkIsSubtype(Type t1, Expr t2) {
if (!Type.isImplicitCoerciveSubtype(t1, t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(errorMessage(SUBTYPE_ERROR, t1, t2.result().nominal()),
filename, t2);
}
}
// Check t1 :> t2
private void checkIsSubtype(Nominal t1, Nominal t2, SyntacticElement elem,
Context context) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.raw())) {
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.nominal()),
context, elem);
}
}
private void checkIsSubtype(Nominal t1, Expr t2, Context context) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.result()
.nominal()), context, t2);
}
}
private void checkIsSubtype(Type t1, Expr t2, Context context) {
if (!Type.isImplicitCoerciveSubtype(t1, t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(errorMessage(SUBTYPE_ERROR, t1, t2.result().nominal()),
context, t2);
}
}
// Environment Class
/**
* <p>
* Responsible for mapping source-level variables to their declared and
* actual types, at any given program point. Since the flow-type checker
* uses a flow-sensitive approach to type checking, then the typing
* environment will change as we move through the statements of a function
* or method.
* </p>
*
* <p>
* This class is implemented in a functional style to minimise possible
* problems related to aliasing (which have been a problem in the past). To
* improve performance, reference counting is to ensure that cloning the
* underling map is only performed when actually necessary.
* </p>
*
* @author David J. Pearce
*
*/
private static final class Environment {
/**
* The mapping of variables to their declared type.
*/
private final HashMap<String, Nominal> declaredTypes;
/**
* The mapping of variables to their current type.
*/
private final HashMap<String, Nominal> currentTypes;
/**
* The reference count, which indicate how many references to this
* environment there are. When there is only one reference, then the put
* and putAll operations will perform an "inplace" update (i.e. without
* cloning the underlying collection).
*/
private int count; // refCount
/**
* Construct an empty environment. Initially the reference count is 1.
*/
public Environment() {
count = 1;
currentTypes = new HashMap<String, Nominal>();
declaredTypes = new HashMap<String, Nominal>();
}
/**
* Construct a fresh environment as a copy of another map. Initially the
* reference count is 1.
*/
private Environment(Environment environment) {
count = 1;
this.currentTypes = (HashMap<String, Nominal>) environment.currentTypes.clone();
this.declaredTypes = (HashMap<String, Nominal>) environment.declaredTypes.clone();
}
/**
* Get the type associated with a given variable at the current program
* point, or null if that variable is not declared.
*
* @param variable
* Variable to return type for.
* @return
*/
public Nominal getCurrentType(String variable) {
return currentTypes.get(variable);
}
/**
* Get the declared type of a given variable, or null if that variable
* is not declared.
*
* @param variable
* Variable to return type for.
* @return
*/
public Nominal getDeclaredType(String variable) {
return declaredTypes.get(variable);
}
/**
* Check whether a given variable is declared within this environment.
*
* @param variable
* @return
*/
public boolean containsKey(String variable) {
return declaredTypes.containsKey(variable);
}
/**
* Return the set of declared variables in this environment (a.k.a the
* domain).
*
* @return
*/
public Set<String> keySet() {
return declaredTypes.keySet();
}
/**
* Declare a new variable with a given type. In the case that this
* environment has a reference count of 1, then an "in place" update is
* performed. Otherwise, a fresh copy of this environment is returned
* with the given variable associated with the given type, whilst this
* environment is unchanged.
*
* @param variable
* Name of variable to be declared with given type
* @param declared
* Declared type of the given variable
* @param initial
* Initial type of given variable
* @return An updated version of the environment which contains the new
* association.
*/
public Environment declare(String variable, Nominal declared, Nominal initial) {
if (declaredTypes.containsKey(variable)) {
throw new RuntimeException("Variable already declared - "
+ variable);
}
if (count == 1) {
declaredTypes.put(variable, declared);
currentTypes.put(variable, initial);
return this;
} else {
Environment nenv = new Environment(this);
nenv.declaredTypes.put(variable, declared);
nenv.currentTypes.put(variable, initial);
count
return nenv;
}
}
/**
* Update the current type of a given variable. If that variable already
* had a current type, then this is overwritten. In the case that this
* environment has a reference count of 1, then an "in place" update is
* performed. Otherwise, a fresh copy of this environment is returned
* with the given variable associated with the given type, whilst this
* environment is unchanged.
*
* @param variable
* Name of variable to be associated with given type
* @param type
* Type to associated with given variable
* @return An updated version of the environment which contains the new
* association.
*/
public Environment update(String variable, Nominal type) {
if (!declaredTypes.containsKey(variable)) {
throw new RuntimeException("Variable not declared - "
+ variable);
}
if (count == 1) {
currentTypes.put(variable, type);
return this;
} else {
Environment nenv = new Environment(this);
nenv.currentTypes.put(variable, type);
count
return nenv;
}
}
/**
* Remove a variable and any associated type from this environment. In
* the case that this environment has a reference count of 1, then an
* "in place" update is performed. Otherwise, a fresh copy of this
* environment is returned with the given variable and any association
* removed.
*
* @param variable
* Name of variable to be removed from the environment
* @return An updated version of the environment in which the given
* variable no longer exists.
*/
public Environment remove(String key) {
if (count == 1) {
currentTypes.remove(key);
return this;
} else {
Environment nenv = new Environment(this);
nenv.currentTypes.remove(key);
count
return nenv;
}
}
/**
* Merge a given environment with this environment to produce an
* environment representing their join. Only variables from a given set
* are included in the result, and all such variables are required to be
* declared in both environments. The type of each variable included is
* the union of its type in this environment and the other environment.
*
* @param declared
* The set of declared variables which should be included in
* the result. The intuition is that these are the variables
* which were declared in both environments before whatever
* updates were made.
* @param env
* The given environment to be merged with this environment.
* @return
*/
public final Environment merge(Set<String> declared, Environment env) {
// first, need to check for the special bottom value case.
if (this == BOTTOM) {
return env;
} else if (env == BOTTOM) {
return this;
}
// ok, not bottom so compute intersection.
this.free();
env.free();
Environment result = new Environment();
for (String variable : declared) {
Nominal lhs_t = this.getCurrentType(variable);
Nominal rhs_t = env.getCurrentType(variable);
result.declare(variable, this.getDeclaredType(variable),
Nominal.Union(lhs_t, rhs_t));
}
return result;
}
/**
* Create a fresh copy of this environment. In fact, this operation
* simply increments the reference count of this environment and returns
* it.
*/
public Environment clone() {
count++;
return this;
}
/**
* Decrease the reference count of this environment by one.
*/
public void free() {
--count;
}
public String toString() {
return currentTypes.toString();
}
public int hashCode() {
return currentTypes.hashCode();
}
public boolean equals(Object o) {
if (o instanceof Environment) {
Environment r = (Environment) o;
return currentTypes.equals(r.currentTypes);
}
return false;
}
}
private static final Environment BOTTOM = new Environment();
} |
package nars.inference;
import java.util.HashMap;
import nars.config.Parameters;
import nars.entity.BudgetValue;
import nars.entity.Concept;
import nars.control.DerivationContext;
import nars.entity.Sentence;
import nars.entity.Task;
import nars.entity.TruthValue;
import static nars.inference.TruthFunctions.comparison;
import static nars.inference.TruthFunctions.induction;
import static nars.inference.TruthFunctions.intersection;
import static nars.inference.TruthFunctions.negation;
import static nars.inference.TruthFunctions.reduceConjunction;
import static nars.inference.TruthFunctions.reduceConjunctionNeg;
import static nars.inference.TruthFunctions.reduceDisjunction;
import static nars.inference.TruthFunctions.union;
import nars.io.Symbols;
import nars.language.CompoundTerm;
import nars.language.Conjunction;
import nars.language.DifferenceExt;
import nars.language.DifferenceInt;
import nars.language.Disjunction;
import nars.language.Equivalence;
import nars.language.ImageExt;
import nars.language.ImageInt;
import nars.language.Implication;
import nars.language.Inheritance;
import nars.language.IntersectionExt;
import nars.language.IntersectionInt;
import nars.language.SetExt;
import nars.language.SetInt;
import nars.language.Similarity;
import nars.language.Statement;
import nars.language.Term;
import static nars.language.Terms.reduceComponents;
import nars.language.Variable;
import nars.language.Variables;
import static nars.inference.TruthFunctions.abduction;
import nars.language.Interval;
/**
* Compound term composition and decomposition rules, with two premises.
* <p>
* New compound terms are introduced only in forward inference, while
* decompositional rules are also used in backward inference
*/
public final class CompositionalRules {
/**
* {<S ==> M>, <P ==> M>} |- {<(S|P) ==> M>, <(S&P) ==> M>, <(S-P) ==>
* M>,
* <(P-S) ==> M>}
*
* @param taskSentence The first premise
* @param belief The second premise
* @param index The location of the shared term
* @param nal Reference to the memory
*/
static void composeCompound(final Statement taskContent, final Statement beliefContent, final int index, final DerivationContext nal) {
if ((!nal.getCurrentTask().sentence.isJudgment()) || (taskContent.getClass() != beliefContent.getClass())) {
return;
}
final Term componentT = taskContent.term[1 - index];
final Term componentB = beliefContent.term[1 - index];
final Term componentCommon = taskContent.term[index];
int order1 = taskContent.getTemporalOrder();
int order2 = beliefContent.getTemporalOrder();
int order = TemporalRules.composeOrder(order1, order2);
if (order == TemporalRules.ORDER_INVALID) {
return;
}
if ((componentT instanceof CompoundTerm) && ((CompoundTerm) componentT).containsAllTermsOf(componentB)) {
decomposeCompound((CompoundTerm) componentT, componentB, componentCommon, index, true, order, nal);
return;
} else if ((componentB instanceof CompoundTerm) && ((CompoundTerm) componentB).containsAllTermsOf(componentT)) {
decomposeCompound((CompoundTerm) componentB, componentT, componentCommon, index, false, order, nal);
return;
}
final TruthValue truthT = nal.getCurrentTask().sentence.truth;
final TruthValue truthB = nal.getCurrentBelief().truth;
final TruthValue truthOr = union(truthT, truthB);
final TruthValue truthAnd = intersection(truthT, truthB);
TruthValue truthDif = null;
Term termOr = null;
Term termAnd = null;
Term termDif = null;
if (index == 0) {
if (taskContent instanceof Inheritance) {
termOr = IntersectionInt.make(componentT, componentB);
termAnd = IntersectionExt.make(componentT, componentB);
if (truthB.isNegative()) {
if (!truthT.isNegative()) {
termDif = DifferenceExt.make(componentT, componentB);
truthDif = intersection(truthT, negation(truthB));
}
} else if (truthT.isNegative()) {
termDif = DifferenceExt.make(componentB, componentT);
truthDif = intersection(truthB, negation(truthT));
}
} else if (taskContent instanceof Implication) {
termOr = Disjunction.make(componentT, componentB);
termAnd = Conjunction.make(componentT, componentB);
}
processComposed(taskContent, componentCommon, termOr, order, truthOr, nal);
processComposed(taskContent, componentCommon, termAnd, order, truthAnd, nal);
processComposed(taskContent, componentCommon, termDif, order, truthDif, nal);
} else { // index == 1
if (taskContent instanceof Inheritance) {
termOr = IntersectionExt.make(componentT, componentB);
termAnd = IntersectionInt.make(componentT, componentB);
if (truthB.isNegative()) {
if (!truthT.isNegative()) {
termDif = DifferenceInt.make(componentT, componentB);
truthDif = intersection(truthT, negation(truthB));
}
} else if (truthT.isNegative()) {
termDif = DifferenceInt.make(componentB, componentT);
truthDif = intersection(truthB, negation(truthT));
}
} else if (taskContent instanceof Implication) {
termOr = Conjunction.make(componentT, componentB);
termAnd = Disjunction.make(componentT, componentB);
}
processComposed(taskContent, termOr, componentCommon, order, truthOr, nal);
processComposed(taskContent, termAnd, componentCommon, order, truthAnd, nal);
processComposed(taskContent, termDif, componentCommon, order, truthDif, nal);
}
}
/**
* Finish composing implication term
*
* @param premise1 Type of the contentInd
* @param subject Subject of contentInd
* @param predicate Predicate of contentInd
* @param truth TruthValue of the contentInd
* @param memory Reference to the memory
*/
private static void processComposed(final Statement statement, final Term subject, final Term predicate, final int order, final TruthValue truth, final DerivationContext nal) {
if ((subject == null) || (predicate == null)) {
return;
}
Term content = Statement.make(statement, subject, predicate, order);
if ((content == null) || statement == null || content.equals(statement) || content.equals(nal.getCurrentBelief().term)) {
return;
}
BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, false); //(allow overlap) but not needed here, isn't detachment, this one would be even problematic from control perspective because its composition
}
/**
* {<(S|P) ==> M>, <P ==> M>} |- <S ==> M>
*
* @param implication The implication term to be decomposed
* @param componentCommon The part of the implication to be removed
* @param term1 The other term in the contentInd
* @param index The location of the shared term: 0 for subject, 1 for
* predicate
* @param compoundTask Whether the implication comes from the task
* @param nal Reference to the memory
*/
private static void decomposeCompound(CompoundTerm compound, Term component, Term term1, int index, boolean compoundTask, int order, DerivationContext nal) {
if ((compound instanceof Statement) || (compound instanceof ImageExt) || (compound instanceof ImageInt)) {
return;
}
Term term2 = reduceComponents(compound, component, nal.mem());
if (term2 == null) {
return;
}
Task task = nal.getCurrentTask();
Sentence sentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
Statement oldContent = (Statement) task.getTerm();
TruthValue v1, v2;
if (compoundTask) {
v1 = sentence.truth;
v2 = belief.truth;
} else {
v1 = belief.truth;
v2 = sentence.truth;
}
TruthValue truth = null;
Term content;
if (index == 0) {
content = Statement.make(oldContent, term1, term2, order);
if (content == null) {
return;
}
if (oldContent instanceof Inheritance) {
if (compound instanceof IntersectionExt) {
truth = reduceConjunction(v1, v2);
} else if (compound instanceof IntersectionInt) {
truth = reduceDisjunction(v1, v2);
} else if ((compound instanceof SetInt) && (component instanceof SetInt)) {
truth = reduceConjunction(v1, v2);
} else if ((compound instanceof SetExt) && (component instanceof SetExt)) {
truth = reduceDisjunction(v1, v2);
} else if (compound instanceof DifferenceExt) {
if (compound.term[0].equals(component)) {
truth = reduceDisjunction(v2, v1);
} else {
truth = reduceConjunctionNeg(v1, v2);
}
}
} else if (oldContent instanceof Implication) {
if (compound instanceof Conjunction) {
truth = reduceConjunction(v1, v2);
} else if (compound instanceof Disjunction) {
truth = reduceDisjunction(v1, v2);
}
}
} else {
content = Statement.make(oldContent, term2, term1, order);
if (content == null) {
return;
}
if (oldContent instanceof Inheritance) {
if (compound instanceof IntersectionInt) {
truth = reduceConjunction(v1, v2);
} else if (compound instanceof IntersectionExt) {
truth = reduceDisjunction(v1, v2);
} else if ((compound instanceof SetExt) && (component instanceof SetExt)) {
truth = reduceConjunction(v1, v2);
} else if ((compound instanceof SetInt) && (component instanceof SetInt)) {
truth = reduceDisjunction(v1, v2);
} else if (compound instanceof DifferenceInt) {
if (compound.term[1].equals(component)) {
truth = reduceDisjunction(v2, v1);
} else {
truth = reduceConjunctionNeg(v1, v2);
}
}
} else if (oldContent instanceof Implication) {
if (compound instanceof Disjunction) {
truth = reduceConjunction(v1, v2);
} else if (compound instanceof Conjunction) {
truth = reduceDisjunction(v1, v2);
}
}
}
if (truth != null) {
BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, true); //(allow overlap), a form of detachment
}
}
/**
* {(||, S, P), P} |- S {(&&, S, P), P} |- S
*
* @param implication The implication term to be decomposed
* @param componentCommon The part of the implication to be removed
* @param compoundTask Whether the implication comes from the task
* @param nal Reference to the memory
*/
static void decomposeStatement(CompoundTerm compound, Term component, boolean compoundTask, int index, DerivationContext nal) {
boolean isTemporalConjunction = (compound instanceof Conjunction) && !((Conjunction) compound).isSpatial;
if (isTemporalConjunction && (compound.getTemporalOrder() == TemporalRules.ORDER_FORWARD) && (index != 0)) {
return;
}
if(isTemporalConjunction && (compound.getTemporalOrder() == TemporalRules.ORDER_FORWARD)) {
if(!nal.getCurrentTask().sentence.isEternal() && compound.term[index + 1] instanceof Interval) {
long shift_occurrence = ((Interval)compound.term[1]).getTime(nal.memory);
nal.getTheNewStamp().setOccurrenceTime(nal.getCurrentTask().sentence.getOccurenceTime() + shift_occurrence);
}
}
Task task = nal.getCurrentTask();
Sentence taskSentence = task.sentence;
Sentence belief = nal.getCurrentBelief();
Term content = reduceComponents(compound, component, nal.mem());
if (content == null) {
return;
}
TruthValue truth = null;
BudgetValue budget;
if (taskSentence.isQuestion() || taskSentence.isQuest()) {
budget = BudgetFunctions.compoundBackward(content, nal);
nal.doublePremiseTask(content, truth, budget, false, false);
// special inference to answer conjunctive questions with query variables
if (taskSentence.term.hasVarQuery()) {
Concept contentConcept = nal.mem().concept(content);
if (contentConcept == null) {
return;
}
Sentence contentBelief = contentConcept.getBelief(nal, task);
if (contentBelief == null) {
return;
}
Task contentTask = new Task(contentBelief, task.budget, false);
nal.setCurrentTask(contentTask);
Term conj = Conjunction.make(component, content);
truth = intersection(contentBelief.truth, belief.truth);
budget = BudgetFunctions.compoundForward(truth, conj, nal);
nal.doublePremiseTask(conj, truth, budget, false, false);
}
} else {
TruthValue v1, v2;
if (compoundTask) {
v1 = taskSentence.truth;
v2 = belief.truth;
} else {
v1 = belief.truth;
v2 = taskSentence.truth;
}
if (compound instanceof Conjunction) {
if (taskSentence.isGoal()) {
if (compoundTask) {
truth = intersection(v1, v2);
} else {
return;
}
} else { // isJudgment
truth = reduceConjunction(v1, v2);
}
} else if (compound instanceof Disjunction) {
if (taskSentence.isGoal()) {
if (compoundTask) {
truth = reduceConjunction(v2, v1);
} else {
return;
}
} else { // isJudgment
truth = reduceDisjunction(v1, v2);
}
} else {
return;
}
budget = BudgetFunctions.compoundForward(truth, content, nal);
}
nal.doublePremiseTask(content, truth, budget, false, false);
}
/**
* Introduce a dependent variable in an outer-layer conjunction {<S --> P1>,
* <S --> P2>} |- (&&, <#x --> P1>, <#x --> P2>)
*
* @param taskContent The first premise <M --> S>
* @param beliefContent The second premise <M --> P>
* @param index The location of the shared term: 0 for subject, 1 for
* predicate
* @param nal Reference to the memory
*/
public static void introVarOuter(final Statement taskContent, final Statement beliefContent, final int index, final DerivationContext nal) {
if (!(taskContent instanceof Inheritance)) {
return;
}
Variable varInd1 = new Variable("$varInd1");
Variable varInd2 = new Variable("$varInd2");
Term term11dependent=null, term12dependent=null, term21dependent=null, term22dependent=null;
Term term11, term12, term21, term22, commonTerm = null;
HashMap<Term, Term> subs = new HashMap<>();
if (index == 0) {
term11 = varInd1;
term21 = varInd1;
term12 = taskContent.getPredicate();
term22 = beliefContent.getPredicate();
term12dependent=term12;
term22dependent=term22;
if (term12 instanceof ImageExt) {
if ((/*(ImageExt)*/term12).containsTermRecursively(term22)) {
commonTerm = term22;
}
if(commonTerm == null && term12 instanceof ImageExt) {
commonTerm = ((ImageExt) term12).getTheOtherComponent();
if(!(term22.containsTermRecursively(commonTerm))) {
commonTerm=null;
}
if (term22 instanceof ImageExt && ((commonTerm == null) || !(term22).containsTermRecursively(commonTerm))) {
commonTerm = ((ImageExt) term22).getTheOtherComponent();
if ((commonTerm == null) || !(term12).containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
if (commonTerm != null) {
subs.put(commonTerm, varInd2);
term12 = ((CompoundTerm) term12).applySubstitute(subs);
if(!(term22 instanceof CompoundTerm)) {
term22 = varInd2;
} else {
term22 = ((CompoundTerm) term22).applySubstitute(subs);
}
}
}
if (commonTerm==null && term22 instanceof ImageExt) {
if ((/*(ImageExt)*/term22).containsTermRecursively(term12)) {
commonTerm = term12;
}
if(commonTerm == null && term22 instanceof ImageExt) {
commonTerm = ((ImageExt) term22).getTheOtherComponent();
if(!(term12.containsTermRecursively(commonTerm))) {
commonTerm=null;
}
if (term12 instanceof ImageExt && ((commonTerm == null) || !(term12).containsTermRecursively(commonTerm))) {
commonTerm = ((ImageExt) term12).getTheOtherComponent();
if ((commonTerm == null) || !(term22).containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
if (commonTerm != null) {
subs.put(commonTerm, varInd2);
term22 = ((CompoundTerm) term22).applySubstitute(subs);
if(!(term12 instanceof CompoundTerm)) {
term12 = varInd2;
} else {
term12 = ((CompoundTerm) term12).applySubstitute(subs);
}
}
}
} else {
term11 = taskContent.getSubject();
term21 = beliefContent.getSubject();
term12 = varInd1;
term22 = varInd1;
term11dependent=term11;
term21dependent=term21;
if (term21 instanceof ImageInt) {
if ((/*(ImageInt)*/term21).containsTermRecursively(term11)) {
commonTerm = term11;
}
if(term11 instanceof ImageInt && commonTerm == null && term21 instanceof ImageInt) {
commonTerm = ((ImageInt) term11).getTheOtherComponent();
if(!(term21.containsTermRecursively(commonTerm))) {
commonTerm=null;
}
if ((commonTerm == null) || !(term21).containsTermRecursively(commonTerm)) {
commonTerm = ((ImageInt) term21).getTheOtherComponent();
if ((commonTerm == null) || !(term11).containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
if (commonTerm != null) {
subs.put(commonTerm, varInd2);
term21 = ((CompoundTerm) term21).applySubstitute(subs);
if(!(term11 instanceof CompoundTerm)) {
term11 = varInd2;
} else {
term11 = ((CompoundTerm) term11).applySubstitute(subs);
}
}
}
if (commonTerm==null && term11 instanceof ImageInt) {
if ((/*(ImageInt)*/term11).containsTermRecursively(term21)) {
commonTerm = term21;
}
if(term21 instanceof ImageInt && commonTerm == null && term11 instanceof ImageInt) {
commonTerm = ((ImageInt) term21).getTheOtherComponent();
if(!(term11.containsTermRecursively(commonTerm))) {
commonTerm=null;
}
if ((commonTerm == null) || !(term11).containsTermRecursively(commonTerm)) {
commonTerm = ((ImageInt) term11).getTheOtherComponent();
if ((commonTerm == null) || !(term21).containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
if (commonTerm != null) {
subs.put(commonTerm, varInd2);
term11 = ((CompoundTerm) term11).applySubstitute(subs);
if(!(term21 instanceof CompoundTerm)) {
term21 = varInd2;
} else {
term21 = ((CompoundTerm) term21).applySubstitute(subs);
}
}
}
}
Statement state1 = Inheritance.make(term11, term12);
Statement state2 = Inheritance.make(term21, term22);
Term content = Implication.make(state1, state2);
if (content == null) {
return;
}
TruthValue truthT = nal.getCurrentTask().sentence.truth;
TruthValue truthB = nal.getCurrentBelief().truth;
if ((truthT == null) || (truthB == null)) {
if(Parameters.DEBUG) {
System.out.println("ERROR: Belief with null truth value. (introVarOuter)");
}
return;
}
TruthValue truth = induction(truthT, truthB);
BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, false);
content = Implication.make(state2, state1);
truth = induction(truthB, truthT);
budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, false);
content = Equivalence.make(state1, state2);
truth = comparison(truthT, truthB);
budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, false);
Variable varDep = new Variable("#varDep");
if (index == 0) {
state1 = Inheritance.make(varDep, term12dependent);
state2 = Inheritance.make(varDep, term22dependent);
} else {
state1 = Inheritance.make(term11dependent, varDep);
state2 = Inheritance.make(term21dependent, varDep);
}
if ((state1==null) || (state2 == null))
return;
content = Conjunction.make(state1, state2);
truth = intersection(truthT, truthB);
budget = BudgetFunctions.compoundForward(truth, content, nal);
nal.doublePremiseTask(content, truth, budget, false, false);
}
/**
* {<M --> S>, <C ==> <M --> P>>} |- <(&&, <#x --> S>, C) ==> <#x --> P>>
* {<M --> S>, (&&, C, <M --> P>)} |- (&&, C, <<#x --> S> ==> <#x --> P>>)
*
* @param taskContent The first premise directly used in internal induction,
* <M --> S>
* @param beliefContent The componentCommon to be used as a premise in
* internal induction, <M --> P>
* @param oldCompound The whole contentInd of the first premise, Implication
* or Conjunction
* @param nal Reference to the memory
*/
static boolean introVarInner(Statement premise1, Statement premise2, CompoundTerm oldCompound, DerivationContext nal) {
Task task = nal.getCurrentTask();
Sentence taskSentence = task.sentence;
if (!taskSentence.isJudgment() || (premise1.getClass() != premise2.getClass()) || oldCompound.containsTerm(premise1)) {
return false;
}
Term subject1 = premise1.getSubject();
Term subject2 = premise2.getSubject();
Term predicate1 = premise1.getPredicate();
Term predicate2 = premise2.getPredicate();
Term commonTerm1, commonTerm2;
if (subject1.equals(subject2)) {
commonTerm1 = subject1;
commonTerm2 = secondCommonTerm(predicate1, predicate2, 0);
} else if (predicate1.equals(predicate2)) {
commonTerm1 = predicate1;
commonTerm2 = secondCommonTerm(subject1, subject2, 0);
} else {
return false;
}
Sentence belief = nal.getCurrentBelief();
HashMap<Term, Term> substitute = new HashMap<>();
boolean b1 = false, b2 = false;
{
Variable varDep2 = new Variable("#varDep2");
Term content = Conjunction.make(premise1, oldCompound);
if (!(content instanceof CompoundTerm))
return false;
substitute.put(commonTerm1, varDep2);
content = ((CompoundTerm)content).applySubstitute(substitute);
TruthValue truth = intersection(taskSentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.forward(truth, nal);
b1 = (nal.doublePremiseTask(content, truth, budget, false, false))!=null;
}
substitute.clear();
{
Variable varInd1 = new Variable("$varInd1");
Variable varInd2 = new Variable("$varInd2");
substitute.put(commonTerm1, varInd1);
if (commonTerm2 != null) {
substitute.put(commonTerm2, varInd2);
}
Term content = Implication.make(premise1, oldCompound);
if ((content == null) || (!(content instanceof CompoundTerm))) {
return false;
}
content = ((CompoundTerm)content).applySubstituteToCompound(substitute);
TruthValue truth;
if (premise1.equals(taskSentence.term)) {
truth = induction(belief.truth, taskSentence.truth);
} else {
truth = induction(taskSentence.truth, belief.truth);
}
BudgetValue budget = BudgetFunctions.forward(truth, nal);
b2 = nal.doublePremiseTask(content, truth, budget, false, false)!=null;
}
return b1 || b2;
}
/**
* Introduce a second independent variable into two terms with a common
* component
*
* @param term1 The first term
* @param term2 The second term
* @param index The index of the terms in their statement
*/
private static Term secondCommonTerm(Term term1, Term term2, int index) {
Term commonTerm = null;
if (index == 0) {
if ((term1 instanceof ImageExt) && (term2 instanceof ImageExt)) {
commonTerm = ((ImageExt) term1).getTheOtherComponent();
if ((commonTerm == null) || !term2.containsTermRecursively(commonTerm)) {
commonTerm = ((ImageExt) term2).getTheOtherComponent();
if ((commonTerm == null) || !term1.containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
} else if ((term1 instanceof ImageInt) && (term2 instanceof ImageInt)) {
commonTerm = ((ImageInt) term1).getTheOtherComponent();
if ((commonTerm == null) || !term2.containsTermRecursively(commonTerm)) {
commonTerm = ((ImageInt) term2).getTheOtherComponent();
if ((commonTerm == null) || !term1.containsTermRecursively(commonTerm)) {
commonTerm = null;
}
}
}
return commonTerm;
}
public static void eliminateVariableOfConditionAbductive(final int figure, final Sentence sentence, final Sentence belief, final DerivationContext nal) {
Statement T1 = (Statement) sentence.term;
Statement T2 = (Statement) belief.term;
Term S1 = T2.getSubject();
Term S2 = T1.getSubject();
Term P1 = T2.getPredicate();
Term P2 = T1.getPredicate();
HashMap<Term, Term> res1 = new HashMap<>();
HashMap<Term, Term> res2 = new HashMap<>();
HashMap<Term, Term> res3 = new HashMap<>();
HashMap<Term, Term> res4 = new HashMap<>();
if (figure == 21) {
res1.clear();
res2.clear();
Variables.findSubstitute(Symbols.VAR_INDEPENDENT, P1, S2, res1, res2); //this part is
T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies
if(T1==null) {
return;
}
T2 = (Statement) T2.applySubstitute(res1);
if(T2==null) {
return;
}
S1 = T2.getSubject();
S2 = T1.getSubject();
P1 = T2.getPredicate();
P2 = T1.getPredicate(); //update the variables because T1 and T2 may have changed
if (S1 instanceof Conjunction) {
//try to unify P2 with a component
for (final Term s1 : ((CompoundTerm) S1).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, P2, res3, res4)) {
for (Term s2 : ((CompoundTerm) S1).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (!s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
if (P2 instanceof Conjunction) {
//try to unify S1 with a component
for (final Term s1 : ((CompoundTerm) P2).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S1, res3, res4)) {
for (Term s2 : ((CompoundTerm) P2).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (!s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
}
if (figure == 12) {
res1.clear();
res2.clear();
Variables.findSubstitute(Symbols.VAR_INDEPENDENT, S1, P2, res1, res2); //this part is
T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies
if(T1==null) {
return;
}
T2 = (Statement) T2.applySubstitute(res1);
if(T2==null) {
return;
}
S1 = T2.getSubject();
S2 = T1.getSubject();
P1 = T2.getPredicate();
P2 = T1.getPredicate(); //update the variables because T1 and T2 may have changed
if (S2 instanceof Conjunction) {
//try to unify P1 with a component
for (final Term s1 : ((CompoundTerm) S2).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, P1, res3, res4)) {
for (Term s2 : ((CompoundTerm) S2).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (!s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
if (P1 instanceof Conjunction) {
//try to unify S2 with a component
for (final Term s1 : ((CompoundTerm) P1).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S2, res3, res4)) {
for (Term s2 : ((CompoundTerm) P1).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (!s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
}
if (figure == 11) {
res1.clear();
res2.clear();
Variables.findSubstitute(Symbols.VAR_INDEPENDENT, S1, S2, res1, res2); //this part is
T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies
if(T1==null) {
return;
}
T2 = (Statement) T2.applySubstitute(res1);
if(T2==null) {
return;
}
S1 = T2.getSubject();
S2 = T1.getSubject();
P1 = T2.getPredicate();
P2 = T1.getPredicate(); //update the variables because T1 and T2 may have changed
if (P1 instanceof Conjunction) {
//try to unify P2 with a component
for (final Term s1 : ((CompoundTerm) P1).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, P2, res3, res4)) {
for (Term s2 : ((CompoundTerm) P1).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if ((!s2.equals(s1)) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
if (P2 instanceof Conjunction) {
//try to unify P1 with a component
for (final Term s1 : ((CompoundTerm) P2).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, P1, res3, res4)) {
for (Term s2 : ((CompoundTerm) P2).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (!s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
}
if (figure == 22) {
res1.clear();
res2.clear();
Variables.findSubstitute(Symbols.VAR_INDEPENDENT, P1, P2, res1, res2); //this part is
T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies
if(T1==null) {
return;
}
T2 = (Statement) T2.applySubstitute(res1);
if(T2==null) {
return;
}
S1 = T2.getSubject();
S2 = T1.getSubject();
P1 = T2.getPredicate();
P2 = T1.getPredicate(); //update the variables because T1 and T2 may have changed
if (S1 instanceof Conjunction) {
//try to unify S2 with a component
for (final Term s1 : ((CompoundTerm) S1).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S2, res3, res4)) {
for (Term s2 : ((CompoundTerm) S1).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (s2!=null && !s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
if (S2 instanceof Conjunction) {
//try to unify S1 with a component
for (final Term s1 : ((CompoundTerm) S2).term) {
res3.clear();
res4.clear(); //here the dependent part matters, see example of Issue40
if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S1, res3, res4)) {
for (Term s2 : ((CompoundTerm) S2).term) {
if (!(s2 instanceof CompoundTerm)) {
continue;
}
s2 = ((CompoundTerm) s2).applySubstitute(res3);
if(s2==null || s2.hasVarIndep()) {
continue;
}
if (s2!=null && !s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) {
TruthValue truth = abduction(sentence.truth, belief.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal);
nal.doublePremiseTask(s2, truth, budget, false, false);
}
}
}
}
}
}
}
static void IntroVarSameSubjectOrPredicate(final Sentence originalMainSentence, final Sentence subSentence, final Term component, final Term content, final int index, final DerivationContext nal) {
Term T1 = originalMainSentence.term;
if (!(T1 instanceof CompoundTerm) || !(content instanceof CompoundTerm)) {
return;
}
CompoundTerm T = (CompoundTerm) T1;
CompoundTerm T2 = (CompoundTerm) content;
if ((component instanceof Inheritance && content instanceof Inheritance)
|| (component instanceof Similarity && content instanceof Similarity)) {
//CompoundTerm result = T;
if (component.equals(content)) {
return; //wouldnt make sense to create a conjunction here, would contain a statement twice
}
Variable depIndVar1 = new Variable("#depIndVar1");
Variable depIndVar2 = new Variable("#depIndVar2");
if (((Statement) component).getPredicate().equals(((Statement) content).getPredicate()) && !(((Statement) component).getPredicate() instanceof Variable)) {
CompoundTerm zw = (CompoundTerm) T.term[index];
zw = (CompoundTerm) zw.setComponent(1, depIndVar1, nal.mem());
T2 = (CompoundTerm) T2.setComponent(1, depIndVar1, nal.mem());
Conjunction res = (Conjunction) Conjunction.make(zw, T2);
T = (CompoundTerm) T.setComponent(index, res, nal.mem());
} else if (((Statement) component).getSubject().equals(((Statement) content).getSubject()) && !(((Statement) component).getSubject() instanceof Variable)) {
CompoundTerm zw = (CompoundTerm) T.term[index];
zw = (CompoundTerm) zw.setComponent(0, depIndVar2, nal.mem());
T2 = (CompoundTerm) T2.setComponent(0, depIndVar2, nal.mem());
Conjunction res = (Conjunction) Conjunction.make(zw, T2);
T = (CompoundTerm) T.setComponent(index, res, nal.mem());
}
TruthValue truth = induction(originalMainSentence.truth, subSentence.truth);
BudgetValue budget = BudgetFunctions.compoundForward(truth, T, nal);
nal.doublePremiseTask(T, truth, budget, false, false);
}
}
} |
package nars.regulation.twopoint;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JPanel;
import nars.core.EventEmitter;
import nars.core.Events.CycleEnd;
import nars.core.Memory;
import nars.core.NAR;
import nars.core.NAR.PluginState;
import nars.core.Parameters;
import nars.core.build.Default;
import nars.entity.Task;
import nars.gui.NARSwing;
import nars.io.TextOutput;
import nars.language.Term;
import nars.operator.Operation;
import nars.operator.Operator;
import nars.plugin.mental.InternalExperience;
/**
*
* @author patrick.hammer
*/
public class drawPanel extends JPanel {
final int feedbackCycles = 100;
int movement = 0;
int lastMovement = 0;
public class move extends Operator {
public move() {
super("^move");
}
@Override
protected List<Task> execute(Operation operation, Term[] args, Memory memory) {
if (args.length == 2 || args.length==3) { //left, self
prevy.add(y);
prevx.add(x);
long now = nar.time();
/* if (now - lastMovementAt < minCyclesPerMovement) {
moving();
return null;
}*/
if (args[0].toString().equals("left")) {
x -= 10;
if (x <= setpoint) {
System.out.println("BAD:\n" + operation.getTask().getExplanation());
bad();
} else {
good();
}
}
if (args[0].toString().equals("right")) {
x += 10;
if (x >= setpoint) {
System.out.println("BAD:\n" + operation.getTask().getExplanation());
bad();
} else {
good();
}
}
movement++;
// lastMovementAt = now;
}
return null;
}
}
public void beGood() {
nar.addInput("<SELF --> [good]>!");
// nar.addInput("<SELF --> [bad]>! %0%");
}
public void moving() {
// nar.addInput("<SELF --> [moving]>. :|:");
}
public void beGoodNow() {
nar.addInput("<SELF --> [good]>! :|:");
}
public void good() {
nar.addInput("<SELF --> [good]>. :|: %1.00;0.90%");
}
public void bad() {
nar.addInput("<SELF --> [good]>. :|: %0.00;0.90%");
}
public void target(String direction) {
nar.addInput("<target --> " + direction + ">. :|:");
}
NAR nar;
public drawPanel() {
// Parameters.TEMPORAL_INDUCTION_SAMPLES=0;
// Parameters.DERIVATION_DURABILITY_LEAK=0.1f;
// Parameters.DERIVATION_PRIORITY_LEAK=0.1f;
// Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF = false;
nar = new Default().build();
nar.addPlugin(new move());
/* int k=0;
for(PluginState s: nar.getPlugins()) {
if(s.plugin instanceof InternalExperience) {
nar.removePlugin(s);
break;
}
k++;
}*/
nar.on(CycleEnd.class, new EventEmitter.EventObserver() {
@Override
public void event(Class event, Object[] args) {
boolean hasMoved = (movement != lastMovement);
lastMovement = movement;
if(nar.time()%100==0) {
y+=1;
prevy.add(y);
prevx.add(x);
}
if (hasMoved || nar.time() % feedbackCycles == 0) {
if (x == setpoint)
good();
}
if(nar.time()%1000==0) {
if (x > setpoint)
target("left1"); //this way it also has to learn left <-> left1
else if (x < setpoint)
target("right1"); //and learn right <-> right1
else
target("here");
}
if(nar.time()%10000==0) {
beGood();
}
/* if (hasMoved) {
}*/
repaint();
}
});
NARSwing.themeInvert();
new NARSwing(nar);
nar.addInput("*volume=0");
nar.start(1);
intialDesire();
}
static int setpoint = 80; //220; //80
int x = 160;
int y = 10;
protected void intialDesire() {
nar.addInput("move(left)! :|: %1.00;0.50%");
nar.addInput("move(right)! :|: %1.00;0.50%");
}
List<Integer> prevx=new ArrayList<>();
List<Integer> prevy=new ArrayList<>();
private void doDrawing(Graphics g) {
//nar.step(10);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
for(int i=0;i<prevx.size();i++) {
g2d.fillRect(prevy.get(i), prevx.get(i), 10, 10);
}
g2d.fillRect(y, x, 10, 10);
g2d.setColor(Color.red);
g2d.drawLine(0, setpoint+5, 2000, setpoint+5);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.